返回 CodeWhale
mod.rs
1 use serde_json::{Map, Value};
2 use std::collections::{BTreeMap, BTreeSet};
3 use std::fmt::Write as _;
4
5 pub const MANIFEST_PATH: &str = "contract/codex-v2.json";
6 pub const PINNED_SCHEMA_PATH: &str = "tests/pinned/codex/codex_app_server_protocol.schemas.json";
7
8 pub struct Outputs {
9 pub files: Vec<(&'static str, String)>,
10 }
11
12 pub fn generate(manifest: &str, pinned: &str) -> Result<Outputs, String> {
13 let manifest: Value = serde_json::from_str(manifest).map_err(|error| error.to_string())?;
14 let pinned: Value = serde_json::from_str(pinned).map_err(|error| error.to_string())?;
15 let contract = Contract::load(&manifest, &pinned)?;
16 let mut builder = Builder::new(&contract);
17 for root in contract.roots()? {
18 builder.def(&root)?;
19 }
20 for field in &contract.extension_fields {
21 builder.def(&field.owner)?;
22 }
23 let items = builder.finish()?;
24 let rust = RustOut::new(&items);
25 Ok(Outputs {
26 files: vec![
27 ("src/methods.rs", methods_rs(&contract)?),
28 ("src/v2.rs", rust.render(&contract)?),
29 ("METHODS.md", methods_md(&contract, &items)),
30 (
31 "schema/json/codex-v2.schema.json",
32 schema_json(&contract, &builder.raw)?,
33 ),
34 (
35 "schema/typescript/codex-v2.d.ts",
36 typescript(&contract, &items)?,
37 ),
38 ],
39 })
40 }
41
42 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
43 pub enum Kind {
44 ClientRequest,
45 ClientNotification,
46 ServerRequest,
47 ServerNotification,
48 }
49
50 impl Kind {
51 const ALL: [Kind; 4] = [
52 Kind::ClientRequest,
53 Kind::ClientNotification,
54 Kind::ServerRequest,
55 Kind::ServerNotification,
56 ];
57
58 fn key(self) -> &'static str {
59 match self {
60 Kind::ClientRequest => "clientRequests",
61 Kind::ClientNotification => "clientNotifications",
62 Kind::ServerRequest => "serverRequests",
63 Kind::ServerNotification => "serverNotifications",
64 }
65 }
66
67 fn section(self) -> &'static str {
68 match self {
69 Kind::ClientRequest => "Client requests",
70 Kind::ClientNotification => "Client notifications",
71 Kind::ServerRequest => "Server requests",
72 Kind::ServerNotification => "Server notifications",
73 }
74 }
75
76 fn enum_name(self) -> &'static str {
77 match self {
78 Kind::ClientRequest => "ClientRequestMethod",
79 Kind::ClientNotification => "ClientNotificationMethod",
80 Kind::ServerRequest => "ServerRequestMethod",
81 Kind::ServerNotification => "ServerNotificationMethod",
82 }
83 }
84
85 fn table_name(self) -> &'static str {
86 match self {
87 Kind::ClientRequest => "CLIENT_REQUESTS",
88 Kind::ClientNotification => "CLIENT_NOTIFICATIONS",
89 Kind::ServerRequest => "SERVER_REQUESTS",
90 Kind::ServerNotification => "SERVER_NOTIFICATIONS",
91 }
92 }
93
94 fn union(self) -> &'static str {
95 match self {
96 Kind::ClientRequest => "ClientRequest",
97 Kind::ClientNotification => "ClientNotification",
98 Kind::ServerRequest => "ServerRequest",
99 Kind::ServerNotification => "ServerNotification",
100 }
101 }
102 }
103
104 pub struct Row {
105 pub method: String,
106 pub tier: String,
107 pub status: String,
108 pub basis: String,
109 pub recommended: Option<String>,
110 pub variant: Option<String>,
111 pub params: Option<String>,
112 pub response: Option<String>,
113 }
114
115 impl Row {
116 fn selected(&self) -> bool {
117 matches!(self.tier.as_str(), "A" | "B")
118 }
119 }
120
121 struct ExtensionField {
122 owner: Key,
123 field: String,
124 schema: Value,
125 }
126
127 struct Contract<'a> {
128 manifest: &'a Value,
129 pinned: &'a Value,
130 rows: BTreeMap<Kind, Vec<Row>>,
131 extension_fields: Vec<ExtensionField>,
132 }
133
134 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
135 struct Key {
136 namespace: String,
137 name: String,
138 }
139
140 impl Key {
141 fn parse(reference: &str) -> Result<Key, String> {
142 let path = reference
143 .strip_prefix("#/definitions/")
144 .ok_or_else(|| format!("unsupported $ref {reference}"))?;
145 Ok(match path.split_once('/') {
146 Some((namespace, name)) => Key {
147 namespace: namespace.into(),
148 name: name.into(),
149 },
150 None => Key {
151 namespace: String::new(),
152 name: path.into(),
153 },
154 })
155 }
156
157 fn reference(&self) -> String {
158 if self.namespace.is_empty() {
159 format!("#/definitions/{}", self.name)
160 } else {
161 format!("#/definitions/{}/{}", self.namespace, self.name)
162 }
163 }
164 }
165
166 fn text(value: &Value, field: &str) -> Result<String, String> {
167 value[field]
168 .as_str()
169 .map(str::to_owned)
170 .ok_or_else(|| format!("manifest field {field} missing in {value}"))
171 }
172
173 fn optional_text(value: &Value, field: &str) -> Option<String> {
174 value[field].as_str().map(str::to_owned)
175 }
176
177 impl<'a> Contract<'a> {
178 fn load(manifest: &'a Value, pinned: &'a Value) -> Result<Self, String> {
179 let mut rows = BTreeMap::new();
180 for kind in Kind::ALL {
181 let mut list = Vec::new();
182 for row in manifest["methods"][kind.key()]
183 .as_array()
184 .ok_or_else(|| format!("manifest has no {}", kind.key()))?
185 {
186 list.push(Row {
187 method: text(row, "method")?,
188 tier: text(row, "tier")?,
189 status: text(row, "status")?,
190 basis: text(row, "basis")?,
191 recommended: optional_text(row, "recommended"),
192 variant: optional_text(row, "variant"),
193 params: optional_text(row, "params"),
194 response: optional_text(row, "response"),
195 });
196 }
197 rows.insert(kind, list);
198 }
199 let mut extension_fields = Vec::new();
200 for field in manifest["extensions"]["fields"]
201 .as_array()
202 .ok_or("manifest has no extension fields")?
203 {
204 let owner = text(field, "type")?;
205 extension_fields.push(ExtensionField {
206 owner: Key {
207 namespace: "v2".into(),
208 name: owner,
209 },
210 field: text(field, "field")?,
211 schema: field["schema"].clone(),
212 });
213 }
214 Ok(Contract {
215 manifest,
216 pinned,
217 rows,
218 extension_fields,
219 })
220 }
221
222 fn schema(&self, key: &Key) -> Result<&'a Value, String> {
223 let found = match key.namespace.as_str() {
224 "" => self.pinned["definitions"].get(&key.name),
225 "v2" => self.pinned["definitions"]["v2"].get(&key.name),
226 "codewhale" => self.manifest["extensions"]["definitions"].get(&key.name),
227 other => return Err(format!("unknown namespace {other}")),
228 };
229 found.ok_or_else(|| format!("no definition {}", key.reference()))
230 }
231
232 fn named(&self, name: &str) -> Result<Key, String> {
233 for namespace in ["v2", ""] {
234 let key = Key {
235 namespace: namespace.into(),
236 name: name.into(),
237 };
238 if self.schema(&key).is_ok() {
239 return Ok(key);
240 }
241 }
242 Err(format!("pinned export has no type {name}"))
243 }
244
245 fn union_params(&self, kind: Kind, method: &str) -> Result<Option<Key>, String> {
246 let union = &self.pinned["definitions"][kind.union()];
247 for variant in union["oneOf"]
248 .as_array()
249 .ok_or_else(|| format!("pinned {} is not a union", kind.union()))?
250 {
251 if variant["properties"]["method"]["enum"][0] == method {
252 return match variant["properties"]["params"]["$ref"].as_str() {
253 Some(reference) => Ok(Some(Key::parse(reference)?)),
254 None => Ok(None),
255 };
256 }
257 }
258 Err(format!("pinned {} has no {method}", kind.union()))
259 }
260
261 fn selected(&self, kind: Kind) -> impl Iterator<Item = &Row> {
262 self.rows[&kind].iter().filter(|row| row.selected())
263 }
264
265 fn params_key(&self, kind: Kind, row: &Row) -> Result<Option<Key>, String> {
266 let key = self.union_params(kind, &row.method)?;
267 match (&key, &row.params) {
268 (Some(key), Some(name)) if &key.name == name => Ok(Some(key.clone())),
269 (None, None) => Ok(None),
270 _ => Err(format!(
271 "{}: manifest params {:?} disagree with the pinned union {:?}",
272 row.method, row.params, key
273 )),
274 }
275 }
276
277 fn response_key(&self, row: &Row) -> Result<Key, String> {
278 self.named(
279 row.response
280 .as_deref()
281 .ok_or_else(|| format!("{} has no response type", row.method))?,
282 )
283 }
284
285 fn roots(&self) -> Result<Vec<Key>, String> {
286 let mut roots = Vec::new();
287 for kind in Kind::ALL {
288 for row in self.selected(kind) {
289 if row.variant.is_none() {
290 return Err(format!("{} has no variant name", row.method));
291 }
292 if let Some(key) = self.params_key(kind, row)? {
293 roots.push(key);
294 }
295 if matches!(kind, Kind::ClientRequest | Kind::ServerRequest) {
296 roots.push(self.response_key(row)?);
297 }
298 }
299 }
300 if let Some(definitions) = self.manifest["extensions"]["definitions"].as_object() {
301 for name in definitions.keys() {
302 if self.named(name).is_ok() {
303 return Err(format!(
304 "Codewhale extension {name} shadows a pinned Codex type"
305 ));
306 }
307 roots.push(Key {
308 namespace: "codewhale".into(),
309 name: name.clone(),
310 });
311 }
312 }
313 Ok(roots)
314 }
315 }
316
317 #[derive(Clone, Debug, PartialEq)]
318 pub enum Ty {
319 String,
320 Bool,
321 Int(&'static str),
322 Json,
323 JsonObject,
324 Named(String),
325 Vec(Box<Ty>),
326 Map(Box<Ty>),
327 NullableMap(Box<Ty>),
328 }
329
330 #[derive(Clone, Debug)]
331 pub struct Field {
332 pub wire: String,
333 pub ty: Ty,
334 pub nullable: bool,
335 pub required: bool,
336 pub default: Option<Value>,
337 pub flatten: bool,
338 }
339
340 #[derive(Clone, Debug)]
341 pub enum External {
342 Unit(String),
343 Newtype(String, Ty),
344 Struct(String, Vec<Field>),
345 }
346
347 #[derive(Clone, Debug)]
348 pub enum Shape {
349 Alias(Ty),
350 Struct {
351 fields: Vec<Field>,
352 deny_unknown: bool,
353 additional: bool,
354 },
355 StringEnum(Vec<String>),
356 Tagged {
357 tag: String,
358 variants: Vec<(String, Vec<Field>)>,
359 },
360 External(Vec<External>),
361 Untagged(Vec<(String, Ty)>),
362 }
363
364 #[derive(Clone, Debug)]
365 pub struct Item {
366 pub name: String,
367 pub shape: Shape,
368 }
369
370 struct Builder<'a> {
371 contract: &'a Contract<'a>,
372 items: BTreeMap<String, Item>,
373 origin: BTreeMap<String, Key>,
374 raw: BTreeMap<String, Value>,
375 }
376
377 fn stripped(schema: &Value) -> Value {
378 match schema {
379 Value::Object(object) => Value::Object(
380 object
381 .iter()
382 .filter(|(key, _)| !matches!(key.as_str(), "description" | "title" | "$schema"))
383 .map(|(key, value)| (key.clone(), stripped(value)))
384 .collect(),
385 ),
386 Value::Array(values) => Value::Array(values.iter().map(stripped).collect()),
387 other => other.clone(),
388 }
389 }
390
391 fn types_of(schema: &Value) -> (Vec<String>, bool) {
392 match &schema["type"] {
393 Value::String(single) => (vec![single.clone()], false),
394 Value::Array(list) => {
395 let names: Vec<String> = list
396 .iter()
397 .filter_map(Value::as_str)
398 .filter(|name| *name != "null")
399 .map(str::to_owned)
400 .collect();
401 let nullable = list.iter().any(|name| name == "null");
402 (names, nullable)
403 }
404 _ => (Vec::new(), false),
405 }
406 }
407
408 fn is_null_schema(schema: &Value) -> bool {
409 schema["type"] == "null"
410 }
411
412 fn single_tag(schema: &Value) -> Option<(String, String)> {
413 let properties = schema["properties"].as_object()?;
414 let mut found = None;
415 for (name, property) in properties {
416 let values = property["enum"].as_array();
417 if property["type"] == "string" && values.is_some_and(|values| values.len() == 1) {
418 if found.is_some() {
419 return None;
420 }
421 found = Some((name.clone(), values?[0].as_str()?.to_owned()));
422 }
423 }
424 found
425 }
426
427 fn string_enum_values(schema: &Value) -> Option<Vec<String>> {
428 if schema["type"] != "string" {
429 return None;
430 }
431 schema["enum"]
432 .as_array()?
433 .iter()
434 .map(|value| value.as_str().map(str::to_owned))
435 .collect()
436 }
437
438 fn single_key_object(schema: &Value) -> Option<(String, &Value)> {
439 let properties = schema["properties"].as_object()?;
440 if properties.len() != 1 {
441 return None;
442 }
443 let (name, property) = properties.iter().next()?;
444 let required = schema["required"].as_array()?;
445 if required.len() == 1 && required[0] == name.as_str() {
446 Some((name.clone(), property))
447 } else {
448 None
449 }
450 }
451
452 impl<'a> Builder<'a> {
453 fn new(contract: &'a Contract<'a>) -> Self {
454 Builder {
455 contract,
456 items: BTreeMap::new(),
457 origin: BTreeMap::new(),
458 raw: BTreeMap::new(),
459 }
460 }
461
462 fn def(&mut self, key: &Key) -> Result<String, String> {
463 let name = key.name.clone();
464 if let Some(previous) = self.origin.get(&name) {
465 if previous == key {
466 return Ok(name);
467 }
468 let before = stripped(self.contract.schema(previous)?);
469 let after = stripped(self.contract.schema(key)?);
470 if before == after {
471 return Ok(name);
472 }
473 return Err(format!(
474 "{} and {} share a name with different shapes",
475 previous.reference(),
476 key.reference()
477 ));
478 }
479 self.origin.insert(name.clone(), key.clone());
480 let schema = self.contract.schema(key)?;
481 self.raw.insert(name.clone(), schema.clone());
482 let shape = self.shape(&name, schema, &key.namespace)?;
483 self.items.insert(
484 name.clone(),
485 Item {
486 name: name.clone(),
487 shape,
488 },
489 );
490 Ok(name)
491 }
492
493 fn inline(&mut self, name: String, schema: &Value, namespace: &str) -> Result<String, String> {
494 if self.items.contains_key(&name) || self.origin.contains_key(&name) {
495 return Err(format!("inline type {name} collides with a definition"));
496 }
497 self.origin.insert(
498 name.clone(),
499 Key {
500 namespace: "inline".into(),
501 name: name.clone(),
502 },
503 );
504 let shape = self.shape(&name, schema, namespace)?;
505 self.items.insert(
506 name.clone(),
507 Item {
508 name: name.clone(),
509 shape,
510 },
511 );
512 Ok(name)
513 }
514
515 fn reference(&mut self, reference: &str, namespace: &str) -> Result<String, String> {
516 let mut key = Key::parse(reference)?;
517 if key.namespace == "inline" {
518 key.namespace = namespace.into();
519 }
520 self.def(&key)
521 }
522
523 fn ty(&mut self, context: &str, schema: &Value, namespace: &str) -> Result<(Ty, bool), String> {
524 if schema == &Value::Bool(true) {
525 return Ok((Ty::Json, false));
526 }
527 let object = schema
528 .as_object()
529 .ok_or_else(|| format!("{context}: unsupported schema {schema}"))?;
530 if let Some(reference) = object.get("$ref").and_then(Value::as_str) {
531 return Ok((Ty::Named(self.reference(reference, namespace)?), false));
532 }
533 if let Some(all) = object.get("allOf").and_then(Value::as_array) {
534 if all.len() != 1 {
535 return Err(format!("{context}: allOf with {} members", all.len()));
536 }
537 return self.ty(context, &all[0], namespace);
538 }
539 for union in ["anyOf", "oneOf"] {
540 if let Some(members) = object.get(union).and_then(Value::as_array) {
541 let present: Vec<&Value> = members
542 .iter()
543 .filter(|member| !is_null_schema(member))
544 .collect();
545 let nullable = present.len() != members.len();
546 if present.len() == 1 {
547 let (ty, inner) = self.ty(context, present[0], namespace)?;
548 return Ok((ty, nullable || inner));
549 }
550 let mut copy = object.clone();
551 copy.insert(
552 union.into(),
553 Value::Array(present.into_iter().cloned().collect()),
554 );
555 let name = self.inline(context.into(), &Value::Object(copy), namespace)?;
556 return Ok((Ty::Named(name), nullable));
557 }
558 }
559 let (types, nullable) = types_of(schema);
560 if types.is_empty() {
561 if object
562 .keys()
563 .all(|key| matches!(key.as_str(), "description" | "title" | "default"))
564 {
565 return Ok((Ty::Json, false));
566 }
567 return Err(format!("{context}: untyped schema {schema}"));
568 }
569 if types.len() != 1 {
570 return Ok((Ty::Json, nullable));
571 }
572 let ty = match types[0].as_str() {
573 "string" => {
574 if object.contains_key("enum") {
575 Ty::Named(self.inline(context.into(), &without_null(schema), namespace)?)
576 } else {
577 Ty::String
578 }
579 }
580 "boolean" => Ty::Bool,
581 "integer" => Ty::Int(match object.get("format").and_then(Value::as_str) {
582 None | Some("int64") => "i64",
583 Some("int32") => "i32",
584 Some("uint8") => "u8",
585 Some("uint16") => "u16",
586 Some("uint32") => "u32",
587 Some("uint64") | Some("uint") => "u64",
588 Some(other) => return Err(format!("{context}: integer format {other}")),
589 }),
590 "array" => {
591 let items = object
592 .get("items")
593 .ok_or_else(|| format!("{context}: array without items"))?;
594 let (item, item_nullable) = self.ty(&format!("{context}Item"), items, namespace)?;
595 if item_nullable {
596 return Err(format!("{context}: nullable array items"));
597 }
598 Ty::Vec(Box::new(item))
599 }
600 "object" => {
601 if object.contains_key("properties") {
602 Ty::Named(self.inline(context.into(), &without_null(schema), namespace)?)
603 } else {
604 match object.get("additionalProperties") {
605 Some(Value::Object(_)) => {
606 let (value, value_nullable) = self.ty(
607 &format!("{context}Value"),
608 &object["additionalProperties"],
609 namespace,
610 )?;
611 if value_nullable {
612 Ty::NullableMap(Box::new(value))
613 } else {
614 Ty::Map(Box::new(value))
615 }
616 }
617 _ => Ty::JsonObject,
618 }
619 }
620 }
621 other => return Err(format!("{context}: type {other}")),
622 };
623 Ok((ty, nullable))
624 }
625
626 fn fields(
627 &mut self,
628 owner: &str,
629 schema: &Value,
630 namespace: &str,
631 skip: Option<&str>,
632 ) -> Result<Vec<Field>, String> {
633 let required: BTreeSet<String> = schema["required"]
634 .as_array()
635 .map(|names| {
636 names
637 .iter()
638 .filter_map(Value::as_str)
639 .map(str::to_owned)
640 .collect()
641 })
642 .unwrap_or_default();
643 let mut fields = Vec::new();
644 if let Some(properties) = schema["properties"].as_object() {
645 for (wire, property) in properties {
646 if Some(wire.as_str()) == skip {
647 continue;
648 }
649 let context = format!("{owner}{}", pascal(wire));
650 let (ty, nullable) = self.ty(&context, property, namespace)?;
651 let default = property
652 .get("default")
653 .filter(|value| !value.is_null())
654 .cloned();
655 fields.push(Field {
656 wire: wire.clone(),
657 ty,
658 nullable,
659 required: required.contains(wire),
660 default,
661 flatten: false,
662 });
663 }
664 }
665 if schema.get("properties").is_some() {
666 for union in ["oneOf", "anyOf"] {
667 if let Some(members) = schema[union].as_array() {
668 let name = format!("{owner}Kind");
669 if self.origin.contains_key(&name) {
670 return Err(format!("flattened union {name} collides with a definition"));
671 }
672 self.origin.insert(
673 name.clone(),
674 Key {
675 namespace: "inline".into(),
676 name: name.clone(),
677 },
678 );
679 let shape = self.union(&name, members, namespace)?;
680 self.items.insert(
681 name.clone(),
682 Item {
683 name: name.clone(),
684 shape,
685 },
686 );
687 fields.push(Field {
688 wire: "kind".into(),
689 ty: Ty::Named(name),
690 nullable: false,
691 required: true,
692 default: None,
693 flatten: true,
694 });
695 }
696 }
697 }
698 for name in &required {
699 if Some(name.as_str()) != skip && !fields.iter().any(|field| &field.wire == name) {
700 return Err(format!("{owner}: required {name} has no property"));
701 }
702 }
703 Ok(fields)
704 }
705
706 fn shape(&mut self, name: &str, schema: &Value, namespace: &str) -> Result<Shape, String> {
707 for union in ["oneOf", "anyOf"] {
708 if let Some(members) = schema[union].as_array()
709 && schema.get("properties").is_none()
710 {
711 return self.union(name, members, namespace);
712 }
713 }
714 if let Some(values) = string_enum_values(schema) {
715 return Ok(Shape::StringEnum(values));
716 }
717 let (types, _) = types_of(schema);
718 if types.len() == 1 && types[0] == "object" && schema.get("properties").is_some() {
719 let mut fields = self.fields(name, schema, namespace, None)?;
720 for extension in &self.contract.extension_fields {
721 if extension.owner.name == name {
722 let (ty, nullable) = self.ty(
723 &format!("{name}{}", pascal(&extension.field)),
724 &extension.schema,
725 namespace,
726 )?;
727 fields.push(Field {
728 wire: extension.field.clone(),
729 ty,
730 nullable,
731 required: false,
732 default: None,
733 flatten: false,
734 });
735 }
736 }
737 let flattened = fields.iter().any(|field| field.flatten);
738 return Ok(Shape::Struct {
739 fields,
740 deny_unknown: schema["additionalProperties"] == false && !flattened,
741 additional: schema["additionalProperties"] == true,
742 });
743 }
744 if types.len() == 1 && types[0] == "object" && schema.get("additionalProperties").is_none()
745 {
746 return Ok(Shape::Struct {
747 fields: Vec::new(),
748 deny_unknown: false,
749 additional: false,
750 });
751 }
752 let (ty, nullable) = self.ty(&format!("{name}Inner"), schema, namespace)?;
753 if nullable {
754 return Err(format!("{name}: nullable alias"));
755 }
756 Ok(Shape::Alias(ty))
757 }
758
759 fn union(&mut self, name: &str, members: &[Value], namespace: &str) -> Result<Shape, String> {
760 if members
761 .iter()
762 .all(|member| string_enum_values(member).is_some())
763 {
764 let mut values = Vec::new();
765 for member in members {
766 values.extend(string_enum_values(member).unwrap_or_default());
767 }
768 return Ok(Shape::StringEnum(values));
769 }
770 let tags: Vec<Option<(String, String)>> = members.iter().map(single_tag).collect();
771 if let Some(Some((tag, _))) = tags.first()
772 && tags
773 .iter()
774 .all(|found| found.as_ref().is_some_and(|(name, _)| name == tag))
775 {
776 let mut variants = Vec::new();
777 for (member, found) in members.iter().zip(&tags) {
778 let (_, value) = found.clone().unwrap_or_default();
779 let owner = format!("{name}{}", pascal(&value));
780 let fields = self.fields(&owner, member, namespace, Some(tag))?;
781 variants.push((value, fields));
782 }
783 return Ok(Shape::Tagged {
784 tag: tag.clone(),
785 variants,
786 });
787 }
788 if members.iter().all(|member| {
789 string_enum_values(member).is_some() || single_key_object(member).is_some()
790 }) {
791 let mut variants = Vec::new();
792 for member in members {
793 if let Some(values) = string_enum_values(member) {
794 variants.extend(values.into_iter().map(External::Unit));
795 continue;
796 }
797 let (key, payload) = single_key_object(member).ok_or("external variant")?;
798 let owner = format!("{name}{}", pascal(&key));
799 if payload["type"] == "object" && payload.get("properties").is_some() {
800 let fields = self.fields(&owner, payload, namespace, None)?;
801 variants.push(External::Struct(key, fields));
802 } else {
803 let (ty, nullable) = self.ty(&owner, payload, namespace)?;
804 if nullable {
805 return Err(format!("{owner}: nullable external payload"));
806 }
807 variants.push(External::Newtype(key, ty));
808 }
809 }
810 return Ok(Shape::External(variants));
811 }
812 let mut variants = Vec::new();
813 for (index, member) in members.iter().enumerate() {
814 let (ty, nullable) = self.ty(&format!("{name}Variant{index}"), member, namespace)?;
815 if nullable {
816 return Err(format!("{name}: nullable untagged member"));
817 }
818 let titled = member["title"]
819 .as_str()
820 .map(|title| title.strip_suffix(name).unwrap_or(title).to_owned())
821 .filter(|title| !title.is_empty());
822 let label = match &ty {
823 _ if titled.is_some() => titled.clone().unwrap_or_default(),
824 Ty::Json => "Other".to_owned(),
825 Ty::String => "String".to_owned(),
826 Ty::Int(_) => "Integer".to_owned(),
827 Ty::Bool => "Bool".to_owned(),
828 Ty::Vec(item) => match item.as_ref() {
829 Ty::String => "Strings".to_owned(),
830 Ty::Named(inner) => format!("{inner}List"),
831 _ => "List".to_owned(),
832 },
833 Ty::Named(inner) => inner.clone(),
834 _ => format!("Variant{index}"),
835 };
836 if variants.iter().any(|(existing, _)| existing == &label) {
837 return Err(format!("{name}: duplicate untagged label {label}"));
838 }
839 variants.push((label, ty));
840 }
841 Ok(Shape::Untagged(variants))
842 }
843
844 fn finish(&self) -> Result<Vec<Item>, String> {
845 Ok(self.items.values().cloned().collect())
846 }
847 }
848
849 fn without_null(schema: &Value) -> Value {
850 let mut copy = schema.clone();
851 if let Some(Value::Array(list)) = copy.get("type").cloned() {
852 let present: Vec<Value> = list.into_iter().filter(|name| name != "null").collect();
853 if present.len() == 1 {
854 copy["type"] = present[0].clone();
855 }
856 }
857 copy
858 }
859
860 pub fn pascal(value: &str) -> String {
861 let mut out = String::new();
862 let mut upper = true;
863 for character in value.chars() {
864 if character.is_ascii_alphanumeric() {
865 if upper {
866 out.extend(character.to_uppercase());
867 upper = false;
868 } else {
869 out.push(character);
870 }
871 } else {
872 upper = true;
873 }
874 }
875 if out.starts_with(|character: char| character.is_ascii_digit()) {
876 out.insert(0, 'V');
877 }
878 out
879 }
880
881 pub fn snake(value: &str) -> String {
882 let mut out = String::new();
883 let characters: Vec<char> = value.chars().collect();
884 for (index, character) in characters.iter().enumerate() {
885 if character.is_ascii_uppercase() {
886 let previous_lower = index > 0
887 && (characters[index - 1].is_ascii_lowercase()
888 || characters[index - 1].is_ascii_digit());
889 let next_lower = characters
890 .get(index + 1)
891 .is_some_and(|next| next.is_ascii_lowercase());
892 let previous_upper = index > 0 && characters[index - 1].is_ascii_uppercase();
893 if previous_lower || (previous_upper && next_lower) {
894 out.push('_');
895 }
896 out.push(character.to_ascii_lowercase());
897 } else if character.is_ascii_alphanumeric() {
898 out.push(*character);
899 } else {
900 out.push('_');
901 }
902 }
903 out
904 }
905
906 const KEYWORDS: &[&str] = &[
907 "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
908 "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
909 "self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
910 "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
911 "override", "priv", "typeof", "unsized", "virtual", "yield", "try", "gen",
912 ];
913
914 fn ident(wire: &str) -> String {
915 let name = snake(wire);
916 if KEYWORDS.contains(&name.as_str()) {
917 format!("r#{name}")
918 } else {
919 name
920 }
921 }
922
923 struct RustOut<'a> {
924 items: &'a [Item],
925 boxed: BTreeSet<(String, String)>,
926 }
927
928 fn direct_refs(ty: &Ty, out: &mut Vec<String>) {
929 if let Ty::Named(name) = ty {
930 out.push(name.clone());
931 }
932 }
933
934 fn item_edges(item: &Item) -> Vec<String> {
935 fn fields(list: &[Field], out: &mut Vec<String>) {
936 for field in list {
937 direct_refs(&field.ty, out);
938 }
939 }
940 let mut out = Vec::new();
941 match &item.shape {
942 Shape::Struct { fields: list, .. } => fields(list, &mut out),
943 Shape::Tagged { variants, .. } => {
944 for (_, list) in variants {
945 fields(list, &mut out);
946 }
947 }
948 Shape::External(variants) => {
949 for variant in variants {
950 match variant {
951 External::Unit(_) => {}
952 External::Newtype(_, ty) => direct_refs(ty, &mut out),
953 External::Struct(_, list) => fields(list, &mut out),
954 }
955 }
956 }
957 Shape::Untagged(variants) => {
958 for (_, ty) in variants {
959 direct_refs(ty, &mut out);
960 }
961 }
962 Shape::Alias(ty) => direct_refs(ty, &mut out),
963 Shape::StringEnum(_) => {}
964 }
965 out
966 }
967
968 fn strongly_connected(items: &[Item]) -> BTreeMap<String, usize> {
969 let edges: BTreeMap<String, Vec<String>> = items
970 .iter()
971 .map(|item| (item.name.clone(), item_edges(item)))
972 .collect();
973 struct State<'a> {
974 edges: &'a BTreeMap<String, Vec<String>>,
975 index: BTreeMap<String, usize>,
976 low: BTreeMap<String, usize>,
977 stack: Vec<String>,
978 on_stack: BTreeSet<String>,
979 next: usize,
980 component: BTreeMap<String, usize>,
981 components: usize,
982 }
983 fn visit(state: &mut State<'_>, node: &str) {
984 state.index.insert(node.into(), state.next);
985 state.low.insert(node.into(), state.next);
986 state.next += 1;
987 state.stack.push(node.into());
988 state.on_stack.insert(node.into());
989 let targets = state.edges.get(node).cloned().unwrap_or_default();
990 for target in targets {
991 if !state.edges.contains_key(&target) {
992 continue;
993 }
994 if !state.index.contains_key(&target) {
995 visit(state, &target);
996 let low = state.low[node].min(state.low[&target]);
997 state.low.insert(node.into(), low);
998 } else if state.on_stack.contains(&target) {
999 let low = state.low[node].min(state.index[&target]);
1000 state.low.insert(node.into(), low);
1001 }
1002 }
1003 if state.low[node] == state.index[node] {
1004 while let Some(member) = state.stack.pop() {
1005 state.on_stack.remove(&member);
1006 state.component.insert(member.clone(), state.components);
1007 if member == node {
1008 break;
1009 }
1010 }
1011 state.components += 1;
1012 }
1013 }
1014 let mut state = State {
1015 edges: &edges,
1016 index: BTreeMap::new(),
1017 low: BTreeMap::new(),
1018 stack: Vec::new(),
1019 on_stack: BTreeSet::new(),
1020 next: 0,
1021 component: BTreeMap::new(),
1022 components: 0,
1023 };
1024 for name in edges.keys() {
1025 if !state.index.contains_key(name) {
1026 visit(&mut state, name);
1027 }
1028 }
1029 state.component
1030 }
1031
1032 fn quote(value: &str) -> String {
1033 serde_json::to_string(value).unwrap_or_default()
1034 }
1035
1036 impl<'a> RustOut<'a> {
1037 fn new(items: &'a [Item]) -> Self {
1038 let component = strongly_connected(items);
1039 let mut boxed = BTreeSet::new();
1040 for item in items {
1041 for target in item_edges(item) {
1042 if component.contains_key(&item.name)
1043 && component.get(&item.name) == component.get(&target)
1044 {
1045 boxed.insert((item.name.clone(), target));
1046 }
1047 }
1048 }
1049 RustOut { items, boxed }
1050 }
1051
1052 fn ty(&self, owner: &str, ty: &Ty) -> String {
1053 match ty {
1054 Ty::String => "String".into(),
1055 Ty::Bool => "bool".into(),
1056 Ty::Int(name) => (*name).into(),
1057 Ty::Json => "Value".into(),
1058 Ty::JsonObject => "Map<String, Value>".into(),
1059 Ty::Named(name) => {
1060 if self.boxed.contains(&(owner.to_owned(), name.clone())) {
1061 format!("Box<{name}>")
1062 } else {
1063 name.clone()
1064 }
1065 }
1066 Ty::Vec(item) => format!("Vec<{}>", self.ty("", item)),
1067 Ty::Map(value) => format!("BTreeMap<String, {}>", self.ty("", value)),
1068 Ty::NullableMap(value) => format!("BTreeMap<String, Option<{}>>", self.ty("", value)),
1069 }
1070 }
1071
1072 fn trivial_default(value: &Value) -> bool {
1073 matches!(value, Value::Bool(false))
1074 || value.as_i64() == Some(0)
1075 || value.as_array().is_some_and(Vec::is_empty)
1076 }
1077
1078 fn literal(&self, owner: &str, ty: &Ty, value: &Value) -> Result<String, String> {
1079 Ok(match (ty, value) {
1080 (Ty::Bool, Value::Bool(flag)) => flag.to_string(),
1081 (Ty::Int(_), Value::Number(number)) => number.to_string(),
1082 (Ty::String, Value::String(text)) => format!("{}.to_owned()", quote(text)),
1083 (Ty::Vec(item), Value::Array(values)) => {
1084 let parts: Result<Vec<String>, String> = values
1085 .iter()
1086 .map(|value| self.literal("", item, value))
1087 .collect();
1088 format!("vec![{}]", parts?.join(", "))
1089 }
1090 (Ty::Named(name), Value::String(text)) => {
1091 let item = self
1092 .items
1093 .iter()
1094 .find(|item| &item.name == name)
1095 .ok_or_else(|| format!("default names unknown type {name}"))?;
1096 match &item.shape {
1097 Shape::StringEnum(values) if values.contains(text) => {
1098 let built = format!("{name}::{}", pascal(text));
1099 if self.boxed.contains(&(owner.to_owned(), name.clone())) {
1100 format!("Box::new({built})")
1101 } else {
1102 built
1103 }
1104 }
1105 Shape::External(variants)
1106 if variants.iter().any(
1107 |variant| matches!(variant, External::Unit(unit) if unit == text),
1108 ) =>
1109 {
1110 format!("{name}::{}", pascal(text))
1111 }
1112 _ => return Err(format!("default {text} does not name a {name} variant")),
1113 }
1114 }
1115 _ => return Err(format!("unsupported default {value} for {ty:?}")),
1116 })
1117 }
1118
1119 fn fields(
1120 &self,
1121 owner: &str,
1122 fields: &[Field],
1123 visibility: &str,
1124 indent: &str,
1125 defaults: &mut String,
1126 ) -> Result<String, String> {
1127 let mut out = String::new();
1128 let mut seen = BTreeSet::new();
1129 for field in fields {
1130 let name = ident(&field.wire);
1131 if !seen.insert(name.clone()) {
1132 return Err(format!("{owner}: field {name} twice"));
1133 }
1134 let base = self.ty(owner, &field.ty);
1135 if field.flatten {
1136 let _ = writeln!(
1137 out,
1138 "{indent}#[serde(flatten)]\n{indent}{visibility}{name}: {base},"
1139 );
1140 continue;
1141 }
1142 let mut attributes = Vec::new();
1143 if name.trim_start_matches("r#") != field.wire {
1144 attributes.push(format!("rename = {}", quote(&field.wire)));
1145 }
1146 let ty = match (&field.default, field.required) {
1147 (Some(default), false) => {
1148 let ty = if field.nullable {
1149 format!("Option<{base}>")
1150 } else {
1151 base.clone()
1152 };
1153 if !field.nullable && Self::trivial_default(default) {
1154 attributes.push("default".into());
1155 } else {
1156 let mut function =
1157 format!("default_{}_{}", snake(owner), snake(&field.wire));
1158 while defaults.contains(&format!("fn {function}()")) {
1159 function.push('_');
1160 }
1161 let literal = self.literal(owner, &field.ty, default)?;
1162 let body = if field.nullable {
1163 format!("Some({literal})")
1164 } else {
1165 literal
1166 };
1167 let _ = write!(defaults, "fn {function}() -> {ty} {{\n {body}\n}}\n\n");
1168 attributes.push(format!("default = {}", quote(&function)));
1169 }
1170 ty
1171 }
1172 (_, true) => {
1173 if field.nullable {
1174 format!("Option<{base}>")
1175 } else {
1176 base
1177 }
1178 }
1179 (None, false) => {
1180 attributes.push("default".into());
1181 attributes.push("skip_serializing_if = \"Option::is_none\"".into());
1182 format!("Option<{base}>")
1183 }
1184 };
1185 if !attributes.is_empty() {
1186 let _ = writeln!(out, "{indent}#[serde({})]", attributes.join(", "));
1187 }
1188 let _ = writeln!(out, "{indent}{visibility}{name}: {ty},");
1189 }
1190 Ok(out)
1191 }
1192
1193 fn derives(&self, item: &Item) -> String {
1194 let mut derives = vec!["Debug", "Clone", "PartialEq", "Eq"];
1195 match &item.shape {
1196 Shape::StringEnum(_) => derives.extend(["Copy", "Hash", "PartialOrd", "Ord"]),
1197 Shape::Struct { fields, .. }
1198 if fields
1199 .iter()
1200 .all(|field| !field.required && field.default.is_none()) =>
1201 {
1202 derives.push("Default")
1203 }
1204 _ => {}
1205 }
1206 derives.extend(["Serialize", "Deserialize"]);
1207 format!(
1208 "#[derive({})]\n#[cfg_attr(feature = \"schema\", derive(schemars::JsonSchema))]\n",
1209 derives.join(", ")
1210 )
1211 }
1212
1213 fn item(&self, item: &Item, defaults: &mut String) -> Result<String, String> {
1214 let name = &item.name;
1215 let mut out = String::new();
1216 match &item.shape {
1217 Shape::Alias(ty) => {
1218 let _ = writeln!(out, "pub type {name} = {};", self.ty(name, ty));
1219 }
1220 Shape::Struct {
1221 fields,
1222 deny_unknown,
1223 additional,
1224 } => {
1225 out.push_str(&self.derives(item));
1226 if *deny_unknown {
1227 out.push_str("#[serde(deny_unknown_fields)]\n");
1228 }
1229 let _ = writeln!(out, "pub struct {name} {{");
1230 out.push_str(&self.fields(name, fields, "pub ", " ", defaults)?);
1231 if *additional {
1232 out.push_str(
1233 " #[serde(flatten)]\n pub additional: Map<String, Value>,\n",
1234 );
1235 }
1236 out.push_str("}\n");
1237 }
1238 Shape::StringEnum(values) => {
1239 out.push_str(&self.derives(item));
1240 let _ = writeln!(out, "pub enum {name} {{");
1241 let mut seen = BTreeSet::new();
1242 for value in values {
1243 let variant = pascal(value);
1244 if !seen.insert(variant.clone()) {
1245 return Err(format!("{name}: variant {variant} twice"));
1246 }
1247 let _ = writeln!(
1248 out,
1249 " #[serde(rename = {})]\n {variant},",
1250 quote(value)
1251 );
1252 }
1253 out.push_str("}\n");
1254 }
1255 Shape::Tagged { tag, variants } => {
1256 out.push_str(&self.derives(item));
1257 let _ = writeln!(out, "#[serde(tag = {})]", quote(tag));
1258 let _ = writeln!(out, "pub enum {name} {{");
1259 let mut seen = BTreeSet::new();
1260 for (value, fields) in variants {
1261 let variant = pascal(value);
1262 if !seen.insert(variant.clone()) {
1263 return Err(format!("{name}: variant {variant} twice"));
1264 }
1265 let _ = writeln!(out, " #[serde(rename = {})]", quote(value));
1266 if fields.is_empty() {
1267 let _ = writeln!(out, " {variant} {{}},");
1268 } else {
1269 let _ = writeln!(out, " {variant} {{");
1270 out.push_str(&self.fields(name, fields, "", " ", defaults)?);
1271 out.push_str(" },\n");
1272 }
1273 }
1274 out.push_str("}\n");
1275 }
1276 Shape::External(variants) => {
1277 out.push_str(&self.derives(item));
1278 let _ = writeln!(out, "pub enum {name} {{");
1279 let mut seen = BTreeSet::new();
1280 for variant in variants {
1281 let (wire, body) = match variant {
1282 External::Unit(wire) => (wire, String::new()),
1283 External::Newtype(wire, ty) => (wire, format!("({})", self.ty(name, ty))),
1284 External::Struct(wire, fields) => (
1285 wire,
1286 format!(
1287 " {{\n{} }}",
1288 self.fields(name, fields, "", " ", defaults)?
1289 ),
1290 ),
1291 };
1292 let label = pascal(wire);
1293 if !seen.insert(label.clone()) {
1294 return Err(format!("{name}: variant {label} twice"));
1295 }
1296 let _ = writeln!(
1297 out,
1298 " #[serde(rename = {})]\n {label}{body},",
1299 quote(wire)
1300 );
1301 }
1302 out.push_str("}\n");
1303 }
1304 Shape::Untagged(variants) => {
1305 out.push_str(&self.derives(item));
1306 out.push_str("#[serde(untagged)]\n");
1307 let _ = writeln!(out, "pub enum {name} {{");
1308 for (label, ty) in variants {
1309 let _ = writeln!(out, " {label}({}),", self.ty(name, ty));
1310 }
1311 out.push_str("}\n");
1312 }
1313 }
1314 Ok(out)
1315 }
1316
1317 fn render(&self, contract: &Contract<'_>) -> Result<String, String> {
1318 let mut out = String::new();
1319 out.push_str("#![allow(clippy::large_enum_variant, clippy::enum_variant_names)]\n\n");
1320 out.push_str("use serde::{Deserialize, Serialize};\nuse serde_json::{Map, Value};\nuse std::collections::BTreeMap;\n\n");
1321 out.push_str("pub use crate::methods::{\n ClientNotificationMethod, ClientRequestMethod, ServerNotificationMethod, ServerRequestMethod,\n};\n\n");
1322 let mut defaults = String::new();
1323 for item in self.items {
1324 out.push_str(&self.item(item, &mut defaults)?);
1325 out.push('\n');
1326 }
1327 out.push_str(&defaults);
1328 out.push_str(&envelopes(contract)?);
1329 out.push_str("pub const TYPE_NAMES: &[&str] = &[\n");
1330 for item in self.items {
1331 let _ = writeln!(out, " {},", quote(&item.name));
1332 }
1333 out.push_str("];\n\n");
1334 out.push_str("pub fn round_trip(type_name: &str, value: Value) -> Option<Result<Value, serde_json::Error>> {\n fn again<T: serde::de::DeserializeOwned + Serialize>(value: Value) -> Result<Value, serde_json::Error> {\n serde_json::to_value(serde_json::from_value::<T>(value)?)\n }\n Some(match type_name {\n");
1335 for item in self.items {
1336 let _ = writeln!(
1337 out,
1338 " {} => again::<{}>(value),",
1339 quote(&item.name),
1340 item.name
1341 );
1342 }
1343 out.push_str(" _ => return None,\n })\n}\n");
1344 Ok(out)
1345 }
1346 }
1347
1348 fn envelopes(contract: &Contract<'_>) -> Result<String, String> {
1349 let mut out = String::new();
1350 let enum_of = |out: &mut String,
1351 name: &str,
1352 kind: Kind,
1353 payload: &dyn Fn(&Row) -> Result<Option<String>, String>|
1354 -> Result<(), String> {
1355 let _ = writeln!(
1356 out,
1357 "#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n#[serde(tag = \"method\", content = \"params\")]\npub enum {name} {{"
1358 );
1359 for row in contract.selected(kind) {
1360 let variant = row.variant.clone().unwrap_or_default();
1361 let _ = writeln!(out, " #[serde(rename = {})]", quote(&row.method));
1362 match payload(row)? {
1363 Some(ty) => {
1364 let _ = writeln!(out, " {variant}({ty}),");
1365 }
1366 None => {
1367 let _ = writeln!(out, " {variant},");
1368 }
1369 }
1370 }
1371 out.push_str("}\n\n");
1372 let method_enum = kind.enum_name();
1373 let _ = writeln!(
1374 out,
1375 "impl {name} {{\n pub fn method(&self) -> {method_enum} {{\n match self {{"
1376 );
1377 for row in contract.selected(kind) {
1378 let variant = row.variant.clone().unwrap_or_default();
1379 let pattern = if payload(row)?.is_some() { "(_)" } else { "" };
1380 let _ = writeln!(
1381 out,
1382 " Self::{variant}{pattern} => {method_enum}::{variant},"
1383 );
1384 }
1385 out.push_str(" }\n }\n}\n\n");
1386 Ok(())
1387 };
1388 enum_of(
1389 &mut out,
1390 "ClientRequestParams",
1391 Kind::ClientRequest,
1392 &|row| Ok(row.params.clone()),
1393 )?;
1394 enum_of(
1395 &mut out,
1396 "ClientNotification",
1397 Kind::ClientNotification,
1398 &|row| Ok(row.params.clone()),
1399 )?;
1400 enum_of(
1401 &mut out,
1402 "ServerRequestParams",
1403 Kind::ServerRequest,
1404 &|row| Ok(row.params.clone()),
1405 )?;
1406 enum_of(
1407 &mut out,
1408 "ServerNotification",
1409 Kind::ServerNotification,
1410 &|row| Ok(row.params.clone()),
1411 )?;
1412 for (name, kind) in [
1413 ("ClientResponse", Kind::ClientRequest),
1414 ("ServerRequestResponse", Kind::ServerRequest),
1415 ] {
1416 let method_enum = kind.enum_name();
1417 let _ = writeln!(
1418 out,
1419 "#[derive(Debug, Clone, PartialEq, Eq, Serialize)]\n#[serde(untagged)]\npub enum {name} {{"
1420 );
1421 for row in contract.selected(kind) {
1422 let _ = writeln!(
1423 out,
1424 " {}({}),",
1425 row.variant.clone().unwrap_or_default(),
1426 row.response.clone().unwrap_or_default()
1427 );
1428 }
1429 let _ = writeln!(
1430 out,
1431 "}}\n\nimpl {name} {{\n pub fn method(&self) -> {method_enum} {{\n match self {{"
1432 );
1433 for row in contract.selected(kind) {
1434 let variant = row.variant.clone().unwrap_or_default();
1435 let _ = writeln!(
1436 out,
1437 " Self::{variant}(_) => {method_enum}::{variant},"
1438 );
1439 }
1440 let _ = writeln!(
1441 out,
1442 " }}\n }}\n\n pub fn decode(method: {method_enum}, result: Value) -> Result<Self, serde_json::Error> {{\n Ok(match method {{"
1443 );
1444 for row in contract.selected(kind) {
1445 let variant = row.variant.clone().unwrap_or_default();
1446 let _ = writeln!(
1447 out,
1448 " {method_enum}::{variant} => Self::{variant}(serde_json::from_value(result)?),"
1449 );
1450 }
1451 out.push_str(" })\n }\n}\n\n");
1452 }
1453 Ok(out)
1454 }
1455
1456 fn methods_rs(contract: &Contract<'_>) -> Result<String, String> {
1457 let manifest = contract.manifest;
1458 let mut out = String::new();
1459 let _ = writeln!(
1460 out,
1461 "pub const CONTRACT_NAME: &str = {};\npub const CONTRACT_VERSION: u32 = {};\npub const CODEX_PROTOCOL_TAG: &str = {};\npub const CODEX_PROTOCOL_COMMIT: &str = {};\n",
1462 quote(manifest["contract"].as_str().unwrap_or_default()),
1463 manifest["version"].as_u64().ok_or("manifest version")?,
1464 quote(manifest["upstream"]["tag"].as_str().unwrap_or_default()),
1465 quote(manifest["upstream"]["commit"].as_str().unwrap_or_default()),
1466 );
1467 out.push_str("pub mod error_code {\n");
1468 for error in manifest["errors"].as_array().ok_or("manifest errors")? {
1469 let _ = writeln!(
1470 out,
1471 " pub const {}: i64 = {};",
1472 error["name"].as_str().ok_or("error name")?,
1473 error["code"].as_i64().ok_or("error code")?
1474 );
1475 }
1476 out.push_str("}\n\n");
1477 out.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum Tier {\n A,\n B,\n}\n\n");
1478 out.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum Disposition {\n Selected(Tier),\n C,\n Undecided,\n}\n\nimpl Disposition {\n pub const fn selected(self) -> bool {\n matches!(self, Self::Selected(_))\n }\n}\n\n");
1479 for kind in Kind::ALL {
1480 let name = kind.enum_name();
1481 let rows: Vec<&Row> = contract.selected(kind).collect();
1482 let _ = writeln!(
1483 out,
1484 "#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]\npub enum {name} {{"
1485 );
1486 for row in &rows {
1487 let _ = writeln!(out, " {},", row.variant.clone().unwrap_or_default());
1488 }
1489 let _ = writeln!(
1490 out,
1491 "}}\n\nimpl {name} {{\n pub const ALL: &'static [Self] = &["
1492 );
1493 for row in &rows {
1494 let _ = writeln!(
1495 out,
1496 " Self::{},",
1497 row.variant.clone().unwrap_or_default()
1498 );
1499 }
1500 out.push_str(
1501 " ];\n\n pub const fn method(self) -> &'static str {\n match self {\n",
1502 );
1503 for row in &rows {
1504 let _ = writeln!(
1505 out,
1506 " Self::{} => {},",
1507 row.variant.clone().unwrap_or_default(),
1508 quote(&row.method)
1509 );
1510 }
1511 out.push_str(
1512 " }\n }\n\n pub const fn tier(self) -> Tier {\n match self {\n",
1513 );
1514 for row in &rows {
1515 let _ = writeln!(
1516 out,
1517 " Self::{} => Tier::{},",
1518 row.variant.clone().unwrap_or_default(),
1519 row.tier
1520 );
1521 }
1522 out.push_str(" }\n }\n\n pub const fn params_type(self) -> Option<&'static str> {\n match self {\n");
1523 for row in &rows {
1524 let value = match &row.params {
1525 Some(params) => format!("Some({})", quote(params)),
1526 None => "None".into(),
1527 };
1528 let _ = writeln!(
1529 out,
1530 " Self::{} => {value},",
1531 row.variant.clone().unwrap_or_default()
1532 );
1533 }
1534 out.push_str(" }\n }\n\n");
1535 if matches!(kind, Kind::ClientRequest | Kind::ServerRequest) {
1536 out.push_str(
1537 " pub const fn response_type(self) -> &'static str {\n match self {\n",
1538 );
1539 for row in &rows {
1540 let _ = writeln!(
1541 out,
1542 " Self::{} => {},",
1543 row.variant.clone().unwrap_or_default(),
1544 quote(row.response.as_deref().unwrap_or_default())
1545 );
1546 }
1547 out.push_str(" }\n }\n\n");
1548 }
1549 out.push_str(
1550 " pub fn from_method(method: &str) -> Option<Self> {\n match method {\n",
1551 );
1552 for row in &rows {
1553 let _ = writeln!(
1554 out,
1555 " {} => Some(Self::{}),",
1556 quote(&row.method),
1557 row.variant.clone().unwrap_or_default()
1558 );
1559 }
1560 out.push_str(" _ => None,\n }\n }\n}\n\n");
1561 let _ = writeln!(
1562 out,
1563 "impl std::fmt::Display for {name} {{\n fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{\n formatter.write_str(self.method())\n }}\n}}\n"
1564 );
1565 let _ = writeln!(
1566 out,
1567 "impl serde::Serialize for {name} {{\n fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {{\n serializer.serialize_str(self.method())\n }}\n}}\n"
1568 );
1569 let _ = writeln!(
1570 out,
1571 "impl<'de> serde::Deserialize<'de> for {name} {{\n fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {{\n let method = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;\n Self::from_method(&method)\n .ok_or_else(|| serde::de::Error::custom(format!(\"unknown method: {{method}}\")))\n }}\n}}\n"
1572 );
1573 }
1574 for kind in Kind::ALL {
1575 let _ = writeln!(
1576 out,
1577 "pub const {}: &[(&str, Disposition)] = &[",
1578 kind.table_name()
1579 );
1580 for row in &contract.rows[&kind] {
1581 let disposition = match row.tier.as_str() {
1582 "A" => "Disposition::Selected(Tier::A)",
1583 "B" => "Disposition::Selected(Tier::B)",
1584 "C" => "Disposition::C",
1585 "undecided" => "Disposition::Undecided",
1586 other => return Err(format!("{}: tier {other}", row.method)),
1587 };
1588 let _ = writeln!(out, " ({}, {disposition}),", quote(&row.method));
1589 }
1590 out.push_str("];\n\n");
1591 }
1592 out.push_str("fn lookup(table: &[(&str, Disposition)], method: &str) -> Option<Disposition> {\n table\n .iter()\n .find(|(name, _)| *name == method)\n .map(|(_, disposition)| *disposition)\n}\n\n");
1593 for (function, kind) in [
1594 ("client_request_disposition", Kind::ClientRequest),
1595 ("client_notification_disposition", Kind::ClientNotification),
1596 ("server_request_disposition", Kind::ServerRequest),
1597 ("server_notification_disposition", Kind::ServerNotification),
1598 ] {
1599 let _ = writeln!(
1600 out,
1601 "pub fn {function}(method: &str) -> Option<Disposition> {{\n lookup({}, method)\n}}\n",
1602 kind.table_name()
1603 );
1604 }
1605 out.push_str("pub fn unselected_request_error(method: &str) -> Option<i64> {\n match client_request_disposition(method) {\n Some(Disposition::Selected(_)) => None,\n _ => Some(error_code::METHOD_NOT_FOUND),\n }\n}\n");
1606 Ok(out)
1607 }
1608
1609 fn cell(value: &str) -> String {
1610 value.replace('|', "\\|")
1611 }
1612
1613 fn methods_md(contract: &Contract<'_>, items: &[Item]) -> String {
1614 let manifest = contract.manifest;
1615 let mut out = String::new();
1616 let tag = manifest["upstream"]["tag"].as_str().unwrap_or_default();
1617 let commit = manifest["upstream"]["commit"].as_str().unwrap_or_default();
1618 let _ = writeln!(out, "# Codex App Server method inventory\n");
1619 let _ = writeln!(
1620 out,
1621 "Generated from `contract/codex-v2.json` (contract `{}` version {}) and the pinned Codex `{tag}` export (commit `{commit}`) by `cargo run -p codewhale-app-server-protocol --bin codewhale-codex-contract -- --write`. Edit the manifest, never this file; `tests/contract.rs` fails when they drift. The method sets are the unmodified export members under `tests/pinned/codex/`.\n",
1622 manifest["contract"].as_str().unwrap_or_default(),
1623 manifest["version"]
1624 );
1625 out.push_str("- **A**: required for 0.10.3 Codex parity.\n- **B**: service methods, required for 0.10.3.\n- **C**: out of scope, for the reason given.\n- **undecided**: the 0.10.3 parity bar does not settle it yet. The last column carries a recommended tier for the founder to confirm; until then it is handled exactly like Tier C.\n\n");
1626 out.push_str("Status: `implemented` means a Codex-shaped handler is on main (response goldens are not yet checked); `partial` means the Codex method name dispatches to the legacy shape; `missing` means no handler; `method-not-found` means the dispatcher answers `-32601`; `never-sent` means the server never emits it. The stable export is the scope: methods that exist only in the experimental export are not listed. A complete inventory or typed shape is not a handler: status, not tier, says what main dispatches.\n\n");
1627 out.push_str("## Dispatch rules\n\n| Tier | Rule |\n| --- | --- |\n");
1628 if let Some(rules) = manifest["dispatch"].as_object() {
1629 for (tier, rule) in rules {
1630 let _ = writeln!(
1631 out,
1632 "| {tier} | {} |",
1633 cell(rule.as_str().unwrap_or_default())
1634 );
1635 }
1636 }
1637 out.push('\n');
1638 let mut counts = BTreeMap::new();
1639 for kind in Kind::ALL {
1640 let _ = writeln!(out, "## {}\n", kind.section());
1641 out.push_str("| Method | Tier | Status | Basis | Recommended | Params | Result |\n| --- | --- | --- | --- | --- | --- | --- |\n");
1642 for row in &contract.rows[&kind] {
1643 *counts
1644 .entry((kind.section(), row.tier.clone()))
1645 .or_insert(0usize) += 1;
1646 let shown = |value: &Option<String>| match value {
1647 Some(name) if row.selected() => format!("`{name}`"),
1648 Some(name) => format!("{name} (untyped)"),
1649 None => String::new(),
1650 };
1651 let _ = writeln!(
1652 out,
1653 "| `{}` | {} | {} | {} | {} | {} | {} |",
1654 row.method,
1655 row.tier,
1656 row.status,
1657 cell(&row.basis),
1658 row.recommended.clone().unwrap_or_default(),
1659 shown(&row.params),
1660 shown(&row.response),
1661 );
1662 }
1663 out.push('\n');
1664 }
1665 out.push_str(
1666 "## Totals\n\n| Kind | A | B | C | undecided |\n| --- | --- | --- | --- | --- |\n",
1667 );
1668 for kind in Kind::ALL {
1669 let count = |tier: &str| {
1670 counts
1671 .get(&(kind.section(), tier.to_owned()))
1672 .copied()
1673 .unwrap_or(0)
1674 };
1675 let _ = writeln!(
1676 out,
1677 "| {} | {} | {} | {} | {} |",
1678 kind.section(),
1679 count("A"),
1680 count("B"),
1681 count("C"),
1682 count("undecided")
1683 );
1684 }
1685 let _ = writeln!(
1686 out,
1687 "\nTyped definitions generated into `src/v2.rs`: {}.\n",
1688 items.len()
1689 );
1690 out.push_str("## Errors\n\nCodex envelopes carry no `jsonrpc` member. ACP keeps its own JSON-RPC 2.0 envelope and is not this contract.\n\n| Name | Code | Meaning |\n| --- | --- | --- |\n");
1691 if let Some(errors) = manifest["errors"].as_array() {
1692 for error in errors {
1693 let _ = writeln!(
1694 out,
1695 "| `{}` | {} | {} |",
1696 error["name"].as_str().unwrap_or_default(),
1697 error["code"],
1698 cell(error["meaning"].as_str().unwrap_or_default())
1699 );
1700 }
1701 }
1702 out.push_str("\n## Codewhale extensions\n\nThese ride on Codex shapes without changing any pinned field. The pinned `Thread` schema allows additional properties, so a Codex client ignores the fields. Codewhale notifications live under `codewhale/`, because Codex already uses `thread/environment/*` for its own environments. Extension shapes are declared under `extensions.definitions` in the manifest and generated with the Codex types; none carries a credential.\n\n| Name | Kind | Tier | Status | Shape |\n| --- | --- | --- | --- | --- |\n");
1703 if let Some(rows) = manifest["extensions"]["rows"].as_array() {
1704 for row in rows {
1705 let _ = writeln!(
1706 out,
1707 "| `{}` | {} | {} | {} | {} |",
1708 row["name"].as_str().unwrap_or_default(),
1709 row["kind"].as_str().unwrap_or_default(),
1710 row["tier"].as_str().unwrap_or_default(),
1711 row["status"].as_str().unwrap_or_default(),
1712 cell(row["shape"].as_str().unwrap_or_default())
1713 );
1714 }
1715 }
1716 out
1717 }
1718
1719 fn rewrite_refs(value: &Value) -> Value {
1720 match value {
1721 Value::Object(object) => {
1722 let mut copy = Map::new();
1723 for (key, child) in object {
1724 if key == "$ref"
1725 && let Some(reference) = child.as_str()
1726 && let Ok(parsed) = Key::parse(reference)
1727 {
1728 copy.insert(
1729 key.clone(),
1730 Value::String(format!("#/definitions/{}", parsed.name)),
1731 );
1732 } else if key != "$schema" {
1733 copy.insert(key.clone(), rewrite_refs(child));
1734 }
1735 }
1736 Value::Object(copy)
1737 }
1738 Value::Array(values) => Value::Array(values.iter().map(rewrite_refs).collect()),
1739 other => other.clone(),
1740 }
1741 }
1742
1743 fn schema_json(contract: &Contract<'_>, raw: &BTreeMap<String, Value>) -> Result<String, String> {
1744 let manifest = contract.manifest;
1745 let mut definitions = Map::new();
1746 for (name, schema) in raw {
1747 definitions.insert(name.clone(), rewrite_refs(schema));
1748 }
1749 for extension in &contract.extension_fields {
1750 if let Some(Value::Object(properties)) = definitions
1751 .get_mut(&extension.owner.name)
1752 .and_then(|owner| owner.get_mut("properties"))
1753 {
1754 properties.insert(extension.field.clone(), rewrite_refs(&extension.schema));
1755 }
1756 }
1757 let mut methods = Map::new();
1758 for kind in Kind::ALL {
1759 let mut list = Map::new();
1760 for row in contract.selected(kind) {
1761 let mut entry = Map::new();
1762 entry.insert("tier".into(), Value::String(row.tier.clone()));
1763 if let Some(params) = &row.params {
1764 entry.insert(
1765 "params".into(),
1766 Value::String(format!("#/definitions/{params}")),
1767 );
1768 }
1769 if let Some(response) = &row.response {
1770 entry.insert(
1771 "result".into(),
1772 Value::String(format!("#/definitions/{response}")),
1773 );
1774 }
1775 list.insert(row.method.clone(), Value::Object(entry));
1776 }
1777 methods.insert(kind.key().into(), Value::Object(list));
1778 }
1779 let document = serde_json::json!({
1780 "$schema": "http://json-schema.org/draft-07/schema#",
1781 "title": manifest["contract"],
1782 "x-contract-version": manifest["version"],
1783 "x-upstream": {"tag": manifest["upstream"]["tag"], "commit": manifest["upstream"]["commit"]},
1784 "x-methods": methods,
1785 "definitions": definitions,
1786 });
1787 serde_json::to_string_pretty(&document)
1788 .map(|text| text + "\n")
1789 .map_err(|error| error.to_string())
1790 }
1791
1792 fn ts_ty(ty: &Ty) -> String {
1793 match ty {
1794 Ty::String => "string".into(),
1795 Ty::Bool => "boolean".into(),
1796 Ty::Int(_) => "number".into(),
1797 Ty::Json => "unknown".into(),
1798 Ty::JsonObject => "{ [key: string]: unknown }".into(),
1799 Ty::Named(name) => name.clone(),
1800 Ty::Vec(item) => format!("Array<{}>", ts_ty(item)),
1801 Ty::Map(value) => format!("{{ [key: string]: {} }}", ts_ty(value)),
1802 Ty::NullableMap(value) => format!("{{ [key: string]: {} | null }}", ts_ty(value)),
1803 }
1804 }
1805
1806 fn ts_object(fields: &[Field], extra: Option<&str>) -> String {
1807 let mut members = ts_fields(fields);
1808 if let Some(extra) = extra {
1809 if !members.is_empty() {
1810 members.push_str("; ");
1811 }
1812 members.push_str(extra);
1813 }
1814 let base = if members.is_empty() {
1815 "Record<string, never>".to_owned()
1816 } else {
1817 format!("{{ {members} }}")
1818 };
1819 let flattened: Vec<String> = fields
1820 .iter()
1821 .filter(|field| field.flatten)
1822 .map(|field| ts_ty(&field.ty))
1823 .collect();
1824 if flattened.is_empty() {
1825 base
1826 } else if members.is_empty() {
1827 flattened.join(" & ")
1828 } else {
1829 format!("{base} & {}", flattened.join(" & "))
1830 }
1831 }
1832
1833 fn ts_fields(fields: &[Field]) -> String {
1834 fields
1835 .iter()
1836 .filter(|field| !field.flatten)
1837 .map(|field| {
1838 let optional = if field.required { "" } else { "?" };
1839 let nullable = if field.nullable { " | null" } else { "" };
1840 format!(
1841 "{}{optional}: {}{nullable}",
1842 quote(&field.wire),
1843 ts_ty(&field.ty)
1844 )
1845 })
1846 .collect::<Vec<_>>()
1847 .join("; ")
1848 }
1849
1850 fn typescript(contract: &Contract<'_>, items: &[Item]) -> Result<String, String> {
1851 let mut out = String::new();
1852 for item in items {
1853 let name = &item.name;
1854 let body = match &item.shape {
1855 Shape::Alias(ty) => ts_ty(ty),
1856 Shape::Struct {
1857 fields, additional, ..
1858 } => ts_object(fields, additional.then_some("[key: string]: unknown")),
1859 Shape::StringEnum(values) => values
1860 .iter()
1861 .map(|value| quote(value))
1862 .collect::<Vec<_>>()
1863 .join(" | "),
1864 Shape::Tagged { tag, variants } => variants
1865 .iter()
1866 .map(|(value, fields)| {
1867 let tagged = format!("{}: {}", quote(tag), quote(value));
1868 ts_object(fields, Some(&tagged))
1869 })
1870 .collect::<Vec<_>>()
1871 .join(" | "),
1872 Shape::External(variants) => variants
1873 .iter()
1874 .map(|variant| match variant {
1875 External::Unit(value) => quote(value),
1876 External::Newtype(key, ty) => format!("{{ {}: {} }}", quote(key), ts_ty(ty)),
1877 External::Struct(key, fields) => {
1878 format!("{{ {}: {} }}", quote(key), ts_object(fields, None))
1879 }
1880 })
1881 .collect::<Vec<_>>()
1882 .join(" | "),
1883 Shape::Untagged(variants) => variants
1884 .iter()
1885 .map(|(_, ty)| ts_ty(ty))
1886 .collect::<Vec<_>>()
1887 .join(" | "),
1888 };
1889 let _ = writeln!(out, "export type {name} = {body};");
1890 }
1891 for (name, kind, response) in [
1892 ("ClientRequestMap", Kind::ClientRequest, true),
1893 ("ClientNotificationMap", Kind::ClientNotification, false),
1894 ("ServerRequestMap", Kind::ServerRequest, true),
1895 ("ServerNotificationMap", Kind::ServerNotification, false),
1896 ] {
1897 let _ = writeln!(out, "export type {name} = {{");
1898 for row in contract.selected(kind) {
1899 let params = row.params.clone().unwrap_or_else(|| "undefined".into());
1900 if response {
1901 let _ = writeln!(
1902 out,
1903 " {}: {{ params: {params}; result: {} }};",
1904 quote(&row.method),
1905 row.response.clone().unwrap_or_default()
1906 );
1907 } else {
1908 let _ = writeln!(out, " {}: {{ params: {params} }};", quote(&row.method));
1909 }
1910 }
1911 out.push_str("};\n");
1912 }
1913 Ok(out)
1914 }
1915
1915 lines RUST