Skip to main content

surjection_core/adapters/
mapper.rs

1//! Entry mappers (SPEC 7.1 `EntryMapper`): one server between Surjection's
2//! rendered form and a client's native entry, plus the canonical form used
3//! for equality and hashing.
4//!
5//! [`McpServersJson`] maps the common `mcpServers.<name>` JSON shape used by
6//! the Claude clients, omp and Pi; what differs between them comes from
7//! their [`Caps`], a few shape switches and a name rule. Codex has its own
8//! TOML mapper (`crate::adapters::codex`) built on the helpers here.
9
10use std::collections::BTreeMap;
11use std::fmt;
12
13use crate::adapters::caps::{Caps, CommandRef, DisableMech, ToolFilterMech};
14use crate::env::Os;
15use crate::error::{CoreError, ErrorCode};
16use crate::formats::{NativeMap, NativeValue};
17use crate::model::server::{ServerFields, Transport};
18
19/// A server ready to write for one client: layers merged, OS overrides
20/// applied and secret references rendered for the client's delivery mode
21/// (SPEC 6, 11.4). Values are written as they are.
22#[derive(Debug, Clone, PartialEq)]
23pub struct RenderedServer {
24    /// The native entry key (the server id or its `native_name`).
25    pub name: String,
26    pub launch: Launch,
27    /// `false` writes the entry natively disabled (`enabled: false`, SPEC
28    /// 8.4, 11.9). A client without that mechanism blocks the target
29    /// (`unsupported_field`).
30    pub enabled: bool,
31    /// The tool filter (`[tools]`), written through the client's native
32    /// fields ([`Caps::tool_filter`]). A client without them blocks the
33    /// target; dropping the filter instead is the renderer's choice.
34    pub tools: ToolLists,
35    /// `[client.<id>]` fields other than `native_name`, already checked
36    /// against the client's passthrough allowlist.
37    pub passthrough: NativeMap,
38}
39
40impl RenderedServer {
41    /// An enabled server without a tool filter or passthrough fields.
42    pub fn new(name: impl Into<String>, launch: Launch) -> Self {
43        Self {
44            name: name.into(),
45            launch,
46            enabled: true,
47            tools: ToolLists::default(),
48            passthrough: NativeMap::new(),
49        }
50    }
51}
52
53/// How the client starts or reaches the server.
54#[derive(Debug, Clone, PartialEq)]
55pub enum Launch {
56    Stdio(StdioLaunch),
57    Http(RemoteLaunch),
58    Sse(RemoteLaunch),
59}
60
61impl Launch {
62    pub const fn transport(&self) -> Transport {
63        match self {
64            Launch::Stdio(_) => Transport::Stdio,
65            Launch::Http(_) => Transport::Http,
66            Launch::Sse(_) => Transport::Sse,
67        }
68    }
69}
70
71#[derive(Debug, Clone, Default, PartialEq)]
72pub struct StdioLaunch {
73    pub command: String,
74    pub args: Vec<String>,
75    pub env: BTreeMap<String, String>,
76    /// Variables the client copies from its own environment into the
77    /// server's under the same name (`env` delivery on a client with
78    /// `EnvRefSyntax::CodexForward`: Codex `env_vars`).
79    pub forward_env: Vec<String>,
80    pub cwd: Option<String>,
81}
82
83#[derive(Debug, Clone, Default, PartialEq)]
84pub struct RemoteLaunch {
85    pub url: String,
86    pub headers: BTreeMap<String, String>,
87    /// A command printing a JSON object of headers, run by the client at
88    /// connect time (`command` delivery on Claude Code, SPEC 11.4).
89    pub headers_helper: Option<String>,
90    /// A variable whose value the client sends as `Authorization: Bearer
91    /// <value>` (Codex `bearer_token_env_var`).
92    pub bearer_env: Option<String>,
93    /// Header name to the variable whose value the client sends as that
94    /// header (Codex `env_http_headers`).
95    pub headers_env: BTreeMap<String, String>,
96}
97
98/// A tool filter: only `allow` (when set), never `deny`.
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
100pub struct ToolLists {
101    pub allow: Option<Vec<String>>,
102    pub deny: Option<Vec<String>>,
103}
104
105impl ToolLists {
106    pub fn is_empty(&self) -> bool {
107        self.allow.is_none() && self.deny.is_none()
108    }
109}
110
111/// Context of one write.
112#[derive(Debug, Clone, Copy)]
113pub struct WriteCx<'a> {
114    pub os: Os,
115    /// The entry currently in the file under the same key, if any. Keys the
116    /// mapper does not model are carried over from it.
117    pub existing: Option<&'a NativeValue>,
118}
119
120/// A native entry read back as a server definition (import, adopt, the
121/// post-write self check).
122///
123/// Values a client forwards from its environment by name (Codex
124/// `env_vars`, `bearer_token_env_var`, `env_http_headers`) read back as
125/// `${env:NAME}` references in `env` and `headers` (SPEC 11.2).
126#[derive(Debug, Clone, Default, PartialEq)]
127pub struct ServerDef {
128    /// Launch and connection fields; `transport` is always set.
129    pub fields: ServerFields,
130    pub headers_helper: Option<String>,
131    /// The entry is natively disabled (`enabled: false`).
132    pub disabled: bool,
133    /// The native tool filter.
134    pub tools: ToolLists,
135    /// Allowlisted native fields, for `[client.<id>]`.
136    pub passthrough: NativeMap,
137    /// Native fields with no canonical or passthrough equivalent. Reported
138    /// on import; carried over by later writes.
139    pub unmapped: NativeMap,
140}
141
142/// The canonical text of a native entry: object keys sorted, client
143/// defaults dropped. Equal canonical forms mean the client sees the same
144/// server.
145#[derive(Debug, Clone, PartialEq, Eq, Hash)]
146pub struct Canonical(String);
147
148impl Canonical {
149    /// Canonical text of `value` as it is (keys sorted, nothing dropped).
150    pub fn of(value: &NativeValue) -> Self {
151        let mut text = String::new();
152        write_canonical(value, &mut text);
153        Self(text)
154    }
155
156    pub fn as_str(&self) -> &str {
157        &self.0
158    }
159}
160
161/// Why a server cannot be written to, or read from, a client. A write
162/// failure blocks that target; nothing is dropped silently (SPEC 7.1).
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub enum MapError {
165    /// The client cannot run this transport (`http` on Claude Desktop,
166    /// `ws` read from Claude Code).
167    UnsupportedTransport { transport: String },
168    /// The client has no native field for a set field (`cwd` on Claude).
169    UnsupportedField { field: String },
170    /// The entry key breaks the client's naming rule; set `native_name`.
171    InvalidName { name: String },
172    /// A native value has another kind than the client documents.
173    UnexpectedShape {
174        field: String,
175        expected: &'static str,
176    },
177}
178
179impl MapError {
180    pub const fn code(&self) -> ErrorCode {
181        match self {
182            MapError::UnsupportedTransport { .. } => ErrorCode::UnsupportedTransport,
183            MapError::UnsupportedField { .. } => ErrorCode::UnsupportedField,
184            MapError::InvalidName { .. } => ErrorCode::InvalidId,
185            MapError::UnexpectedShape { .. } => ErrorCode::UnexpectedShape,
186        }
187    }
188}
189
190impl fmt::Display for MapError {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            MapError::UnsupportedTransport { transport } => {
194                write!(f, "the client cannot run {transport:?} servers")
195            }
196            MapError::UnsupportedField { field } => {
197                write!(f, "the client has no native field for `{field}`")
198            }
199            MapError::InvalidName { name } => {
200                write!(
201                    f,
202                    "{name:?} is not a valid entry name for the client; set `native_name`"
203                )
204            }
205            MapError::UnexpectedShape { field, expected } => {
206                write!(f, "`{field}` must be {expected}")
207            }
208        }
209    }
210}
211
212impl std::error::Error for MapError {}
213
214impl From<MapError> for CoreError {
215    fn from(err: MapError) -> Self {
216        CoreError::new(err.code(), err.to_string())
217    }
218}
219
220/// Maps one server to and from a client's native entry.
221pub trait EntryMapper: Sync {
222    fn to_native(&self, server: &RenderedServer, cx: &WriteCx<'_>)
223    -> Result<NativeValue, MapError>;
224
225    /// Reads the entry `key` back. Named as in SPEC 7.1, hence the lint.
226    #[allow(clippy::wrong_self_convention)]
227    fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError>;
228
229    /// Sorted, client defaults dropped; used for equality and hashing.
230    fn canonical(&self, value: &NativeValue) -> Canonical;
231
232    /// Why the client itself does not load this entry, when it does not
233    /// (gate V1 CC-5: Claude Code skips a `url` entry without `type`). Such
234    /// an entry still reads back, so import can take it, but importing it
235    /// starts a server the client never ran.
236    fn skipped_by_client(&self, _value: &NativeValue) -> Option<&'static str> {
237        None
238    }
239}
240
241/// Keys every `mcpServers` entry may have.
242const MODELED_KEYS: [&str; 6] = ["type", "command", "args", "env", "url", "headers"];
243const HEADERS_HELPER: &str = "headersHelper";
244const TYPE: &str = "type";
245const CWD: &str = "cwd";
246const ENABLED: &str = "enabled";
247
248/// Commands that are `.cmd` or `.bat` shims on Windows (npm-installed
249/// launchers), which a client spawning without a shell cannot start.
250const WINDOWS_SHIMS: [&str; 7] = ["npx", "npm", "pnpm", "pnpx", "yarn", "yarnpkg", "corepack"];
251
252/// The `mcpServers.<name>` JSON entry: `{type, command, args, env, cwd}` or
253/// `{type, url, headers, headersHelper}`, plus the disable flag (`enabled`
254/// or `disabled`) of clients that disable natively (SPEC 7.3).
255///
256/// Stdio entries are written with `command` and `args`, plus `env` when it
257/// has variables (or the existing entry has the key).
258#[derive(Debug)]
259pub struct McpServersJson {
260    pub caps: &'static Caps,
261    /// Write `type: "stdio"` on stdio entries.
262    pub type_field: bool,
263    /// Write `type` on http entries. SSE entries always get it, since a
264    /// bare `url` reads as http.
265    pub remote_type: bool,
266    /// The client has a native `cwd` field. Without it a server with `cwd`
267    /// blocks, and a native `cwd` is unmapped and kept.
268    pub cwd: bool,
269    /// Other native `type` spellings of http (Pi `streamable-http`).
270    pub http_aliases: &'static [&'static str],
271    /// The client runs an untyped `url` entry as http, so a missing `type`
272    /// equals `http` in the canonical form (omp, Pi). Without it, an
273    /// untyped remote entry is not the one Surjection writes (Claude Code
274    /// requires `type`).
275    pub url_implies_http: bool,
276    /// Whether an entry key is valid for the client.
277    pub valid_name: fn(&str) -> bool,
278}
279
280impl McpServersJson {
281    fn headers_helper(&self) -> bool {
282        self.caps.command_ref == Some(CommandRef::HeadersHelper)
283    }
284
285    fn is_modeled(&self, key: &str) -> bool {
286        MODELED_KEYS.contains(&key)
287            || (key == CWD && self.cwd)
288            || (key == HEADERS_HELPER && self.headers_helper())
289            || is_disable_key(self.caps, key)
290            || is_tool_key(self.caps, key)
291            || self.caps.passthrough_allowlist.contains(&key)
292    }
293
294    /// The type the client gives an entry without `type`.
295    fn inferred_type(&self, entry: &NativeMap) -> Option<&'static str> {
296        if entry.contains_key("command") {
297            Some("stdio")
298        } else if entry.contains_key("url") && self.url_implies_http {
299            Some("http")
300        } else {
301            None
302        }
303    }
304}
305
306impl EntryMapper for McpServersJson {
307    fn to_native(
308        &self,
309        server: &RenderedServer,
310        cx: &WriteCx<'_>,
311    ) -> Result<NativeValue, MapError> {
312        check_name(self.valid_name, &server.name)?;
313        let transport = check_transport(self.caps, &server.launch)?;
314        let existing = existing_entry(cx);
315        let keep_empty = |key: &str| existing.is_some_and(|entry| entry.contains_key(key));
316        let mut entry = NativeMap::new();
317        match &server.launch {
318            Launch::Stdio(stdio) => {
319                if !stdio.forward_env.is_empty() {
320                    return unsupported("env_vars");
321                }
322                if self.type_field {
323                    entry.insert(TYPE, "stdio".into());
324                }
325                let (command, args) = if self.caps.windows_shell_shim && cx.os == Os::Windows {
326                    shell_shim(&stdio.command, &stdio.args)
327                } else {
328                    (stdio.command.clone(), stdio.args.clone())
329                };
330                entry.insert("command", command.into());
331                entry.insert("args", strings(args));
332                if !stdio.env.is_empty() || keep_empty("env") {
333                    entry.insert("env", string_map(&stdio.env));
334                }
335                if let Some(cwd) = &stdio.cwd {
336                    if !self.cwd {
337                        return unsupported(CWD);
338                    }
339                    entry.insert(CWD, cwd.as_str().into());
340                }
341            }
342            Launch::Http(remote) | Launch::Sse(remote) => {
343                if remote.bearer_env.is_some() {
344                    return unsupported("bearer_token_env_var");
345                }
346                if !remote.headers_env.is_empty() {
347                    return unsupported("env_http_headers");
348                }
349                if self.remote_type || transport == Transport::Sse {
350                    entry.insert(TYPE, transport.as_str().into());
351                }
352                entry.insert("url", remote.url.as_str().into());
353                if !remote.headers.is_empty() || keep_empty("headers") {
354                    entry.insert("headers", string_map(&remote.headers));
355                }
356                if let Some(helper) = &remote.headers_helper {
357                    if !self.headers_helper() {
358                        return unsupported(HEADERS_HELPER);
359                    }
360                    entry.insert(HEADERS_HELPER, helper.as_str().into());
361                }
362            }
363        }
364        write_enabled(&mut entry, self.caps, server, existing)?;
365        write_tools(&mut entry, self.caps, &server.tools)?;
366        write_passthrough(&mut entry, self.caps, server)?;
367        carry_over(&mut entry, existing, |key| self.is_modeled(key));
368        Ok(NativeValue::Object(entry))
369    }
370
371    fn from_native(&self, key: &str, value: &NativeValue) -> Result<ServerDef, MapError> {
372        let entry = value.as_object().ok_or_else(|| MapError::UnexpectedShape {
373            field: key.to_owned(),
374            expected: "an object",
375        })?;
376        let transport = match entry.get(TYPE) {
377            Some(NativeValue::String(kind)) => match kind.as_str() {
378                "stdio" => Transport::Stdio,
379                "http" => Transport::Http,
380                "sse" => Transport::Sse,
381                alias if self.http_aliases.contains(&alias) => Transport::Http,
382                other => {
383                    return Err(MapError::UnsupportedTransport {
384                        transport: other.to_owned(),
385                    });
386                }
387            },
388            Some(_) => return shape(TYPE, "a string"),
389            // SPEC 7.5: `command` means stdio, a bare `url` means http.
390            None if entry.contains_key("command") => Transport::Stdio,
391            None if entry.contains_key("url") => Transport::Http,
392            None => return shape("command", "set (or `url` for a remote server)"),
393        };
394        let mut fields = ServerFields {
395            transport: Some(transport),
396            command: string_field(entry, "command")?,
397            args: string_list(entry, "args")?,
398            cwd: if self.cwd {
399                string_field(entry, CWD)?
400            } else {
401                None
402            },
403            url: string_field(entry, "url")?,
404            headers: string_map_field(entry, "headers")?,
405            env: string_map_field(entry, "env")?,
406        };
407        if self.caps.windows_shell_shim
408            && let (Some(command), Some(args)) = (&fields.command, &fields.args)
409            && let Some((inner, rest)) = shell_unshim(command, args)
410        {
411            fields.command = Some(inner);
412            fields.args = Some(rest);
413        }
414        let mut def = ServerDef {
415            fields,
416            disabled: read_disabled(entry, self.caps)?,
417            tools: read_tools(entry, self.caps)?,
418            ..ServerDef::default()
419        };
420        if self.headers_helper() {
421            def.headers_helper = string_field(entry, HEADERS_HELPER)?;
422        }
423        split_rest(&mut def, entry, self.caps, |key| self.is_modeled(key));
424        Ok(def)
425    }
426
427    fn canonical(&self, value: &NativeValue) -> Canonical {
428        let Some(entry) = value.as_object() else {
429            return Canonical::of(value);
430        };
431        let mut entry = entry.clone();
432        if let Some(kind) = entry.get(TYPE).and_then(NativeValue::as_str) {
433            let kind = if self.http_aliases.contains(&kind) {
434                "http"
435            } else {
436                kind
437            };
438            if Some(kind) == self.inferred_type(&entry) {
439                entry.remove(TYPE);
440            } else {
441                entry.insert(TYPE, kind.into());
442            }
443        }
444        drop_empty(&mut entry, &["args", "env", "headers"]);
445        drop_default_enabled(&mut entry, self.caps);
446        Canonical::of(&NativeValue::Object(entry))
447    }
448
449    fn skipped_by_client(&self, value: &NativeValue) -> Option<&'static str> {
450        let entry = value.as_object()?;
451        // An entry with a `command` is stdio whatever else it holds.
452        (entry.contains_key("url")
453            && !entry.contains_key(TYPE)
454            && self.inferred_type(entry).is_none())
455        .then_some("has a `url` but no `type`, so the client skips it")
456    }
457}
458
459// ---------------------------------------------------------------------------
460// Shared by the mappers
461
462/// `[A-Za-z0-9_-]+`, the entry name rule of Pi (SPEC 5.1; V2 verifies it).
463pub fn word_name(name: &str) -> bool {
464    !name.is_empty()
465        && name
466            .bytes()
467            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
468}
469
470/// `[A-Za-z0-9_.-]+`: Claude Code and Codex also load names with `.`
471/// (gate V1, CC-7 and CX-6, on Windows and Linux).
472pub fn dotted_word_name(name: &str) -> bool {
473    !name.is_empty()
474        && name.bytes().all(|byte| {
475            byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' || byte == b'.'
476        })
477}
478
479/// The existing entry of a write, when it is an object.
480pub(crate) fn existing_entry<'a>(cx: &WriteCx<'a>) -> Option<&'a NativeMap> {
481    cx.existing.and_then(NativeValue::as_object)
482}
483
484pub(crate) fn check_name(valid: fn(&str) -> bool, name: &str) -> Result<(), MapError> {
485    if valid(name) {
486        Ok(())
487    } else {
488        Err(MapError::InvalidName {
489            name: name.to_owned(),
490        })
491    }
492}
493
494pub(crate) fn check_transport(caps: &Caps, launch: &Launch) -> Result<Transport, MapError> {
495    let transport = launch.transport();
496    if caps.transports.contains(transport) {
497        Ok(transport)
498    } else {
499        Err(MapError::UnsupportedTransport {
500            transport: transport.as_str().to_owned(),
501        })
502    }
503}
504
505/// The entry key of the client's in-entry disable flag and the value that
506/// disables (`enabled: false`, `disabled: true`); `None` when the client
507/// has no such flag.
508fn disable_flag(caps: &Caps) -> Option<(&'static str, bool)> {
509    match caps.native_disable {
510        Some(DisableMech::EnabledFalse) => Some((ENABLED, false)),
511        Some(DisableMech::DisabledTrue) => Some(("disabled", true)),
512        Some(DisableMech::ListMember(_)) | None => None,
513    }
514}
515
516/// Whether `key` is the client's in-entry disable flag.
517pub(crate) fn is_disable_key(caps: &Caps, key: &str) -> bool {
518    disable_flag(caps).is_some_and(|(flag, _)| flag == key)
519}
520
521/// The disable flag set for a disabled server (`enabled: false` or
522/// `disabled: true`); its enabled value only when the existing entry has
523/// the key, so an update does not churn it.
524pub(crate) fn write_enabled(
525    entry: &mut NativeMap,
526    caps: &Caps,
527    server: &RenderedServer,
528    existing: Option<&NativeMap>,
529) -> Result<(), MapError> {
530    let Some((flag, disabled)) = disable_flag(caps) else {
531        return if server.enabled {
532            Ok(())
533        } else {
534            unsupported(ENABLED)
535        };
536    };
537    if !server.enabled {
538        entry.insert(flag, NativeValue::Bool(disabled));
539    } else if existing.is_some_and(|entry| entry.contains_key(flag)) {
540        entry.insert(flag, NativeValue::Bool(!disabled));
541    }
542    Ok(())
543}
544
545pub(crate) fn read_disabled(entry: &NativeMap, caps: &Caps) -> Result<bool, MapError> {
546    let Some((flag, disabled)) = disable_flag(caps) else {
547        return Ok(false);
548    };
549    match entry.get(flag) {
550        None => Ok(false),
551        Some(NativeValue::Bool(value)) => Ok(*value == disabled),
552        Some(_) => shape(flag, "a boolean"),
553    }
554}
555
556/// Removes the disable flag at its enabled value, the default, when the
557/// client has one.
558pub(crate) fn drop_default_enabled(entry: &mut NativeMap, caps: &Caps) {
559    if let Some((flag, disabled)) = disable_flag(caps)
560        && entry.get(flag) == Some(&NativeValue::Bool(!disabled))
561    {
562        entry.remove(flag);
563    }
564}
565
566/// Whether `key` is one of the client's native tool filter fields.
567pub(crate) fn is_tool_key(caps: &Caps, key: &str) -> bool {
568    match caps.tool_filter {
569        Some(ToolFilterMech::AllowDeny { allow, deny }) => key == allow || key == deny,
570        Some(ToolFilterMech::Allow(allow)) => key == allow,
571        None => false,
572    }
573}
574
575pub(crate) fn write_tools(
576    entry: &mut NativeMap,
577    caps: &Caps,
578    tools: &ToolLists,
579) -> Result<(), MapError> {
580    let (allow_key, deny_key) = match caps.tool_filter {
581        _ if tools.is_empty() => return Ok(()),
582        Some(ToolFilterMech::AllowDeny { allow, deny }) => (allow, Some(deny)),
583        Some(ToolFilterMech::Allow(allow)) => (allow, None),
584        None => return unsupported("tools"),
585    };
586    if let Some(allow) = &tools.allow {
587        entry.insert(allow_key, strings(allow.clone()));
588    }
589    if let Some(deny) = &tools.deny {
590        let Some(deny_key) = deny_key else {
591            return unsupported("tools.deny");
592        };
593        entry.insert(deny_key, strings(deny.clone()));
594    }
595    Ok(())
596}
597
598pub(crate) fn read_tools(entry: &NativeMap, caps: &Caps) -> Result<ToolLists, MapError> {
599    Ok(match caps.tool_filter {
600        Some(ToolFilterMech::AllowDeny { allow, deny }) => ToolLists {
601            allow: string_list(entry, allow)?,
602            deny: string_list(entry, deny)?,
603        },
604        Some(ToolFilterMech::Allow(allow)) => ToolLists {
605            allow: string_list(entry, allow)?,
606            deny: None,
607        },
608        None => ToolLists::default(),
609    })
610}
611
612/// Writes the allowlisted passthrough fields; a timeout must be a
613/// non-negative number in the client's unit.
614pub(crate) fn write_passthrough(
615    entry: &mut NativeMap,
616    caps: &Caps,
617    server: &RenderedServer,
618) -> Result<(), MapError> {
619    for (key, value) in server.passthrough.iter() {
620        if !caps.passthrough_allowlist.contains(&key) {
621            return unsupported(key);
622        }
623        if let Some(timeout) = caps.timeouts.iter().find(|timeout| timeout.key == key)
624            && timeout.duration(value).is_none()
625        {
626            return shape(key, timeout.expected());
627        }
628        entry.insert(key, value.clone());
629    }
630    Ok(())
631}
632
633/// Copies the keys of `existing` the mapper does not model.
634pub(crate) fn carry_over(
635    entry: &mut NativeMap,
636    existing: Option<&NativeMap>,
637    is_modeled: impl Fn(&str) -> bool,
638) {
639    for (key, value) in existing.into_iter().flat_map(NativeMap::iter) {
640        if !is_modeled(key) {
641            entry.insert(key, value.clone());
642        }
643    }
644}
645
646/// Files the keys of `entry` that are passthrough or unmodeled.
647pub(crate) fn split_rest(
648    def: &mut ServerDef,
649    entry: &NativeMap,
650    caps: &Caps,
651    is_modeled: impl Fn(&str) -> bool,
652) {
653    for (key, value) in entry.iter() {
654        if caps.passthrough_allowlist.contains(&key) {
655            def.passthrough.insert(key, value.clone());
656        } else if !is_modeled(key) {
657            def.unmapped.insert(key, value.clone());
658        }
659    }
660}
661
662/// Removes keys holding an empty array or object.
663pub(crate) fn drop_empty(entry: &mut NativeMap, keys: &[&str]) {
664    for key in keys {
665        let empty = match entry.get(key) {
666            Some(NativeValue::Array(items)) => items.is_empty(),
667            Some(NativeValue::Object(map)) => map.is_empty(),
668            _ => false,
669        };
670        if empty {
671            entry.remove(key);
672        }
673    }
674}
675
676pub(crate) fn unsupported<T>(field: &str) -> Result<T, MapError> {
677    Err(MapError::UnsupportedField {
678        field: field.to_owned(),
679    })
680}
681
682pub(crate) fn shape<T>(field: &str, expected: &'static str) -> Result<T, MapError> {
683    Err(MapError::UnexpectedShape {
684        field: field.to_owned(),
685        expected,
686    })
687}
688
689pub(crate) fn strings(items: Vec<String>) -> NativeValue {
690    NativeValue::Array(items.into_iter().map(NativeValue::String).collect())
691}
692
693pub(crate) fn string_map(map: &BTreeMap<String, String>) -> NativeValue {
694    NativeValue::Object(
695        map.iter()
696            .map(|(key, value)| (key.as_str(), NativeValue::from(value.as_str())))
697            .collect(),
698    )
699}
700
701pub(crate) fn string_field(entry: &NativeMap, key: &str) -> Result<Option<String>, MapError> {
702    match entry.get(key) {
703        None => Ok(None),
704        Some(NativeValue::String(value)) => Ok(Some(value.clone())),
705        Some(_) => shape(key, "a string"),
706    }
707}
708
709pub(crate) fn string_list(entry: &NativeMap, key: &str) -> Result<Option<Vec<String>>, MapError> {
710    let Some(value) = entry.get(key) else {
711        return Ok(None);
712    };
713    value
714        .as_array()
715        .and_then(|items| {
716            items
717                .iter()
718                .map(|item| item.as_str().map(str::to_owned))
719                .collect::<Option<Vec<_>>>()
720        })
721        .map(Some)
722        .ok_or_else(|| MapError::UnexpectedShape {
723            field: key.to_owned(),
724            expected: "an array of strings",
725        })
726}
727
728pub(crate) fn string_map_field(
729    entry: &NativeMap,
730    key: &str,
731) -> Result<Option<BTreeMap<String, String>>, MapError> {
732    let Some(value) = entry.get(key) else {
733        return Ok(None);
734    };
735    value
736        .as_object()
737        .and_then(|map| {
738            map.iter()
739                .map(|(name, value)| {
740                    value
741                        .as_str()
742                        .map(|value| (name.to_owned(), value.to_owned()))
743                })
744                .collect::<Option<BTreeMap<_, _>>>()
745        })
746        .map(Some)
747        .ok_or_else(|| MapError::UnexpectedShape {
748            field: key.to_owned(),
749            expected: "an object of strings",
750        })
751}
752
753/// Whether `command` is a Windows `.cmd`/`.bat` shim: a known npm launcher
754/// named without extension, or any `.cmd`/`.bat` file.
755fn is_windows_shim(command: &str) -> bool {
756    let name = command
757        .rsplit(['/', '\\'])
758        .next()
759        .unwrap_or(command)
760        .to_ascii_lowercase();
761    name.ends_with(".cmd") || name.ends_with(".bat") || WINDOWS_SHIMS.contains(&name.as_str())
762}
763
764/// `npx args...` as `cmd /c npx args...` (SPEC 5.2); other commands as they
765/// are.
766fn shell_shim(command: &str, args: &[String]) -> (String, Vec<String>) {
767    if !is_windows_shim(command) {
768        return (command.to_owned(), args.to_vec());
769    }
770    let mut shimmed = Vec::with_capacity(args.len() + 2);
771    shimmed.push("/c".to_owned());
772    shimmed.push(command.to_owned());
773    shimmed.extend_from_slice(args);
774    ("cmd".to_owned(), shimmed)
775}
776
777/// The inverse of [`shell_shim`]: `cmd /c <shim> args...` as `<shim>
778/// args...`. A `cmd /c` running anything else is kept as written, so it
779/// reads back as it would be written.
780fn shell_unshim(command: &str, args: &[String]) -> Option<(String, Vec<String>)> {
781    let is_cmd = command.eq_ignore_ascii_case("cmd") || command.eq_ignore_ascii_case("cmd.exe");
782    match args {
783        [flag, inner, rest @ ..]
784            if is_cmd && flag.eq_ignore_ascii_case("/c") && is_windows_shim(inner) =>
785        {
786            Some((inner.clone(), rest.to_vec()))
787        }
788        _ => None,
789    }
790}
791
792fn write_canonical(value: &NativeValue, out: &mut String) {
793    match value {
794        NativeValue::Null => out.push_str("null"),
795        NativeValue::Bool(value) => out.push_str(if *value { "true" } else { "false" }),
796        NativeValue::Integer(value) => out.push_str(&value.to_string()),
797        NativeValue::Float(value) => out.push_str(&format!("{value:?}")),
798        NativeValue::String(value) => push_string(value, out),
799        NativeValue::Datetime(value) => {
800            out.push_str("datetime(");
801            push_string(value, out);
802            out.push(')');
803        }
804        NativeValue::Array(items) => {
805            out.push('[');
806            for (index, item) in items.iter().enumerate() {
807                if index > 0 {
808                    out.push(',');
809                }
810                write_canonical(item, out);
811            }
812            out.push(']');
813        }
814        NativeValue::Object(map) => {
815            let mut members: Vec<(&str, &NativeValue)> = map.iter().collect();
816            members.sort_by(|a, b| a.0.cmp(b.0));
817            out.push('{');
818            for (index, (key, item)) in members.into_iter().enumerate() {
819                if index > 0 {
820                    out.push(',');
821                }
822                push_string(key, out);
823                out.push(':');
824                write_canonical(item, out);
825            }
826            out.push('}');
827        }
828    }
829}
830
831fn push_string(value: &str, out: &mut String) {
832    out.push_str(&serde_json::to_string(value).expect("a string serializes"));
833}