use serde_json::{Map, Value};
pub fn add_dependencies(
pkg: &mut Value,
section: &str,
entries: &[(String, String)],
) -> Result<Vec<String>, String> {
let root = pkg.as_object_mut().ok_or("package.json is not an object")?;
let deps = root
.entry(section)
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()
.ok_or_else(|| format!("{section} is not an object"))?;
let was_sorted = deps.keys().zip(deps.keys().skip(1)).all(|(a, b)| a <= b);
let mut added = Vec::new();
for (name, range) in entries {
if !deps.contains_key(name) {
deps.insert(name.clone(), Value::String(range.clone()));
added.push(name.clone());
}
}
if was_sorted && !added.is_empty() {
let mut all: Vec<(String, Value)> = std::mem::take(deps).into_iter().collect();
all.sort_by(|a, b| a.0.cmp(&b.0));
deps.extend(all);
}
Ok(added)
}
pub fn to_string_like(original: &str, value: &Value) -> Result<String, String> {
use serde::Serialize;
let indent = detect_indent(original);
let mut out = Vec::new();
let formatter = serde_json::ser::PrettyFormatter::with_indent(indent.as_bytes());
let mut ser = serde_json::Serializer::with_formatter(&mut out, formatter);
value.serialize(&mut ser).map_err(|e| e.to_string())?;
let mut text = String::from_utf8(out).map_err(|e| e.to_string())?;
if original.is_empty() || original.ends_with('\n') {
text.push('\n');
}
Ok(text)
}
fn detect_indent(original: &str) -> String {
original
.lines()
.skip(1)
.map(|l| {
l.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.collect::<String>()
})
.find(|ws| !ws.is_empty())
.unwrap_or_else(|| " ".to_string())
}
#[cfg(test)]
mod tests {
use super::*;
const ORIGINAL: &str = r#"{
"name": "kitchen",
"version": "1.0.0",
"scripts": {
"start": "vite"
},
"dependencies": {
"react": "^19.0.0",
"zustand": "^5.0.0"
},
"devDependencies": {
"vite": "^7.0.0"
}
}
"#;
#[test]
fn keeps_key_order_indent_and_sorts_new_dependency() {
let mut pkg: Value = serde_json::from_str(ORIGINAL).unwrap();
let added = add_dependencies(
&mut pkg,
"dependencies",
&[
("@offline-protocol/id-react".into(), "^0.2.0".into()),
("react".into(), "^18.0.0".into()),
],
)
.unwrap();
assert_eq!(added, vec!["@offline-protocol/id-react".to_string()]);
let text = to_string_like(ORIGINAL, &pkg).unwrap();
let expected = ORIGINAL.replace(
" \"dependencies\": {\n",
" \"dependencies\": {\n \"@offline-protocol/id-react\": \"^0.2.0\",\n",
);
assert_eq!(text, expected);
}
#[test]
fn appends_when_dependencies_were_unsorted() {
let original = "{\n \"dependencies\": {\n \"zustand\": \"1\",\n \"react\": \"1\"\n },\n \"name\": \"x\"\n}";
let mut pkg: Value = serde_json::from_str(original).unwrap();
add_dependencies(&mut pkg, "dependencies", &[("axios".into(), "^1".into())]).unwrap();
let text = to_string_like(original, &pkg).unwrap();
assert_eq!(
text,
"{\n \"dependencies\": {\n \"zustand\": \"1\",\n \"react\": \"1\",\n \"axios\": \"^1\"\n },\n \"name\": \"x\"\n}"
);
}
#[test]
fn creates_missing_section_at_the_end() {
let original = "{\n\t\"name\": \"x\"\n}\n";
let mut pkg: Value = serde_json::from_str(original).unwrap();
add_dependencies(&mut pkg, "dependencies", &[("axios".into(), "^1".into())]).unwrap();
let text = to_string_like(original, &pkg).unwrap();
assert_eq!(
text,
"{\n\t\"name\": \"x\",\n\t\"dependencies\": {\n\t\t\"axios\": \"^1\"\n\t}\n}\n"
);
}
}