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