zed_util/
schemars.rs

1use schemars::{JsonSchema, transform::transform_subschemas};
2
3const DEFS_PATH: &str = "#/$defs/";
4
5/// Replaces the JSON schema definition for some type if it is in use (in the definitions list), and
6/// returns a reference to it.
7///
8/// This asserts that JsonSchema::schema_name() + "2" does not exist because this indicates that
9/// there are multiple types that use this name, and unfortunately schemars APIs do not support
10/// resolving this ambiguity - see <https://github.com/GREsau/schemars/issues/449>
11///
12/// This takes a closure for `schema` because some settings types are not available on the remote
13/// server, and so will crash when attempting to access e.g. GlobalThemeRegistry.
14pub fn replace_subschema<T: JsonSchema>(
15    generator: &mut schemars::SchemaGenerator,
16    schema: impl Fn() -> schemars::Schema,
17) -> schemars::Schema {
18    let schema_name = T::schema_name();
19    let definitions = generator.definitions_mut();
20    assert!(!definitions.contains_key(&format!("{schema_name}2")));
21    assert!(definitions.contains_key(schema_name.as_ref()));
22    definitions.insert(schema_name.to_string(), schema().to_value());
23    schemars::Schema::new_ref(format!("{DEFS_PATH}{schema_name}"))
24}
25
26/// Adds a new JSON schema definition and returns a reference to it. **Panics** if the name is
27/// already in use.
28pub fn add_new_subschema(
29    generator: &mut schemars::SchemaGenerator,
30    name: &str,
31    schema: serde_json::Value,
32) -> schemars::Schema {
33    let old_definition = generator.definitions_mut().insert(name.to_string(), schema);
34    assert_eq!(old_definition, None);
35    schemars::Schema::new_ref(format!("{DEFS_PATH}{name}"))
36}
37
38/// Defaults `additionalProperties` to `true`, as if `#[schemars(deny_unknown_fields)]` was on every
39/// struct. Skips structs that have `additionalProperties` set (such as if #[serde(flatten)] is used
40/// on a map).
41#[derive(Clone)]
42pub struct DefaultDenyUnknownFields;
43
44impl schemars::transform::Transform for DefaultDenyUnknownFields {
45    fn transform(&mut self, schema: &mut schemars::Schema) {
46        if let Some(object) = schema.as_object_mut()
47            && object.contains_key("properties")
48            && !object.contains_key("additionalProperties")
49            && !object.contains_key("unevaluatedProperties")
50        {
51            object.insert("additionalProperties".to_string(), false.into());
52        }
53        transform_subschemas(self, schema);
54    }
55}