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