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 = "678157acaa819d5510adfe359abb5d0392cfe461";
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
148// Codex 0.150 added these multi-agent values before our next full protocol
149// refresh. Keep every generated response namespace compatible with them.
150const Codex0150DefinitionSchemas: Record<string, Schema.Json> = {
151 CollabAgentTool: {
152 type: "string",
153 enum: [
154 "spawnAgent",
155 "sendInput",
156 "resumeAgent",
157 "wait",
158 "closeAgent",
159 "sendMessage",
160 "followupTask",
161 "interruptAgent",
162 "listAgents",
163 ],
164 },
165 CollabAgentToolCallStatus: {
166 type: "string",
167 enum: ["inProgress", "completed", "failed", "interrupted"],
168 },
169 PlanType: {
170 type: "string",
171 enum: [
172 "free",
173 "go",
174 "plus",
175 "pro",
176 "prolite",
177 "team",
178 "self_serve_business_prolite",
179 "self_serve_business_usage_based",
180 "business",
181 "ent26",
182 "enterprise_cbp_automation",
183 "enterprise_cbp_usage_based",
184 "enterprise",
185 "edu",
186 "edu_plus",
187 "edu_pro",
188 "unknown",
189 ],
190 },
191 SubAgentActivityKind: {
192 type: "string",
193 enum: ["started", "interacted", "interrupted", "completed"],
194 },
195};
196
197const getGeneratedPaths = Effect.fn("getGeneratedPaths")(function* () {
198 const path = yield* Path.Path;
199 const generatedDir = path.join(import.meta.dirname, "..", "src", "_generated");
200 return {
201 generatedDir,
202 schemaOutputPath: path.join(generatedDir, "schema.gen.ts"),
203 metaOutputPath: path.join(generatedDir, "meta.gen.ts"),
204 namespacesOutputPath: path.join(generatedDir, "namespaces.gen.ts"),
205 } satisfies GeneratedPaths;
206});
207
208const ensureGeneratedDir = Effect.fn("ensureGeneratedDir")(function* () {
209 const fs = yield* FileSystem.FileSystem;
210 const { generatedDir } = yield* getGeneratedPaths();
211 yield* fs.makeDirectory(generatedDir, { recursive: true });
212});
213
214const fetchText = Effect.fn("fetchText")(function* (url: string) {
215 return yield* HttpClientRequest.get(url).pipe(
216 HttpClientRequest.setHeader("user-agent", USER_AGENT),
217 HttpClient.execute,
218 Effect.flatMap(HttpClientResponse.filterStatusOk),
219 Effect.flatMap((okResponse) => okResponse.text),
220 Effect.mapError(
221 (cause) =>
222 new GeneratorError({
223 detail: `Failed to fetch ${url}`,
224 cause,
225 }),
226 ),
227 );
228});
229
230const fetchDirectoryEntries = Effect.fn("fetchDirectoryEntries")(function* (path: string) {
231 const raw = yield* fetchText(`${GITHUB_API_BASE}/${path}?ref=${UPSTREAM_REF}`);
232 return yield* decodeGithubContentEntries(raw);
233});
234
235function collectSchemaEntries(
236 chunk: string,
237): ReadonlyArray<{ readonly name: string; readonly code: string }> {
238 const lines = chunk
239 .split("\n")
240 .map((line) => line.trim())
241 .filter((line) => line.length > 0 && !line.startsWith("//"));
242 const entries: Array<{ name: string; code: string }> = [];
243
244 for (let index = 0; index < lines.length; index += 1) {
245 const typeLine = lines[index];
246 if (!typeLine?.startsWith("export type ")) {
247 continue;
248 }
249
250 const constLine = lines[index + 1];
251 if (!constLine?.startsWith("export const ")) {
252 throw new Error(`Malformed generator output near: ${typeLine}`);
253 }
254
255 const match = /^export type ([A-Za-z0-9_]+)/.exec(typeLine);
256 if (!match?.[1]) {
257 throw new Error(`Could not extract schema name from: ${typeLine}`);
258 }
259
260 entries.push({
261 name: match[1],
262 code: `${typeLine}\n${constLine}`,
263 });
264 index += 1;
265 }
266
267 return entries;
268}
269
270function normalizeNullableTypes(value: Schema.Json): Schema.Json {
271 if (Array.isArray(value)) {
272 return value.map(normalizeNullableTypes);
273 }
274 if (value === null || typeof value !== "object") {
275 return value;
276 }
277
278 const normalizedEntries = Object.entries(value).map(([key, child]) => [
279 key,
280 normalizeNullableTypes(child),
281 ]);
282 const normalizedObject = Object.fromEntries(normalizedEntries) as Record<string, Schema.Json>;
283 const typeValue = normalizedObject.type;
284
285 if (!Array.isArray(typeValue)) {
286 return normalizedObject;
287 }
288
289 const normalizedTypes = typeValue.filter((entry): entry is string => typeof entry === "string");
290 if (normalizedTypes.length !== typeValue.length || !normalizedTypes.includes("null")) {
291 return normalizedObject;
292 }
293
294 const nonNullTypes = normalizedTypes.filter((entry) => entry !== "null");
295 if (nonNullTypes.length !== 1) {
296 return normalizedObject;
297 }
298 const nonNullType = nonNullTypes[0]!;
299
300 const nextObject: Record<string, Schema.Json> = {};
301 for (const [key, child] of Object.entries(normalizedObject)) {
302 if (key !== "type") {
303 nextObject[key] = child;
304 }
305 }
306
307 return {
308 anyOf: [
309 {
310 ...nextObject,
311 type: nonNullType,
312 },
313 { type: "null" },
314 ],
315 };
316}
317
318function stripNullDefaults(value: Schema.Json): Schema.Json {
319 if (Array.isArray(value)) {
320 return value.map(stripNullDefaults);
321 }
322 if (value === null || typeof value !== "object") {
323 return value;
324 }
325
326 return Object.fromEntries(
327 Object.entries(value)
328 .filter(([key, child]) => !(key === "default" && child === null))
329 .map(([key, child]) => [key, stripNullDefaults(child)]),
330 ) as Schema.Json;
331}
332
333// Codex 0.153 adds async questions to agent messages. Keep older protocol
334// fields until the next full refresh, including every thread history namespace.
335function addAsyncQuestionFields(value: Schema.Json): Schema.Json {
336 if (Array.isArray(value)) {
337 return value.map(addAsyncQuestionFields);
338 }
339 if (value === null || typeof value !== "object") {
340 return value;
341 }
342 const properties = "properties" in value ? value.properties : undefined;
343 const itemType =
344 properties && typeof properties === "object" && "type" in properties
345 ? properties.type
346 : undefined;
347 if (
348 properties &&
349 typeof properties === "object" &&
350 itemType &&
351 typeof itemType === "object" &&
352 "enum" in itemType &&
353 Array.isArray(itemType.enum) &&
354 itemType.enum.includes("agentMessage")
355 ) {
356 return {
357 ...value,
358 properties: {
359 ...properties,
360 delivery: { anyOf: [{ type: "string", enum: ["async"] }, { type: "null" }] },
361 questions: {
362 anyOf: [
363 {
364 type: "array",
365 items: {
366 type: "object",
367 properties: {
368 title: { type: "string" },
369 options: {
370 anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }],
371 },
372 },
373 required: ["title"],
374 },
375 },
376 { type: "null" },
377 ],
378 },
379 },
380 };
381 }
382 return Object.fromEntries(
383 Object.entries(value).map(([key, child]) => [key, addAsyncQuestionFields(child)]),
384 );
385}
386
387function toPascalCaseMethod(method: string) {
388 return method
389 .split("/")
390 .flatMap((segment) => segment.split(/(?=[A-Z])/))
391 .flatMap((segment) => segment.split(/[-_]/))
392 .filter(Boolean)
393 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
394 .join("");
395}
396
397function parseRequestEntries(fileContents: string): ReadonlyArray<MethodEntry> {
398 const entryPattern = /\{\s*"method":\s*"([^"]+)",\s*id:\s*RequestId,\s*params:\s*([^,}]+)/g;
399 const entries: Array<MethodEntry> = [];
400 let match: RegExpExecArray | null;
401 while ((match = entryPattern.exec(fileContents)) !== null) {
402 entries.push({
403 method: match[1]!,
404 paramsType: match[2]!.trim(),
405 });
406 }
407 return entries;
408}
409
410function parseNotificationEntries(fileContents: string): ReadonlyArray<MethodEntry> {
411 const entryPattern = /\{\s*"method":\s*"([^"]+)"(?:,\s*"params":\s*([^ }]+))?\s*\}/g;
412 const entries: Array<MethodEntry> = [];
413 let match: RegExpExecArray | null;
414 while ((match = entryPattern.exec(fileContents)) !== null) {
415 entries.push({
416 method: match[1]!,
417 ...(match[2] ? { paramsType: match[2].trim() } : {}),
418 });
419 }
420 return entries;
421}
422
423function resolveSchemaTypeName(
424 rawTypeName: string,
425 generatedSchemaNames: ReadonlySet<string>,
426): string {
427 if (rawTypeName === "undefined") {
428 return "undefined";
429 }
430
431 const candidates = [
432 rawTypeName,
433 `V2${rawTypeName}`,
434 `V1${rawTypeName}`,
435 `SerdeJson${rawTypeName}`,
436 ];
437 for (const candidate of candidates) {
438 if (generatedSchemaNames.has(candidate)) {
439 return candidate;
440 }
441 }
442
443 throw new Error(`Unable to resolve schema type name: ${rawTypeName}`);
444}
445
446function resolveResponseTypeName(
447 method: string,
448 paramsType: string | undefined,
449 generatedSchemaNames: ReadonlySet<string>,
450): string {
451 const overrides: Record<string, string> = {
452 "account/logout": "LogoutAccountResponse",
453 "account/rateLimits/read": "GetAccountRateLimitsResponse",
454 "account/usage/read": "GetAccountTokenUsageResponse",
455 "account/workspaceMessages/read": "GetWorkspaceMessagesResponse",
456 "config/batchWrite": "ConfigWriteResponse",
457 "config/mcpServer/reload": "McpServerRefreshResponse",
458 "config/value/write": "ConfigWriteResponse",
459 "configRequirements/read": "ConfigRequirementsReadResponse",
460 "externalAgentConfig/import/readHistories": "ExternalAgentConfigImportHistoriesReadResponse",
461 };
462
463 const override = overrides[method];
464 if (override) {
465 return resolveSchemaTypeName(override, generatedSchemaNames);
466 }
467
468 if (paramsType && paramsType !== "undefined") {
469 const fromParams = paramsType.replace(/Params$/, "Response");
470 try {
471 return resolveSchemaTypeName(fromParams, generatedSchemaNames);
472 } catch {
473 // Fall through to method-based lookup.
474 }
475 }
476
477 return resolveSchemaTypeName(`${toPascalCaseMethod(method)}Response`, generatedSchemaNames);
478}
479
480function renderMethodConstants(constantName: string, entries: ReadonlyArray<MethodEntry>) {
481 return [
482 `export const ${constantName} = {`,
483 ...entries.map(
484 (entry) => ` ${JSON.stringify(entry.method)}: ${JSON.stringify(entry.method)},`,
485 ),
486 "} as const;",
487 "",
488 ].join("\n");
489}
490
491function renderTypeInterface(
492 interfaceName: string,
493 entries: ReadonlyArray<MethodEntry>,
494 typeName: (entry: MethodEntry) => string,
495) {
496 return [
497 `export interface ${interfaceName} {`,
498 ...entries.map((entry) => ` readonly ${JSON.stringify(entry.method)}: ${typeName(entry)};`),
499 "}",
500 "",
501 ].join("\n");
502}
503
504function renderSchemaMap(
505 constantName: string,
506 entries: ReadonlyArray<MethodEntry>,
507 typeName: (entry: MethodEntry) => string,
508) {
509 return [
510 `export const ${constantName} = {`,
511 ...entries.map((entry) => {
512 const schemaName = typeName(entry);
513 return ` ${JSON.stringify(entry.method)}: ${
514 schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`
515 },`;
516 }),
517 "} as const;",
518 "",
519 ].join("\n");
520}
521
522function renderSchemaTypeReference(schemaName: string) {
523 return schemaName === "undefined" ? "undefined" : `CodexSchema.${schemaName}`;
524}
525
526function exportNameForPath(filePath: string): string {
527 const relative = filePath.replace(/^schema\/json\//, "").replace(/\.json$/, "");
528 if (!relative.includes("/")) {
529 return relative;
530 }
531
532 const [namespace, name] = relative.split("/", 2) as [string, string];
533 const namespacePrefix = namespace
534 .split(/[^A-Za-z0-9]+/)
535 .filter(Boolean)
536 .map((segment) => segment[0]!.toUpperCase() + segment.slice(1))
537 .join("");
538 return `${namespacePrefix}${name}`;
539}
540
541function buildJsonSchemaFiles(
542 entries: ReadonlyArray<GithubContentEntry>,
543): ReadonlyArray<JsonSchemaFile> {
544 return entries
545 .filter(
546 (entry) =>
547 entry.type === "file" &&
548 entry.name.endsWith(".json") &&
549 entry.download_url !== null &&
550 !entry.name.startsWith("codex_app_server_protocol."),
551 )
552 .map((entry) => {
553 const relative = entry.path.replace(/^codex-rs\/app-server-protocol\/schema\/json\//, "");
554 const parts = relative.split("/");
555 if (parts.length > 1) {
556 return {
557 namespace: parts[0]!,
558 exportName: exportNameForPath(relative),
559 fileName: entry.name,
560 downloadUrl: entry.download_url!,
561 qualifiedName: relative.replace(/\.json$/, ""),
562 } satisfies JsonSchemaFile;
563 }
564 return {
565 exportName: exportNameForPath(relative),
566 fileName: entry.name,
567 downloadUrl: entry.download_url!,
568 qualifiedName: relative.replace(/\.json$/, ""),
569 } satisfies JsonSchemaFile;
570 });
571}
572
573function rewriteExternalRefs(
574 value: Schema.Json,
575 localDefinitionNames: ReadonlyMap<string, string>,
576 currentNamespace: string | undefined,
577 exportNameByQualifiedName: ReadonlyMap<string, string>,
578): Schema.Json {
579 if (Array.isArray(value)) {
580 return value.map((entry) =>
581 rewriteExternalRefs(entry, localDefinitionNames, currentNamespace, exportNameByQualifiedName),
582 );
583 }
584 if (value === null || typeof value !== "object") {
585 return value;
586 }
587
588 return Object.fromEntries(
589 Object.entries(value).map(([key, child]) => {
590 if (key === "$ref" && typeof child === "string" && child.startsWith("#/definitions/")) {
591 const definitionName = child.slice("#/definitions/".length);
592 const localRewrite = localDefinitionNames.get(definitionName);
593 if (localRewrite) {
594 return [key, `#/definitions/${localRewrite}`];
595 }
596
597 const candidates = [
598 ...(currentNamespace ? [`${currentNamespace}/${definitionName}`] : []),
599 definitionName,
600 definitionName.replace(/^v[12]\//, ""),
601 definitionName.replace(/^serde_json\//, ""),
602 `v2/${definitionName}`,
603 `v1/${definitionName}`,
604 `serde_json/${definitionName}`,
605 ];
606
607 const rewritten = candidates
608 .map((candidate) => exportNameByQualifiedName.get(candidate))
609 .find((candidate) => candidate !== undefined);
610
611 if (!rewritten) {
612 throw new Error(`Missing rewritten definition for ref: ${child}`);
613 }
614
615 return [key, `#/definitions/${rewritten}`];
616 }
617
618 return [
619 key,
620 rewriteExternalRefs(
621 child,
622 localDefinitionNames,
623 currentNamespace,
624 exportNameByQualifiedName,
625 ),
626 ];
627 }),
628 ) as Schema.Json;
629}
630
631const generateFiles = Effect.fn("generateFiles")(function* () {
632 yield* ensureGeneratedDir();
633
634 const [rootJsonEntries, v1JsonEntries, v2JsonEntries] = yield* Effect.all([
635 fetchDirectoryEntries("schema/json"),
636 fetchDirectoryEntries("schema/json/v1"),
637 fetchDirectoryEntries("schema/json/v2"),
638 ]);
639
640 const jsonSchemaFiles = [
641 ...buildJsonSchemaFiles(rootJsonEntries),
642 ...buildJsonSchemaFiles(v1JsonEntries),
643 ...buildJsonSchemaFiles(v2JsonEntries),
644 ].toSorted((left, right) => left.exportName.localeCompare(right.exportName));
645
646 const exportNameByQualifiedName = new Map(
647 jsonSchemaFiles.map((file) => [file.qualifiedName, file.exportName]),
648 );
649 const aggregateSchemas: Record<string, Schema.Json> = {};
650
651 for (const file of jsonSchemaFiles) {
652 const raw = yield* fetchText(file.downloadUrl);
653 const parsed = yield* decodeJsonSchemaDocument(raw);
654 const localDefinitionNames = new Map(
655 Object.keys(parsed.definitions ?? {}).map((definitionName) => [
656 definitionName,
657 `${file.exportName}__${definitionName.replace(/[^A-Za-z0-9]/g, "")}`,
658 ]),
659 );
660
661 for (const [definitionName, definitionSchema] of Object.entries(parsed.definitions ?? {})) {
662 const compatibleDefinitionSchema =
663 Codex0150DefinitionSchemas[definitionName] ?? definitionSchema;
664 aggregateSchemas[localDefinitionNames.get(definitionName)!] = stripNullDefaults(
665 normalizeNullableTypes(
666 rewriteExternalRefs(
667 compatibleDefinitionSchema,
668 localDefinitionNames,
669 file.namespace,
670 exportNameByQualifiedName,
671 ),
672 ),
673 );
674 }
675
676 const topLevelSchema: Record<string, Schema.Json> = {};
677 for (const [key, value] of Object.entries(parsed)) {
678 if (key !== "definitions") {
679 topLevelSchema[key] = value;
680 }
681 }
682
683 aggregateSchemas[file.exportName] = stripNullDefaults(
684 normalizeNullableTypes(
685 rewriteExternalRefs(
686 topLevelSchema,
687 localDefinitionNames,
688 file.namespace,
689 exportNameByQualifiedName,
690 ),
691 ),
692 );
693 }
694
695 for (const [name, schema] of Object.entries(ManualSchemas)) {
696 if (!(name in aggregateSchemas)) {
697 aggregateSchemas[name] = stripNullDefaults(normalizeNullableTypes(schema));
698 }
699 }
700
701 const generator = makeJsonSchemaGenerator();
702 for (const [name, schema] of Object.entries(aggregateSchemas).toSorted(([left], [right]) =>
703 left.localeCompare(right),
704 )) {
705 generator.addSchema(name, addAsyncQuestionFields(schema) as never);
706 }
707
708 const generatedEntries = new Map<string, string>();
709 const output = generator.generate("openapi-3.1", aggregateSchemas as never, false).trim();
710 if (output.length > 0) {
711 for (const entry of collectSchemaEntries(output)) {
712 if (!generatedEntries.has(entry.name)) {
713 generatedEntries.set(entry.name, entry.code);
714 }
715 }
716 }
717
718 const generatedSchemaNames = new Set(generatedEntries.keys());
719 const clientRequestRaw = yield* fetchText(
720 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts`,
721 );
722 const clientNotificationRaw = yield* fetchText(
723 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ClientNotification.ts`,
724 );
725 const serverRequestRaw = yield* fetchText(
726 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerRequest.ts`,
727 );
728 const serverNotificationRaw = yield* fetchText(
729 `https://raw.githubusercontent.com/openai/codex/${UPSTREAM_REF}/codex-rs/app-server-protocol/schema/typescript/ServerNotification.ts`,
730 );
731
732 const clientRequestEntries = parseRequestEntries(clientRequestRaw);
733 const clientNotificationEntries = parseNotificationEntries(clientNotificationRaw);
734 const serverRequestEntries = parseRequestEntries(serverRequestRaw);
735 const serverNotificationEntries = parseNotificationEntries(serverNotificationRaw);
736
737 const prelude = [
738 "// This file is generated by the effect-codex-app-server package. Do not edit manually.",
739 `// Upstream protocol ref: ${UPSTREAM_REF}`,
740 "",
741 ];
742
743 const schemaOutput = [
744 ...prelude,
745 'import * as Schema from "effect/Schema";',
746 "",
747 [...generatedEntries.values()].join("\n\n"),
748 "",
749 ].join("\n");
750
751 const metaOutput = [
752 ...prelude,
753 'import * as CodexSchema from "./schema.gen.ts";',
754 "",
755 renderMethodConstants("CLIENT_REQUEST_METHODS", clientRequestEntries),
756 renderMethodConstants("CLIENT_NOTIFICATION_METHODS", clientNotificationEntries),
757 renderMethodConstants("SERVER_REQUEST_METHODS", serverRequestEntries),
758 renderMethodConstants("SERVER_NOTIFICATION_METHODS", serverNotificationEntries),
759 "export type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;",
760 "export type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;",
761 "export type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;",
762 "export type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;",
763 "",
764 renderTypeInterface("ClientRequestParamsByMethod", clientRequestEntries, (entry) =>
765 renderSchemaTypeReference(
766 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
767 ),
768 ),
769 renderTypeInterface("ClientRequestResponsesByMethod", clientRequestEntries, (entry) =>
770 renderSchemaTypeReference(
771 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
772 ),
773 ),
774 renderTypeInterface("ClientNotificationParamsByMethod", clientNotificationEntries, (entry) =>
775 renderSchemaTypeReference(
776 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
777 ),
778 ),
779 renderTypeInterface("ServerRequestParamsByMethod", serverRequestEntries, (entry) =>
780 renderSchemaTypeReference(
781 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
782 ),
783 ),
784 renderTypeInterface("ServerRequestResponsesByMethod", serverRequestEntries, (entry) =>
785 renderSchemaTypeReference(
786 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
787 ),
788 ),
789 renderTypeInterface("ServerNotificationParamsByMethod", serverNotificationEntries, (entry) =>
790 renderSchemaTypeReference(
791 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
792 ),
793 ),
794 renderSchemaMap("CLIENT_REQUEST_PARAMS", clientRequestEntries, (entry) =>
795 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
796 ),
797 renderSchemaMap("CLIENT_REQUEST_RESPONSES", clientRequestEntries, (entry) =>
798 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
799 ),
800 renderSchemaMap("CLIENT_NOTIFICATION_PARAMS", clientNotificationEntries, (entry) =>
801 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
802 ),
803 renderSchemaMap("SERVER_REQUEST_PARAMS", serverRequestEntries, (entry) =>
804 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
805 ),
806 renderSchemaMap("SERVER_REQUEST_RESPONSES", serverRequestEntries, (entry) =>
807 resolveResponseTypeName(entry.method, entry.paramsType, generatedSchemaNames),
808 ),
809 renderSchemaMap("SERVER_NOTIFICATION_PARAMS", serverNotificationEntries, (entry) =>
810 resolveSchemaTypeName(entry.paramsType ?? "undefined", generatedSchemaNames),
811 ),
812 ].join("\n");
813
814 const namespaceGroups = new Map<string, Array<JsonSchemaFile>>();
815 for (const file of jsonSchemaFiles) {
816 if (!file.namespace) {
817 continue;
818 }
819 const current = namespaceGroups.get(file.namespace) ?? [];
820 current.push(file);
821 namespaceGroups.set(file.namespace, current);
822 }
823
824 const namespacesOutput = [
825 ...prelude,
826 'import * as CodexSchema from "./schema.gen.ts";',
827 "",
828 ...[...namespaceGroups.entries()]
829 .toSorted(([left], [right]) => left.localeCompare(right))
830 .map(([namespace, files]) => {
831 const constantName = namespace.replace(/[^A-Za-z0-9]/g, "");
832 return [
833 `export const ${constantName} = {`,
834 ...files
835 .toSorted((left, right) => left.fileName.localeCompare(right.fileName))
836 .map(
837 (file) =>
838 ` ${JSON.stringify(file.fileName.replace(/\.json$/, ""))}: CodexSchema.${file.exportName},`,
839 ),
840 "} as const;",
841 "",
842 ].join("\n");
843 }),
844 ].join("\n");
845
846 const fs = yield* FileSystem.FileSystem;
847 const { generatedDir, metaOutputPath, namespacesOutputPath, schemaOutputPath } =
848 yield* getGeneratedPaths();
849 yield* fs.writeFileString(schemaOutputPath, schemaOutput);
850 yield* fs.writeFileString(metaOutputPath, metaOutput);
851 yield* fs.writeFileString(namespacesOutputPath, namespacesOutput);
852
853 yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
854
855 yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
856 Effect.flatMap((spawner) =>
857 spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
858 ),
859 Effect.flatMap((child) => child.exitCode),
860 Effect.tap((code) =>
861 code === 0
862 ? Effect.void
863 : Effect.fail(
864 new GeneratorError({
865 detail: `vp fmt failed with exit code ${code}`,
866 }),
867 ),
868 ),
869 );
870});
871
872generateFiles().pipe(
873 Effect.scoped,
874 Effect.provide(
875 Layer.mergeAll(
876 Logger.layer([Logger.consolePretty()]),
877 NodeServices.layer,
878 FetchHttpClient.layer,
879 ),
880 ),
881 NodeRuntime.runMain,
882);