use crate::schema::pointer;
use serde_json::Value;
use std::collections::BTreeSet;
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SettingsCoverage {
pub section_found: bool,
pub missing: Vec<String>,
pub unknown: Vec<String>,
pub duplicate: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SettingsCoverageError {
NonObjectSchema,
}
impl fmt::Display for SettingsCoverageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NonObjectSchema => f.write_str("settings schema root must be a JSON object"),
}
}
}
impl std::error::Error for SettingsCoverageError {}
pub fn settings_coverage(
schema: &Value,
page: &str,
) -> Result<SettingsCoverage, SettingsCoverageError> {
if !schema.is_object() {
return Err(SettingsCoverageError::NonObjectSchema);
}
let mut keys = SchemaKeys::default();
keys.walk(schema, "");
let (section_found, headings) = scan_headings(page, &mut keys.duplicate);
Ok(SettingsCoverage {
section_found,
missing: keys
.required
.into_iter()
.filter(|key| !headings.contains(key.as_str()))
.collect(),
unknown: headings
.into_iter()
.filter(|key| !keys.known.contains(*key))
.map(str::to_owned)
.collect(),
duplicate: keys.duplicate.into_iter().collect(),
})
}
#[derive(Default)]
struct SchemaKeys {
known: BTreeSet<String>,
required: BTreeSet<String>,
duplicate: BTreeSet<String>,
}
impl SchemaKeys {
fn walk(&mut self, schema: &Value, path: &str) -> bool {
if ["oneOf", "anyOf"]
.into_iter()
.filter_map(|keyword| schema.get(keyword).and_then(Value::as_array))
.any(|branches| is_tagged_union(branches))
{
self.known.insert(path.to_owned());
if !path.is_empty() {
self.required.insert(path.to_owned());
}
return false;
}
if is_atomic(schema) {
return false;
}
let mut container = false;
if let Some(fields) = schema.get("properties").and_then(Value::as_object) {
container = true;
for (name, child) in fields {
let key = pointer(path, name);
self.record_key(key.clone());
if !self.walk(child, &key) {
self.required.insert(key);
}
}
}
let patterns = schema
.get("patternProperties")
.and_then(Value::as_object)
.into_iter()
.flat_map(|patterns| patterns.values());
for entry in schema
.get("items")
.into_iter()
.chain(patterns)
.chain(schema.get("additionalProperties"))
{
if entry.get("properties").is_some_and(Value::is_object) && !is_atomic(entry) {
self.walk(entry, path);
container = true;
}
}
for keyword in ["oneOf", "anyOf"] {
if let Some(branches) = schema.get(keyword).and_then(Value::as_array) {
container |= self.walk_alternatives(branches, path);
}
}
if let Some(branches) = schema.get("allOf").and_then(Value::as_array) {
for branch in branches {
container |= self.walk(branch, path);
}
}
container
}
fn walk_alternatives(&mut self, branches: &[Value], path: &str) -> bool {
let mut container = false;
let mut known = BTreeSet::new();
for branch in branches {
let mut keys = Self::default();
container |= keys.walk(branch, path);
known.extend(keys.known);
self.required.extend(keys.required);
self.duplicate.extend(keys.duplicate);
}
for key in known {
if key == path {
self.known.insert(key);
} else {
self.record_key(key);
}
}
container
}
fn record_key(&mut self, key: String) {
if self.known.contains(&key) {
self.duplicate.insert(key);
} else {
self.known.insert(key);
}
}
}
fn is_atomic(schema: &Value) -> bool {
matches!(
schema.get("x-ck-kind").and_then(Value::as_str),
Some("json" | "credential_ref")
)
}
fn is_tagged_union(branches: &[Value]) -> bool {
if branches.len() < 2 {
return false;
}
let Some(properties) = branches
.iter()
.map(|branch| {
if branch.get("type").is_some_and(|kind| {
let kind = match kind.as_array().map(Vec::as_slice) {
Some([only]) => only,
_ => kind,
};
kind.as_str() != Some("object")
}) {
return None;
}
branch.get("properties")?.as_object()
})
.collect::<Option<Vec<_>>>()
else {
return false;
};
properties[0].keys().any(|name| {
let mut seen = Vec::with_capacity(properties.len());
properties.iter().all(|fields| {
let Some(tag) = fields.get(name).and_then(tag_value) else {
return false;
};
if seen.contains(&tag) {
return false;
}
seen.push(tag);
true
})
})
}
fn tag_value(schema: &Value) -> Option<&Value> {
schema.get("const").or_else(|| {
let [tag] = schema.get("enum")?.as_array()?.as_slice() else {
return None;
};
Some(tag)
})
}
fn scan_headings<'a>(page: &'a str, duplicate: &mut BTreeSet<String>) -> (bool, BTreeSet<&'a str>) {
let mut section_found = false;
let mut headings = BTreeSet::new();
let mut fence: Option<Fence> = None;
for raw in page.lines() {
let line = raw.trim_start_matches(' ');
if raw.len() - line.len() > 3 {
continue;
}
let marker = fence_marker(line);
if let Some(open) = &fence {
if marker.is_some_and(|(close, rest)| {
close.marker == open.marker
&& close.width >= open.width
&& rest.trim_end_matches([' ', '\t']).is_empty()
}) {
fence = None;
}
continue;
}
if let Some((open, rest)) = marker {
if open.marker != '`' || !rest.contains('`') {
fence = Some(open);
continue;
}
}
match atx_heading(line) {
Some((1 | 2, _)) if section_found => break,
Some((2, "Settings")) => section_found = true,
Some((3, text)) if section_found => {
if let Some(key) = code_span_key(text) {
if !headings.insert(key) {
duplicate.insert(key.to_owned());
}
}
}
_ => {}
}
}
(section_found, headings)
}
struct Fence {
marker: char,
width: usize,
}
fn fence_marker(line: &str) -> Option<(Fence, &str)> {
let marker = line.chars().next()?;
if !matches!(marker, '`' | '~') {
return None;
}
let (width, rest) = marker_run(line, marker);
(width >= 3).then_some((Fence { marker, width }, rest))
}
fn atx_heading(line: &str) -> Option<(usize, &str)> {
let (level, rest) = marker_run(line, '#');
if !(1..=6).contains(&level) || (!rest.is_empty() && !rest.starts_with([' ', '\t'])) {
return None;
}
let rest = rest.trim_end_matches([' ', '\t']);
let text = rest.trim_end_matches('#');
let text = if text.ends_with([' ', '\t']) {
text
} else {
rest
};
Some((level, text.trim_matches([' ', '\t'])))
}
fn code_span_key(text: &str) -> Option<&str> {
let (width, content) = marker_run(text, '`');
if width == 0 {
return None;
}
let mut rest = content;
while let Some(index) = rest.find('`') {
let (ticks, after) = marker_run(&rest[index..], '`');
if ticks == width {
if !after.is_empty() {
return None;
}
let code = &content[..content.len() - rest.len() + index];
let code = code
.strip_prefix(' ')
.and_then(|code| code.strip_suffix(' '))
.unwrap_or(code);
return code.starts_with('/').then_some(code);
}
rest = after;
}
None
}
fn marker_run(text: &str, marker: char) -> (usize, &str) {
let rest = text.trim_start_matches(marker);
(text.len() - rest.len(), rest)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn assert_complete(schema: &Value, page: &str) {
assert_eq!(
settings_coverage(schema, page).unwrap(),
SettingsCoverage {
section_found: true,
missing: vec![],
unknown: vec![],
duplicate: vec![],
}
);
}
#[test]
fn reports_missing_and_unknown_keys_in_the_settings_section() {
let schema = json!({"properties": {"a": {}, "b": {"properties": {"c": {}}}}});
let coverage = settings_coverage(&schema, "## Settings\n### `/a`\n### `/x`").unwrap();
assert!(coverage.section_found);
assert_eq!(coverage.missing, ["/b/c"]);
assert_eq!(coverage.unknown, ["/x"]);
assert!(coverage.duplicate.is_empty());
assert_complete(&schema, "## Settings\n### `/a`\n### `/b/c`");
assert_complete(&schema, "## Settings\n### `/a`\n### `/b`\n### `/b/c`");
let coverage = settings_coverage(&schema, "Settings\n--------\n### `/a`").unwrap();
assert!(!coverage.section_found);
assert_eq!(coverage.missing, ["/a", "/b/c"]);
assert!(coverage.unknown.is_empty());
}
#[test]
fn collection_objects_omit_indices_and_map_keys_recursively() {
let schema = json!({"properties": {
"preload": {"type": "array", "items": {"type": "object", "properties": {
"engine": {"type": "string"},
"options": {"type": "object", "additionalProperties": {"properties": {
"enabled": {"type": "boolean"}
}}}
}}},
"providers": {"type": "object", "patternProperties": {"^.+$": {"type": "object", "properties": {
"base_url": {"type": "string"}
}}}}
}});
assert_complete(
&schema,
"## Settings\n### `/preload/engine`\n### `/preload/options/enabled`\n### `/providers/base_url`",
);
let coverage = settings_coverage(
&schema,
"## Settings\n### `/preload`\n### `/preload/options`\n### `/providers`\n### `/preload/1/engine`\n### `/providers/acme/base_url`",
)
.unwrap();
assert_eq!(
coverage.missing,
[
"/preload/engine",
"/preload/options/enabled",
"/providers/base_url"
]
);
assert_eq!(
coverage.unknown,
["/preload/1/engine", "/providers/acme/base_url"]
);
assert!(coverage.duplicate.is_empty());
}
#[test]
fn scalar_collections_and_annotated_values_stay_single_keys() {
let schema = json!({"properties": {
"list": {"type": "array", "items": {"type": "string"}},
"map": {"type": "object", "patternProperties": {"^.+$": {"type": "string"}}},
"open_map": {"type": "object", "additionalProperties": {"type": "string"}},
"nested_list": {"items": {"items": {"properties": {"ignored": {}}}}},
"opaque": {"x-ck-kind": "json", "properties": {"ignored": {}},
"oneOf": [{"properties": {"also_ignored": {}}}]},
"reference": {"x-ck-kind": "credential_ref", "properties": {"vault_ref": {}}},
"opaque_items": {"items": {"x-ck-kind": "json", "properties": {"ignored": {}}}}
}});
let coverage = settings_coverage(&schema, "## Settings").unwrap();
assert_eq!(
coverage.missing,
[
"/list",
"/map",
"/nested_list",
"/opaque",
"/opaque_items",
"/open_map",
"/reference"
]
);
}
#[test]
fn combines_schema_collisions_and_repeated_headings_in_sorted_duplicate_list() {
let schema = json!({"properties": {"settings": {
"properties": {"port": {}},
"patternProperties": {"^.+$": {"properties": {"port": {}}}},
"additionalProperties": {"properties": {"port": {}}}
}}});
let page = "## Settings\n### `/z`\n### `/a`\n### `/z`\n### `/z`\n### `/a`";
let coverage = settings_coverage(&schema, page).unwrap();
assert_eq!(coverage.missing, ["/settings/port"]);
assert_eq!(coverage.unknown, ["/a", "/z"]);
assert_eq!(coverage.duplicate, ["/a", "/settings/port", "/z"]);
}
#[test]
fn variants_union_branch_keys_at_the_same_pointer() {
let schema = json!({"properties": {"mode": {
"oneOf": [
{"properties": {"alpha": {}}},
{"anyOf": [{"properties": {"beta": {}}}, {"allOf": [{"properties": {"gamma": {}}}]}]}
]
}}});
assert_complete(
&schema,
"## Settings\n### `/mode/alpha`\n### `/mode/beta`\n### `/mode/gamma`",
);
}
#[test]
fn tagged_unions_are_required_as_single_settings() {
for (keyword, variants) in [
(
"oneOf",
json!([
{"type": "object", "properties": {"kind": {"const": "none"}}},
{"type": "object", "properties": {"kind": {"const": "list"}, "tokens": {}}}
]),
),
(
"anyOf",
json!([
{"properties": {"kind": {"enum": ["none"]}}},
{"type": ["object"], "properties": {"kind": {"const": "list"}, "tokens": {}}}
]),
),
] {
let union = json!({(keyword): variants});
assert_complete(&union, "## Settings");
let schema = json!({"properties": {"protected_tokens": union}});
assert_complete(&schema, "## Settings\n### `/protected_tokens`");
let coverage =
settings_coverage(&schema, "## Settings\n### `/protected_tokens/tokens`").unwrap();
assert_eq!(coverage.missing, ["/protected_tokens"]);
assert_eq!(coverage.unknown, ["/protected_tokens/tokens"]);
assert!(coverage.duplicate.is_empty());
}
}
#[test]
fn untagged_alternatives_merge_shared_keys() {
for branches in [
json!([{"properties": {"kind": {}}}, {"properties": {"kind": {}}}]),
json!([
{"properties": {"kind": {"const": "same"}}},
{"properties": {"kind": {"enum": ["same"]}}}
]),
json!([
{"properties": {"kind": {"const": "one"}}},
{"properties": {"kind": {"enum": ["two", "three"]}}}
]),
json!([
{"type": ["object", "null"], "properties": {"kind": {"const": "one"}}},
{"properties": {"kind": {"const": "two"}}}
]),
json!([{"properties": {"kind": {"const": "only"}}}]),
] {
let schema = json!({"properties": {"mode": {"oneOf": branches}}});
assert_complete(&schema, "## Settings\n### `/mode/kind`");
}
}
#[test]
fn alternatives_preserve_collisions_within_a_branch_and_outside_sibling_branches() {
let schema = json!({
"properties": {"external": {}},
"anyOf": [
{"allOf": [{"properties": {"internal": {}}}, {"properties": {"internal": {}}}]},
{"properties": {"internal": {}, "external": {}}}
]
});
let page = "## Settings\n### `/external`\n### `/internal`";
let coverage = settings_coverage(&schema, page).unwrap();
assert!(coverage.missing.is_empty());
assert!(coverage.unknown.is_empty());
assert_eq!(coverage.duplicate, ["/external", "/internal"]);
}
#[test]
fn rejects_non_object_schema_roots() {
for schema in [
json!(null),
json!(false),
json!([]),
json!("object"),
json!(0),
] {
assert_eq!(
settings_coverage(&schema, "## Settings"),
Err(SettingsCoverageError::NonObjectSchema)
);
}
assert_complete(&json!({}), "## Settings");
}
#[test]
fn scanner_requires_one_code_span_in_an_atx_h3() {
let schema = json!({"properties": {"a~b/c": {}, "has`tick": {}, "last": {}}});
let page = "\
## Settings (draft)
### `/before`
##\tSettings ###
### `/a~0b~1c` ###
### `` /has`tick ``
#### `/h4`
### `/indented`
###`/no-space`
### `/extra` text
### `/first` `/second`
### `/no-space-before-closer`###
### `not-a-key`
`/setext`
---------
### `/last`
## Commands
### `/after`";
assert_complete(&schema, page);
}
#[test]
fn fenced_headings_do_not_open_end_or_contribute_to_settings() {
let schema = json!({"properties": {"first": {}, "last": {}}});
let page = "\
~~~markdown
## Settings
### `/hidden-before`
~~~~
## Settings
### `/first`
````markdown
# Hidden H1
```
### `/after-short-fence`
~~~~~
### `/after-tilde-fence`
```` not a closing fence
### `/after-fence-with-info`
`````
### `/last`
# End of Settings
### `/after`";
assert_complete(&schema, page);
}
}