Skip to main content

oxdock_process/
expand.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::{Result, anyhow, bail};
5
6use crate::contract::CommandContext;
7
8/// Maximum bytes to buffer while scanning for closing delimiter.
9/// If exceeded without finding closing delimiter, buffered bytes are flushed as literals.
10const MAX_PLACEHOLDER_SCAN: usize = 1024;
11
12/// Configurable delimiter syntax for template expansion.
13pub struct TemplateDelimiters {
14    pub open: &'static [u8],
15    pub close: &'static [u8],
16}
17
18impl Default for TemplateDelimiters {
19    fn default() -> Self {
20        Self {
21            open: b"{{",
22            close: b"}}",
23        }
24    }
25}
26
27/// Resolver for `{{ MODULE::FUNC(args) }}` placeholder calls.
28///
29/// Receives the module name, function name, and already resolved argument
30/// values, and returns the call result. Only pure value returning host
31/// functions may back this: no handles, no pipes, no I/O. The resolver
32/// carries no formatting logic; formatting lives with the function.
33pub type PlaceholderCall = Arc<
34    dyn Fn(&str, &str, Vec<oxdock_parser::Value>) -> Result<oxdock_parser::Value> + Send + Sync,
35>;
36
37/// Streaming template expansion state machine.
38///
39/// Processes input bytes incrementally, expanding `{{ env:KEY }}` placeholders.
40/// At most `MAX_PLACEHOLDER_SCAN` bytes are held in buffer. Plain text streams
41/// flush immediately with zero buffering.
42pub struct StreamingExpand {
43    /// Bytes accumulated as key payload inside `{{ ... }}` (no open delimiter prefix).
44    buffer: Vec<u8>,
45    /// Explicit key=value overrides (take precedence over env).
46    overrides: HashMap<String, String>,
47    /// Environment variable lookup.
48    env: HashMap<String, String>,
49    /// Structured variable lookup (for key-path evaluation).
50    vars: HashMap<String, oxdock_parser::Value>,
51    /// Optional dispatcher for `{{ MODULE::FUNC(args) }}` calls. When set,
52    /// placeholders holding a call expression are evaluated through it.
53    /// Carries dispatch only; formatting stays with the callee.
54    call_resolver: Option<PlaceholderCall>,
55    /// State: are we currently inside a placeholder?
56    in_placeholder: bool,
57    /// Trailing opening byte from previous chunk : deferred across chunks.
58    pending_brace: bool,
59    /// Trailing closing byte from previous chunk : deferred across chunks.
60    pending_close_brace: bool,
61    /// Trailing backslash from previous chunk : deferred across chunks so
62    /// `\{{` split across a boundary still emits a literal opener.
63    pending_escape: bool,
64    /// Trailing `\` + `{` from previous chunk : deferred across chunks so
65    /// a `\{` split across a boundary still resolves as an escape pair.
66    pending_escape_brace: bool,
67    /// Configurable delimiter syntax.
68    delimiters: TemplateDelimiters,
69}
70
71impl StreamingExpand {
72    /// Create with env vars and optional explicit overrides.
73    /// Overrides take precedence over env vars.
74    pub fn new(overrides: &[(String, String)], env: &HashMap<String, String>) -> Self {
75        Self {
76            buffer: Vec::with_capacity(256),
77            overrides: overrides.iter().cloned().collect(),
78            env: env.clone(),
79            vars: HashMap::new(),
80            call_resolver: None,
81            in_placeholder: false,
82            pending_brace: false,
83            pending_close_brace: false,
84            pending_escape: false,
85            pending_escape_brace: false,
86            delimiters: TemplateDelimiters::default(),
87        }
88    }
89
90    /// Create with env vars, structured variables, and optional explicit overrides.
91    /// Enables key-path evaluation in template tags (e.g., `{{ pkg.package.name }}`).
92    pub fn with_vars(mut self, vars: &HashMap<String, oxdock_parser::Value>) -> Self {
93        self.vars = vars.clone();
94        self
95    }
96
97    /// Enable `{{ MODULE::FUNC(args) }}` calls, dispatched through `resolver`.
98    /// Args are `$var.path` references, string, int, float, and bool
99    /// literals, or `{key: value}` and `[item]` literals nesting those
100    /// same shapes. Unknown functions and bad arity fail strict at expansion.
101    pub fn with_call_resolver(mut self, resolver: PlaceholderCall) -> Self {
102        self.call_resolver = Some(resolver);
103        self
104    }
105
106    /// Process a chunk of input bytes, writing expanded output to `out`.
107    /// Returns early on empty input to preserve pending boundary state.
108    pub fn process_bytes(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<usize> {
109        if input.is_empty() {
110            return Ok(0);
111        }
112
113        let start_len = out.len();
114        let mut i = 0;
115
116        // Handle pending close brace from previous chunk
117        if self.pending_close_brace {
118            self.pending_close_brace = false;
119            if input[0] == self.delimiters.close[1] {
120                // Confirmed close delimiter across boundary : extract key, lookup, emit
121                let key = extract_key(&self.buffer);
122                let value = lookup(
123                    &key,
124                    &self.overrides,
125                    &self.env,
126                    &self.vars,
127                    self.call_resolver.as_ref(),
128                )?;
129                out.extend_from_slice(value.as_bytes());
130                self.buffer.clear();
131                self.in_placeholder = false;
132                i = self.delimiters.close.len() - 1; // Skip input[0] (the second byte)
133            } else {
134                // Lone closing byte : treat as literal part of key
135                // Push it to buffer, then let scan_placeholder process input[0]
136                self.buffer.push(self.delimiters.close[0]);
137                i = 0; // Do NOT skip input[0]: let scan_placeholder handle it
138            }
139        }
140
141        // Handle pending open brace from previous chunk
142        if self.pending_brace {
143            self.pending_brace = false;
144            if input[0] == self.delimiters.open[1] {
145                // Confirmed `{{` across boundary : enter PlaceholderScan
146                self.in_placeholder = true;
147                self.buffer.clear();
148                i = 1; // Skip the second open byte
149            } else {
150                // Single open byte was just a literal : flush it
151                out.push(self.delimiters.open[0]);
152            }
153        }
154
155        // Handle pending escape pair from previous chunk: a trailing `\{`
156        // combines with a leading `{` into a literal opener. Anything
157        // else means both bytes were literal; re-emit them, then let the
158        // scan below handle this chunk from the start.
159        if self.pending_escape_brace {
160            self.pending_escape_brace = false;
161            if !input.is_empty() && input[0] == self.delimiters.open[1] {
162                out.extend_from_slice(b"{{");
163                i = 1;
164            } else {
165                out.push(b'\\');
166                out.push(self.delimiters.open[0]);
167            }
168        }
169
170        // Handle pending escape from previous chunk: a lone trailing `\`
171        // combines with a leading `{{` into a literal opener, or with a
172        // leading `\` into a literal backslash (the pair is complete, so
173        // whatever follows processes normally). A lone trailing `{`
174        // cannot decide yet, so it joins the deferred pair above.
175        if self.pending_escape {
176            self.pending_escape = false;
177            if input.len() >= 2 && input[0] == b'{' && input[1] == b'{' {
178                out.extend_from_slice(b"{{");
179                i = 2;
180            } else if input.len() == 1 && input[0] == self.delimiters.open[0] {
181                self.pending_escape_brace = true;
182                i = 1;
183            } else if !input.is_empty() && input[0] == b'\\' {
184                out.push(b'\\');
185                i = 1;
186            } else {
187                // Not an escape : the backslash was literal; reprocess
188                // this chunk from the start (a lone `{` still defers via
189                // the pending_brace path below).
190                out.push(b'\\');
191            }
192        }
193
194        if self.in_placeholder {
195            // We're inside a placeholder : scan for closing delimiter
196            i = self.scan_placeholder(input, i, out)?;
197        }
198
199        // Normal state : scan for opening byte or flush literals
200        while i < input.len() {
201            if input[i] == b'\\' {
202                if i + 2 < input.len() && input[i + 1] == b'{' && input[i + 2] == b'{' {
203                    // Escaped opener : emit a literal `{{`, consume all three
204                    out.extend_from_slice(b"{{");
205                    i += 3;
206                } else if i + 2 == input.len() && input[i + 1] == self.delimiters.open[0] {
207                    // `\{` ends the chunk : defer the pair; the next
208                    // chunk decides literal `{{` vs literal `\` + `{`.
209                    self.pending_escape_brace = true;
210                    i += 2;
211                } else if i + 1 < input.len() && input[i + 1] == b'\\' {
212                    // Escaped backslash : emit one `\`, consume both (this
213                    // keeps `\\{{ ... }}` expanding, matching the lenient
214                    // interpolator used for command arguments)
215                    out.push(b'\\');
216                    i += 2;
217                } else if i + 1 == input.len() {
218                    // Trailing backslash : defer across the chunk boundary
219                    self.pending_escape = true;
220                    i += 1;
221                } else {
222                    // Ordinary backslash : literal, reprocess what follows
223                    out.push(b'\\');
224                    i += 1;
225                }
226            } else if input[i] == self.delimiters.open[0] {
227                if i + 1 < input.len() && input[i + 1] == self.delimiters.open[1] {
228                    // Found open delimiter : enter PlaceholderScan
229                    self.in_placeholder = true;
230                    self.buffer.clear();
231                    i += 2;
232                    i = self.scan_placeholder(input, i, out)?;
233                } else if i + 1 == input.len() {
234                    // Opening byte is the LAST byte of chunk : defer
235                    self.pending_brace = true;
236                    i += 1;
237                } else {
238                    // Single opening byte in the middle : flush as literal
239                    out.push(self.delimiters.open[0]);
240                    i += 1;
241                }
242            } else {
243                // Flush literal bytes until we find an opening byte, a
244                // backslash (potential `\{{` escape), or end of chunk
245                let start = i;
246                while i < input.len() && input[i] != self.delimiters.open[0] && input[i] != b'\\' {
247                    i += 1;
248                }
249                out.extend_from_slice(&input[start..i]);
250            }
251        }
252
253        Ok(out.len() - start_len)
254    }
255
256    /// Flush remaining buffer. Incomplete placeholders are treated as literals.
257    pub fn flush(mut self, out: &mut Vec<u8>) -> Result<()> {
258        // Emit deferred closing byte if present
259        if self.pending_close_brace {
260            self.buffer.push(self.delimiters.close[0]);
261            self.pending_close_brace = false;
262        }
263        // Emit deferred opening byte if present
264        if self.pending_brace {
265            out.push(self.delimiters.open[0]);
266            self.pending_brace = false;
267        }
268        // Emit deferred backslash if present
269        if self.pending_escape {
270            out.push(b'\\');
271            self.pending_escape = false;
272        }
273        // Emit deferred escape pair if present
274        if self.pending_escape_brace {
275            out.push(b'\\');
276            out.push(self.delimiters.open[0]);
277            self.pending_escape_brace = false;
278        }
279        // If inside placeholder, emit open delimiter prefix ONCE before buffer
280        if self.in_placeholder {
281            out.extend_from_slice(self.delimiters.open);
282            self.in_placeholder = false;
283        }
284        // Flush remaining buffer as literal text
285        out.extend_from_slice(&self.buffer);
286        self.buffer.clear();
287        Ok(())
288    }
289
290    /// Process a complete string (convenience for short command arguments).
291    pub fn expand_string(self, input: &str) -> Result<String> {
292        let mut out = Vec::with_capacity(input.len());
293        let mut expander = self;
294        expander.process_bytes(input.as_bytes(), &mut out)?;
295        expander.flush(&mut out)?;
296        Ok(String::from_utf8(out).unwrap_or_default())
297    }
298
299    /// Scan for closing delimiter starting at position `i`.
300    /// Returns the next position to process after the placeholder.
301    fn scan_placeholder(&mut self, input: &[u8], mut i: usize, out: &mut Vec<u8>) -> Result<usize> {
302        while i < input.len() {
303            if input[i] == self.delimiters.close[0] {
304                if i + 1 < input.len() && input[i + 1] == self.delimiters.close[1] {
305                    // Found closing delimiter : extract key, lookup, emit expansion
306                    let key = extract_key(&self.buffer);
307                    let value = lookup(
308                        &key,
309                        &self.overrides,
310                        &self.env,
311                        &self.vars,
312                        self.call_resolver.as_ref(),
313                    )?;
314                    out.extend_from_slice(value.as_bytes());
315                    self.buffer.clear();
316                    self.in_placeholder = false;
317                    return Ok(i + 2);
318                }
319                if i + 1 == input.len() {
320                    // Closing byte is the LAST byte : defer to next chunk
321                    self.pending_close_brace = true;
322                    return Ok(i + 1);
323                }
324            }
325            self.buffer.push(input[i]);
326            i += 1;
327
328            // Buffer limit exceeded : flush as literal
329            if self.buffer.len() > MAX_PLACEHOLDER_SCAN {
330                out.extend_from_slice(self.delimiters.open);
331                out.extend_from_slice(&self.buffer);
332                self.buffer.clear();
333                self.in_placeholder = false;
334                return Ok(i);
335            }
336        }
337        Ok(i)
338    }
339}
340
341/// Extract and trim key from buffer content (the bytes between delimiters).
342fn extract_key(buffer: &[u8]) -> String {
343    String::from_utf8_lossy(buffer).trim().to_string()
344}
345
346/// Lookup a key in overrides and env, stripping namespace prefixes.
347///
348/// Strict resolution contract:
349/// - `{{ KEY }}` (bare) → overrides only
350/// - `{{ env:KEY }}` → overrides then env
351/// - `{{ $var }}` → script vars
352/// - `{{ $var.field }}` → script var key-path
353/// - `{{ MODULE::FUNC(args) }}` → placeholder call via `calls`
354///
355/// All missing or invalid references return an error.
356fn lookup(
357    raw_key: &str,
358    overrides: &HashMap<String, String>,
359    env: &HashMap<String, String>,
360    vars: &HashMap<String, oxdock_parser::Value>,
361    calls: Option<&PlaceholderCall>,
362) -> Result<String> {
363    let key = raw_key.trim();
364
365    // 1. Explicit overrides (command-level CLI flags: KEY=val)
366    if let Some(val) = overrides.get(key) {
367        return Ok(val.clone());
368    }
369
370    // 2. Environment variables: must be prefixed with "env:"
371    if let Some(env_key) = key.strip_prefix("env:") {
372        if let Some(val) = overrides.get(env_key).or_else(|| env.get(env_key)) {
373            return Ok(val.clone());
374        }
375        let hint = if vars.contains_key(env_key) {
376            format!("; did you mean '${env_key}' (script variable)?")
377        } else {
378            String::new()
379        };
380        bail!("undefined environment variable: '{env_key}'{hint}");
381    }
382
383    // 3. Script variables: must be prefixed with "$"
384    if let Some(var_key) = key.strip_prefix('$') {
385        if var_key.contains('.') {
386            let parts: Vec<&str> = var_key.split('.').collect();
387            return resolve_key_path_strict(&parts, vars);
388        }
389        if let Some(val) = vars.get(var_key) {
390            return Ok(format_value_for_string(val));
391        }
392        let hint = if env.contains_key(var_key) {
393            format!("; did you mean 'env:{var_key}' (environment variable)?")
394        } else if overrides.contains_key(var_key) {
395            format!("; did you mean '{var_key}' (step override)?")
396        } else {
397            String::new()
398        };
399        bail!("undefined script variable: '${var_key}'{hint}");
400    }
401
402    // 4. Placeholder calls: `MODULE::FUNC(args)` dispatches through the
403    // registered resolver. Without one, the shape falls through to the
404    // invalid placeholder error below.
405    if let Some((module, func, args_src)) = parse_call(key) {
406        let Some(resolver) = calls else {
407            bail!(
408                "placeholder call '{module}::{func}' has no function registry; register one with with_call_resolver"
409            );
410        };
411        let mut args = Vec::with_capacity(args_src.len());
412        for src in args_src {
413            args.push(resolve_call_arg(&src, vars)?);
414        }
415        let result = resolver(module, func, args)?;
416        return Ok(format_value_for_string(&result));
417    }
418
419    // 5. Unprefixed key: could be a missing step override or invalid syntax
420    if !key.is_empty()
421        && key
422            .chars()
423            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
424    {
425        let hint = if vars.contains_key(key) {
426            format!("; did you mean '${key}' (script variable)?")
427        } else if env.contains_key(key) {
428            format!("; did you mean 'env:{key}' (environment variable)?")
429        } else {
430            String::new()
431        };
432        bail!("missing required step override argument: '{key}'{hint}");
433    }
434    bail!(
435        "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
436    );
437}
438
439/// Split a placeholder call body into module, function, and raw args.
440///
441/// Accepts `MODULE::FUNC()` and `MODULE::FUNC(a, b)`. Returns `None` when
442/// the body is not call shaped, so plain key paths keep their own errors.
443fn parse_call(key: &str) -> Option<(&str, &str, Vec<String>)> {
444    let (module, rest) = key.split_once("::")?;
445    if module.is_empty()
446        || !module
447            .chars()
448            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
449    {
450        return None;
451    }
452    let (func, args_src) = rest.split_once('(')?;
453    let func = func.trim();
454    if func.is_empty()
455        || !func
456            .chars()
457            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
458    {
459        return None;
460    }
461    let args_src = args_src.strip_suffix(')')?;
462    Some((module, func, split_args(args_src)))
463}
464
465/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
466/// outside the streaming expander. Returns `None` when the body is not
467/// call shaped, so plain keys keep their own handling. Shared with
468/// engine-side string expansion so both paths parse identically.
469pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
470    let (module, func, args) = parse_call(key.trim())?;
471    Some((module.to_string(), func.to_string(), args))
472}
473
474/// Maximum nesting for map and list literals in placeholder call args.
475const MAX_LITERAL_DEPTH: usize = 16;
476
477/// Split call args on top level commas, keeping quoted strings and
478/// `{...}` / `[...]` literals intact. Commas nested inside literals
479/// belong to the literal, not the argument list. Nested calls stay
480/// rejected: only data literals nest, never `MODULE::FUNC(...)`.
481fn split_args(src: &str) -> Vec<String> {
482    split_top_level(src, ',')
483}
484
485/// Split on a top level separator, keeping quoted strings and
486/// `{...}` / `[...]` literals intact.
487fn split_top_level(src: &str, sep: char) -> Vec<String> {
488    let mut out = Vec::new();
489    let mut current = String::new();
490    let mut in_string = false;
491    let mut escaped = false;
492    let mut depth: usize = 0;
493    for c in src.chars() {
494        if in_string {
495            current.push(c);
496            if escaped {
497                escaped = false;
498            } else if c == '\\' {
499                escaped = true;
500            } else if c == '"' {
501                in_string = false;
502            }
503            continue;
504        }
505        match c {
506            '"' => {
507                in_string = true;
508                current.push(c);
509            }
510            '{' | '[' => {
511                depth += 1;
512                current.push(c);
513            }
514            '}' | ']' => {
515                depth = depth.saturating_sub(1);
516                current.push(c);
517            }
518            _ if c == sep && depth == 0 => {
519                out.push(current.trim().to_string());
520                current.clear();
521            }
522            _ => current.push(c),
523        }
524    }
525    let last = current.trim();
526    if !(out.is_empty() && last.is_empty()) {
527        out.push(last.to_string());
528    }
529    out
530}
531
532/// Resolve one placeholder call argument against script variables for
533/// call resolution outside the streaming expander. Same grammar there:
534/// `$var.path`, string, int, float, and bool literals, plus `{...}`
535/// and `[...]` literals holding those shapes nested.
536pub fn resolve_placeholder_arg(
537    src: &str,
538    vars: &HashMap<String, oxdock_parser::Value>,
539) -> Result<oxdock_parser::Value> {
540    resolve_call_arg(src, vars)
541}
542
543/// Resolve one call argument to a value: `$var.path` from vars, a
544/// string, int, float, or bool literal, or a `{key: value}` map or
545/// `[item]` list literal holding those same shapes nested.
546fn resolve_call_arg(
547    src: &str,
548    vars: &HashMap<String, oxdock_parser::Value>,
549) -> Result<oxdock_parser::Value> {
550    resolve_call_value(src, vars, 0)
551}
552
553fn resolve_call_value(
554    src: &str,
555    vars: &HashMap<String, oxdock_parser::Value>,
556    depth: usize,
557) -> Result<oxdock_parser::Value> {
558    if depth > MAX_LITERAL_DEPTH {
559        bail!("placeholder call argument nests too deep (limit {MAX_LITERAL_DEPTH})");
560    }
561    if let Some(path) = src.strip_prefix('$') {
562        let parts: Vec<&str> = path.split('.').collect();
563        return resolve_value_path(&parts, vars);
564    }
565    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
566        return Ok(oxdock_parser::Value::string(unescape_literal(
567            &src[1..src.len() - 1],
568        )?));
569    }
570    if let Some(inner) = strip_wrapped(src, '{', '}') {
571        return resolve_call_map(inner, vars, depth);
572    }
573    if let Some(inner) = strip_wrapped(src, '[', ']') {
574        return resolve_call_list(inner, vars, depth);
575    }
576    match src {
577        "true" => return Ok(oxdock_parser::Value::bool(true)),
578        "false" => return Ok(oxdock_parser::Value::bool(false)),
579        _ => {}
580    }
581    if let Ok(i) = src.parse::<i64>() {
582        return Ok(oxdock_parser::Value::int(i));
583    }
584    if let Ok(f) = src.parse::<f64>() {
585        return Ok(oxdock_parser::Value::float(f));
586    }
587    bail!(
588        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
589    )
590}
591
592/// Strip one wrapping delimiter pair, rejecting unbalanced closers
593/// inside: the opener at 0 must match the closer at the end with no
594/// earlier top level closer.
595fn strip_wrapped(src: &str, open: char, close: char) -> Option<&str> {
596    if !src.starts_with(open) || !src.ends_with(close) || src.len() < 2 {
597        return None;
598    }
599    let mut in_string = false;
600    let mut escaped = false;
601    let mut depth: usize = 0;
602    for (idx, c) in src.char_indices() {
603        if in_string {
604            if escaped {
605                escaped = false;
606            } else if c == '\\' {
607                escaped = true;
608            } else if c == '"' {
609                in_string = false;
610            }
611            continue;
612        }
613        match c {
614            '"' => in_string = true,
615            _ if c == open => depth += 1,
616            _ if c == close => {
617                depth -= 1;
618                if depth == 0 && idx != src.len() - close.len_utf8() {
619                    return None;
620                }
621            }
622            _ => {}
623        }
624    }
625    if depth != 0 {
626        return None;
627    }
628    Some(&src[open.len_utf8()..src.len() - close.len_utf8()])
629}
630
631/// Resolve a `{key: value}` map literal. Keys are bare ASCII
632/// identifiers or double quoted strings; values recurse through
633/// [`resolve_call_value`].
634fn resolve_call_map(
635    inner: &str,
636    vars: &HashMap<String, oxdock_parser::Value>,
637    depth: usize,
638) -> Result<oxdock_parser::Value> {
639    let mut entries = std::collections::BTreeMap::new();
640    if inner.trim().is_empty() {
641        return Ok(oxdock_parser::Value::map(entries));
642    }
643    for entry in split_top_level(inner, ',') {
644        let parts = split_top_level(&entry, ':');
645        if parts.len() != 2 {
646            bail!("invalid map literal entry '{entry}': use key: value");
647        }
648        let key = resolve_call_key(&parts[0])?;
649        if entries.contains_key(&key) {
650            bail!("duplicate key '{key}' in map literal");
651        }
652        let value = resolve_call_value(&parts[1], vars, depth + 1)?;
653        entries.insert(key, value);
654    }
655    Ok(oxdock_parser::Value::map(entries))
656}
657
658/// Resolve one map literal key: a bare ASCII identifier or a double
659/// quoted string.
660fn resolve_call_key(src: &str) -> Result<String> {
661    if src.len() >= 2 && src.starts_with('"') && src.ends_with('"') {
662        return unescape_literal(&src[1..src.len() - 1]);
663    }
664    if !src.is_empty() && src.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
665        return Ok(src.to_string());
666    }
667    bail!("invalid map literal key '{src}': use name or \"name\"")
668}
669
670/// Resolve a `[item]` list literal, elements recursing through
671/// [`resolve_call_value`].
672fn resolve_call_list(
673    inner: &str,
674    vars: &HashMap<String, oxdock_parser::Value>,
675    depth: usize,
676) -> Result<oxdock_parser::Value> {
677    let mut items = Vec::new();
678    if inner.trim().is_empty() {
679        return Ok(oxdock_parser::Value::list(items));
680    }
681    for item in split_top_level(inner, ',') {
682        items.push(resolve_call_value(&item, vars, depth + 1)?);
683    }
684    Ok(oxdock_parser::Value::list(items))
685}
686
687/// Unescape a double quoted literal: `\\` and `\"` only. Anything else
688/// keeps its backslash so template text stays predictable.
689fn unescape_literal(src: &str) -> Result<String> {
690    let mut out = String::with_capacity(src.len());
691    let mut chars = src.chars();
692    while let Some(c) = chars.next() {
693        if c != '\\' {
694            out.push(c);
695            continue;
696        }
697        match chars.next() {
698            Some('\\') => out.push('\\'),
699            Some('"') => out.push('"'),
700            Some(other) => {
701                out.push('\\');
702                out.push(other);
703            }
704            None => bail!("unterminated escape in placeholder string literal"),
705        }
706    }
707    Ok(out)
708}
709
710/// Resolve a dotted path against vars, cloning the value for the caller.
711/// Mirrors `resolve_key_path_strict` but returns the value instead of
712/// its string form so calls receive typed arguments.
713fn resolve_value_path(
714    parts: &[&str],
715    vars: &HashMap<String, oxdock_parser::Value>,
716) -> Result<oxdock_parser::Value> {
717    if parts.is_empty() || parts[0].is_empty() {
718        bail!("invalid placeholder call argument: empty variable reference");
719    }
720    let root_key = parts[0];
721    let mut current = vars
722        .get(root_key)
723        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?
724        .clone();
725    for &segment in &parts[1..] {
726        if segment.contains('(') || segment.contains(')') {
727            bail!("nested calls are not supported in placeholder arguments");
728        }
729        if let Some(map) = current.as_map() {
730            current = map
731                .get(segment)
732                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?
733                .clone();
734        } else if let Some(list) = current.as_list() {
735            let idx: usize = segment
736                .parse()
737                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
738            current = list
739                .get(idx)
740                .ok_or_else(|| {
741                    anyhow!(
742                        "index {idx} out of bounds for list '${root_key}' (len: {})",
743                        list.len()
744                    )
745                })?
746                .clone();
747        } else {
748            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
749        }
750    }
751    Ok(current)
752}
753
754/// Resolve nested key-paths against the vars map.
755///
756/// Fails explicitly on missing object keys, out-of-bounds array indices,
757/// or type mismatches (e.g. trying to access a property on a primitive).
758fn resolve_key_path_strict(
759    parts: &[&str],
760    vars: &HashMap<String, oxdock_parser::Value>,
761) -> Result<String> {
762    let root_key = parts[0];
763    let mut current = vars
764        .get(root_key)
765        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?;
766
767    for &segment in &parts[1..] {
768        if let Some(map) = current.as_map() {
769            current = map
770                .get(segment)
771                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?;
772        } else if let Some(list) = current.as_list() {
773            let idx: usize = segment
774                .parse()
775                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
776            current = list.get(idx).ok_or_else(|| {
777                anyhow!(
778                    "index {idx} out of bounds for list '${root_key}' (len: {})",
779                    list.len()
780                )
781            })?;
782        } else {
783            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
784        }
785    }
786
787    Ok(format_value_for_string(current))
788}
789
790/// Format a Value as a string for inline interpolation.
791/// Render a script value as inline text: the single renderer behind
792/// placeholder expansion everywhere (streaming file templates and
793/// engine string expansion alike), so one value renders one way in
794/// every context.
795///
796/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
797/// `f64` already produces the shortest round-trip decimal (Ryū since
798/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
799/// `3.140000`) with no extra dependency.
800pub fn format_value_for_string(val: &oxdock_parser::Value) -> String {
801    if let Some(s) = val.as_str() {
802        return s.to_string();
803    }
804    if let Some(i) = val.as_i64() {
805        return i.to_string();
806    }
807    if let Some(f) = val.as_f64() {
808        return f.to_string();
809    }
810    if let Some(b) = val.as_bool() {
811        return b.to_string();
812    }
813    // Pipes render through `Display` (`<pipe>`) via the fallthrough below;
814    // handles are opaque and have no string form to spell.
815    if let Some(d) = val.as_duration() {
816        return oxdock_parser::command::format_duration(&d);
817    }
818    if let Some(p) = val.as_path() {
819        return p.to_string_lossy().to_string();
820    }
821    if let Some(items) = val.as_list() {
822        return items
823            .iter()
824            .map(format_value_for_string)
825            .collect::<Vec<_>>()
826            .join(" ");
827    }
828    if let Some(map) = val.as_map() {
829        return map
830            .iter()
831            .map(|(k, v)| format!("\"{}\": {}", k, format_value_for_string(v)))
832            .collect::<Vec<_>>()
833            .join(", ");
834    }
835    if let Some(id) = val.as_handle() {
836        return format!("task#{}", id);
837    }
838    format!("{}", val)
839}
840
841// Legacy functions for backward compatibility
842
843pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
844where
845    F: FnMut(&str) -> Option<String>,
846{
847    let mut out = String::with_capacity(input.len());
848    let mut chars = input.chars().peekable();
849    while let Some(c) = chars.next() {
850        if c == '{' {
851            if let Some(&'{') = chars.peek() {
852                chars.next(); // consume second '{'
853                let mut content = String::new();
854                let mut closed = false;
855                // Look ahead for closing }}
856                let mut inner_chars = chars.clone();
857                while let Some(ch) = inner_chars.next() {
858                    if ch == '}'
859                        && let Some(&'}') = inner_chars.peek()
860                    {
861                        closed = true;
862                        break;
863                    }
864                    content.push(ch);
865                }
866
867                if closed {
868                    // Advance main iterator past content and closing braces.
869                    // Count chars, not bytes: content may contain multi-byte
870                    // UTF-8 (e.g. non-ASCII placeholder names).
871                    for _ in 0..content.chars().count() {
872                        chars.next();
873                    }
874                    chars.next(); // first }
875                    chars.next(); // second }
876
877                    let key = content.trim();
878                    if !key.is_empty() {
879                        out.push_str(&lookup_fn(key).unwrap_or_default());
880                    }
881                } else {
882                    out.push('{');
883                    out.push('{');
884                }
885            } else {
886                out.push('{');
887            }
888        } else {
889            out.push(c);
890        }
891    }
892    out
893}
894
895pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
896    expand_with_lookup(input, |name| {
897        if let Some(key) = name.strip_prefix("env:") {
898            script_envs
899                .get(key)
900                .cloned()
901                .or_else(|| std::env::var(key).ok())
902        } else {
903            None
904        }
905    })
906}
907
908pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
909    expand_with_lookup(input, |name| {
910        if let Some(key) = name.strip_prefix("env:") {
911            ctx.envs().get(key).cloned()
912        } else {
913            None
914        }
915    })
916}
917
918#[cfg(test)]
919mod tests {
920    use super::*;
921    use std::collections::HashMap;
922
923    #[test]
924    fn basic_expansion() {
925        let mut env = HashMap::new();
926        env.insert("NAME".into(), "World".into());
927        let expander = StreamingExpand::new(&[], &env);
928        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
929        assert_eq!(result, "Hello World");
930    }
931
932    #[test]
933    fn multiple_vars() {
934        let mut env = HashMap::new();
935        env.insert("A".into(), "X".into());
936        env.insert("B".into(), "Y".into());
937        let expander = StreamingExpand::new(&[], &env);
938        let result = expander
939            .expand_string("{{ env:A }} and {{ env:B }}")
940            .unwrap();
941        assert_eq!(result, "X and Y");
942    }
943
944    #[test]
945    fn missing_var() {
946        let env = HashMap::new();
947        let expander = StreamingExpand::new(&[], &env);
948        let result = expander.expand_string("{{ env:MISSING }}");
949        assert!(result.is_err());
950        assert!(
951            result
952                .unwrap_err()
953                .to_string()
954                .contains("undefined environment variable"),
955            "error should mention undefined environment variable"
956        );
957    }
958
959    #[test]
960    fn no_placeholders() {
961        let env = HashMap::new();
962        let expander = StreamingExpand::new(&[], &env);
963        let result = expander.expand_string("plain text").unwrap();
964        assert_eq!(result, "plain text");
965    }
966
967    #[test]
968    fn empty_input() {
969        let env = HashMap::new();
970        let expander = StreamingExpand::new(&[], &env);
971        let result = expander.expand_string("").unwrap();
972        assert_eq!(result, "");
973    }
974
975    #[test]
976    fn override_precedence() {
977        let mut env = HashMap::new();
978        env.insert("KEY".into(), "envval".into());
979        let overrides = vec![("KEY".into(), "override".into())];
980        let expander = StreamingExpand::new(&overrides, &env);
981        let result = expander.expand_string("{{ env:KEY }}").unwrap();
982        assert_eq!(result, "override");
983    }
984
985    #[test]
986    fn override_with_namespace() {
987        let mut env = HashMap::new();
988        env.insert("CRATE".into(), "envval".into());
989        let overrides = vec![("CRATE".into(), "override".into())];
990        let expander = StreamingExpand::new(&overrides, &env);
991        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
992        assert_eq!(result, "override");
993    }
994
995    #[test]
996    fn override_raw_key_match() {
997        let mut env = HashMap::new();
998        env.insert("CRATE".into(), "envval".into());
999        let overrides = vec![("env:CRATE".into(), "override".into())];
1000        let expander = StreamingExpand::new(&overrides, &env);
1001        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
1002        assert_eq!(result, "override");
1003    }
1004
1005    #[test]
1006    fn unclosed_placeholder() {
1007        let env = HashMap::new();
1008        let expander = StreamingExpand::new(&[], &env);
1009        let result = expander.expand_string("{{ env:KEY").unwrap();
1010        assert_eq!(result, "{{ env:KEY");
1011    }
1012
1013    #[test]
1014    fn unclosed_with_prefix() {
1015        let env = HashMap::new();
1016        let expander = StreamingExpand::new(&[], &env);
1017        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
1018        assert_eq!(result, "Hello {{ env:KEY");
1019    }
1020
1021    #[test]
1022    fn buffer_limit_exceeded() {
1023        let env = HashMap::new();
1024        let expander = StreamingExpand::new(&[], &env);
1025        // Create input with `{{` followed by >1024 bytes without `}}`
1026        let mut input = b"{{ ".to_vec();
1027        input.extend(std::iter::repeat_n(b'x', 2000));
1028        let result = expander
1029            .expand_string(&String::from_utf8_lossy(&input))
1030            .unwrap();
1031        // Should flush as literal with `{{` prefix
1032        assert!(result.starts_with("{{ "));
1033        assert!(result.len() > 1024);
1034    }
1035
1036    #[test]
1037    fn escaped_opener_emits_literal() {
1038        let mut env = HashMap::new();
1039        env.insert("PROJECT".into(), "OxDock".into());
1040        let expander = StreamingExpand::new(&[], &env);
1041        let result = expander
1042            .expand_string("Built with \\{{ env:PROJECT }}")
1043            .unwrap();
1044        assert_eq!(result, "Built with {{ env:PROJECT }}");
1045    }
1046
1047    /// Stub resolver echoing `upper` over one string arg, for call tests.
1048    fn shout_resolver() -> PlaceholderCall {
1049        Arc::new(|module, func, args| {
1050            if module == "T" && func == "SHOUT" && args.len() == 1 {
1051                let s = args[0]
1052                    .as_str()
1053                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
1054                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
1055            }
1056            bail!("unknown placeholder function '{module}::{func}'")
1057        })
1058    }
1059
1060    #[test]
1061    fn placeholder_call_with_var_arg() {
1062        let env = HashMap::new();
1063        let mut vars = HashMap::new();
1064        vars.insert(
1065            "who".to_string(),
1066            oxdock_parser::Value::string("bob".to_string()),
1067        );
1068        let expander = StreamingExpand::new(&[], &env)
1069            .with_vars(&vars)
1070            .with_call_resolver(shout_resolver());
1071        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1072        assert_eq!(result, "hi BOB!");
1073    }
1074
1075    #[test]
1076    fn placeholder_call_with_literal_args() {
1077        let env = HashMap::new();
1078        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1079        let result = expander
1080            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1081            .unwrap();
1082        assert_eq!(result, "BOB ANN");
1083    }
1084
1085    #[test]
1086    fn placeholder_call_output_stays_literal() {
1087        // Call output containing `{{ }}` is terminal text, never re-expanded.
1088        let env = HashMap::new();
1089        let mut vars = HashMap::new();
1090        vars.insert(
1091            "any".to_string(),
1092            oxdock_parser::Value::string("v".to_string()),
1093        );
1094        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1095            Ok(oxdock_parser::Value::string(
1096                "x {{ env:NOPE }} y".to_string(),
1097            ))
1098        });
1099        let expander = StreamingExpand::new(&[], &env)
1100            .with_vars(&vars)
1101            .with_call_resolver(resolver);
1102        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1103        assert_eq!(result, "x {{ env:NOPE }} y");
1104    }
1105
1106    #[test]
1107    fn placeholder_call_unknown_function_fails() {
1108        let env = HashMap::new();
1109        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1110        let result = expander.expand_string("{{ T::NOPE($x) }}");
1111        assert!(result.is_err());
1112    }
1113
1114    #[test]
1115    fn placeholder_call_without_resolver_fails() {
1116        let env = HashMap::new();
1117        let expander = StreamingExpand::new(&[], &env);
1118        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1119        assert!(result.is_err());
1120    }
1121
1122    #[test]
1123    fn escaped_opener_across_chunks() {
1124        let mut env = HashMap::new();
1125        env.insert("PROJECT".into(), "OxDock".into());
1126        let mut expander = StreamingExpand::new(&[], &env);
1127        let mut out = Vec::new();
1128
1129        // Split `\` / `{{ env:PROJECT }}` across chunks
1130        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1131        expander
1132            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1133            .unwrap();
1134        expander.flush(&mut out).unwrap();
1135
1136        assert_eq!(
1137            String::from_utf8_lossy(&out),
1138            "Built with {{ env:PROJECT }}"
1139        );
1140    }
1141
1142    #[test]
1143    fn double_backslash_then_placeholder_expands() {
1144        let mut env = HashMap::new();
1145        env.insert("PROJECT".into(), "OxDock".into());
1146        let expander = StreamingExpand::new(&[], &env);
1147        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1148        assert_eq!(result, "\\OxDock");
1149    }
1150
1151    #[test]
1152    fn trailing_backslash_flushes_literal() {
1153        let env = HashMap::new();
1154        let expander = StreamingExpand::new(&[], &env);
1155        let result = expander.expand_string("end\\").unwrap();
1156        assert_eq!(result, "end\\");
1157    }
1158
1159    #[test]
1160    fn backslash_before_other_text_is_literal() {
1161        let env = HashMap::new();
1162        let expander = StreamingExpand::new(&[], &env);
1163        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1164        assert_eq!(result, "a\\b \\{ once }");
1165    }
1166
1167    #[test]
1168    fn escaped_pair_split_across_chunks() {
1169        let mut env = HashMap::new();
1170        env.insert("PROJECT".into(), "OxDock".into());
1171        let mut expander = StreamingExpand::new(&[], &env);
1172        let mut out = Vec::new();
1173
1174        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1175        // completes to one backslash, then the placeholder expands
1176        expander.process_bytes(b"\\", &mut out).unwrap();
1177        expander
1178            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1179            .unwrap();
1180        expander.flush(&mut out).unwrap();
1181
1182        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1183    }
1184
1185    #[test]
1186    fn partial_across_chunks() {
1187        let mut env = HashMap::new();
1188        env.insert("NAME".into(), "World".into());
1189        let mut expander = StreamingExpand::new(&[], &env);
1190        let mut out = Vec::new();
1191
1192        // Split `{{ env:NA` / `ME }}` across chunks
1193        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1194        expander.process_bytes(b"ME }}", &mut out).unwrap();
1195        expander.flush(&mut out).unwrap();
1196
1197        assert_eq!(String::from_utf8_lossy(&out), "World");
1198    }
1199
1200    #[test]
1201    fn trailing_brace_across_chunks() {
1202        let mut env = HashMap::new();
1203        env.insert("NAME".into(), "World".into());
1204        let mut expander = StreamingExpand::new(&[], &env);
1205        let mut out = Vec::new();
1206
1207        // Split `...{` / `{env:NAME}}` across chunks
1208        expander.process_bytes(b"...", &mut out).unwrap();
1209        expander.process_bytes(b"{", &mut out).unwrap();
1210        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1211        expander.flush(&mut out).unwrap();
1212
1213        assert_eq!(String::from_utf8_lossy(&out), "...World");
1214    }
1215
1216    #[test]
1217    fn trailing_brace_at_eof() {
1218        let env = HashMap::new();
1219        let mut expander = StreamingExpand::new(&[], &env);
1220        let mut out = Vec::new();
1221
1222        expander.process_bytes(b"hello{", &mut out).unwrap();
1223        expander.flush(&mut out).unwrap();
1224
1225        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1226    }
1227
1228    #[test]
1229    fn immediate_flush_guarantee() {
1230        let env = HashMap::new();
1231        let mut expander = StreamingExpand::new(&[], &env);
1232        let mut out = Vec::new();
1233
1234        // 1MB of plain text with no placeholders
1235        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1236        expander.process_bytes(&input, &mut out).unwrap();
1237        expander.flush(&mut out).unwrap();
1238
1239        assert_eq!(out.len(), 1024 * 1024);
1240    }
1241
1242    #[test]
1243    fn nested_braces() {
1244        let mut env = HashMap::new();
1245        env.insert("KEY{1}".into(), "val".into());
1246        let expander = StreamingExpand::new(&[], &env);
1247        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1248        assert_eq!(result, "val");
1249    }
1250
1251    #[test]
1252    fn split_close_delimiter_across_chunks() {
1253        let mut env = HashMap::new();
1254        env.insert("NAME".into(), "World".into());
1255        let mut expander = StreamingExpand::new(&[], &env);
1256        let mut out = Vec::new();
1257
1258        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1259        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1260        expander.process_bytes(b"}}", &mut out).unwrap();
1261        expander.flush(&mut out).unwrap();
1262
1263        assert_eq!(String::from_utf8_lossy(&out), "World");
1264    }
1265
1266    #[test]
1267    fn split_close_delimiter_with_trailing_content() {
1268        let mut env = HashMap::new();
1269        env.insert("NAME".into(), "World".into());
1270        let mut expander = StreamingExpand::new(&[], &env);
1271        let mut out = Vec::new();
1272
1273        // Split `}}` across chunks with content after
1274        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1275        expander.process_bytes(b"}} rest", &mut out).unwrap();
1276        expander.flush(&mut out).unwrap();
1277
1278        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1279    }
1280
1281    #[test]
1282    fn empty_input_preserves_pending_state() {
1283        let mut env = HashMap::new();
1284        env.insert("NAME".into(), "World".into());
1285        let mut expander = StreamingExpand::new(&[], &env);
1286        let mut out = Vec::new();
1287
1288        // End chunk with closing byte, then empty input, then confirm
1289        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1290        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1291        expander.process_bytes(b"}}", &mut out).unwrap();
1292        expander.flush(&mut out).unwrap();
1293
1294        assert_eq!(String::from_utf8_lossy(&out), "World");
1295    }
1296
1297    #[test]
1298    fn missing_env_var_errors() {
1299        let env = HashMap::new();
1300        let expander = StreamingExpand::new(&[], &env);
1301        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1302        assert!(result.is_err());
1303        let msg = result.unwrap_err().to_string();
1304        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1305        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1306    }
1307
1308    #[test]
1309    fn missing_script_var_errors() {
1310        let env = HashMap::new();
1311        let expander = StreamingExpand::new(&[], &env);
1312        let result = expander.expand_string("{{ $undefined_var }}");
1313        assert!(result.is_err());
1314        let msg = result.unwrap_err().to_string();
1315        assert!(msg.contains("undefined script variable"), "got: {msg}");
1316        assert!(msg.contains("$undefined_var"), "got: {msg}");
1317    }
1318
1319    #[test]
1320    fn missing_key_in_map_errors() {
1321        let mut vars = HashMap::new();
1322        vars.insert(
1323            "cfg".into(),
1324            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1325                "server".into(),
1326                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1327                    "port".into(),
1328                    oxdock_parser::Value::int(8080),
1329                )])),
1330            )])),
1331        );
1332        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1333        let result = expander.expand_string("{{ $cfg.missing_key }}");
1334        assert!(result.is_err());
1335        let msg = result.unwrap_err().to_string();
1336        assert!(
1337            msg.contains("property 'missing_key' not found"),
1338            "got: {msg}"
1339        );
1340    }
1341
1342    #[test]
1343    fn out_of_bounds_array_index_errors() {
1344        let mut vars = HashMap::new();
1345        vars.insert(
1346            "arr".into(),
1347            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1348        );
1349        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1350        let result = expander.expand_string("{{ $arr.5 }}");
1351        assert!(result.is_err());
1352        let msg = result.unwrap_err().to_string();
1353        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1354    }
1355
1356    #[test]
1357    fn type_mismatch_navigation_errors() {
1358        let mut vars = HashMap::new();
1359        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1360        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1361        let result = expander.expand_string("{{ $name.sub_field }}");
1362        assert!(result.is_err());
1363        let msg = result.unwrap_err().to_string();
1364        assert!(
1365            msg.contains("cannot access property 'sub_field' on primitive"),
1366            "got: {msg}"
1367        );
1368    }
1369
1370    #[test]
1371    fn unprefixed_identifier_errors() {
1372        let env = HashMap::new();
1373        let expander = StreamingExpand::new(&[], &env);
1374        let result = expander.expand_string("{{ bare_word }}");
1375        assert!(result.is_err());
1376        let msg = result.unwrap_err().to_string();
1377        assert!(msg.contains("missing required step override"), "got: {msg}");
1378    }
1379
1380    // ── Strict namespace isolation tests ─────────────────────────────────────
1381
1382    #[test]
1383    fn script_var_does_not_fall_back_to_env() {
1384        let mut env = HashMap::new();
1385        env.insert("WHO".into(), "from-env".into());
1386        let expander = StreamingExpand::new(&[], &env);
1387        // $WHO queries vars, NOT env : should error even though env has WHO
1388        let result = expander.expand_string("{{ $WHO }}");
1389        assert!(result.is_err());
1390        let msg = result.unwrap_err().to_string();
1391        assert!(msg.contains("undefined script variable"), "got: {msg}");
1392        assert!(
1393            msg.contains("did you mean 'env:WHO'"),
1394            "hint should suggest env: prefix, got: {msg}"
1395        );
1396    }
1397
1398    #[test]
1399    fn env_var_does_not_fall_back_to_vars() {
1400        let mut vars = HashMap::new();
1401        vars.insert(
1402            "HOST".into(),
1403            oxdock_parser::Value::string("from-var".into()),
1404        );
1405        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1406        // env:HOST queries env, NOT vars : should error even though vars has HOST
1407        let result = expander.expand_string("{{ env:HOST }}");
1408        assert!(result.is_err());
1409        let msg = result.unwrap_err().to_string();
1410        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1411        assert!(
1412            msg.contains("did you mean '$HOST'"),
1413            "hint should suggest $ prefix, got: {msg}"
1414        );
1415    }
1416
1417    #[test]
1418    fn step_override_does_not_fall_back_to_vars() {
1419        let mut vars = HashMap::new();
1420        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1421        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1422        // PORT (bare) queries overrides, NOT vars : should error
1423        let result = expander.expand_string("{{ PORT }}");
1424        assert!(result.is_err());
1425        let msg = result.unwrap_err().to_string();
1426        assert!(msg.contains("missing required step override"), "got: {msg}");
1427        assert!(
1428            msg.contains("did you mean '$PORT'"),
1429            "hint should suggest $ prefix, got: {msg}"
1430        );
1431    }
1432
1433    #[test]
1434    fn env_prefix_isolated_from_script_vars() {
1435        let mut vars = HashMap::new();
1436        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1437        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1438        // env:MODE looks in env, not vars : should error
1439        let result = expander.expand_string("{{ env:MODE }}");
1440        assert!(result.is_err());
1441        let msg = result.unwrap_err().to_string();
1442        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1443        assert!(
1444            msg.contains("did you mean '$MODE'"),
1445            "hint should suggest $ prefix, got: {msg}"
1446        );
1447    }
1448
1449    #[test]
1450    fn dollar_prefix_isolated_from_env() {
1451        let mut env = HashMap::new();
1452        env.insert("PORT".into(), "3000".into());
1453        let expander = StreamingExpand::new(&[], &env);
1454        // $PORT looks in vars, not env : should error
1455        let result = expander.expand_string("{{ $PORT }}");
1456        assert!(result.is_err());
1457        let msg = result.unwrap_err().to_string();
1458        assert!(msg.contains("undefined script variable"), "got: {msg}");
1459        assert!(
1460            msg.contains("did you mean 'env:PORT'"),
1461            "hint should suggest env: prefix, got: {msg}"
1462        );
1463    }
1464
1465    #[test]
1466    fn empty_placeholder_errors() {
1467        let expander = StreamingExpand::new(&[], &HashMap::new());
1468        let result = expander.expand_string("{{ }}");
1469        assert!(result.is_err());
1470        let msg = result.unwrap_err().to_string();
1471        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1472    }
1473
1474    #[test]
1475    fn malformed_symbol_placeholder_errors() {
1476        let expander = StreamingExpand::new(&[], &HashMap::new());
1477        let result = expander.expand_string("{{ @invalid! }}");
1478        assert!(result.is_err());
1479        let msg = result.unwrap_err().to_string();
1480        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1481    }
1482
1483    /// Feed input in fixed-size chunks, then flush: exercises every
1484    /// chunk-boundary alignment for the given split size.
1485    fn render_split(
1486        input: &[u8],
1487        size: usize,
1488        env: &HashMap<String, String>,
1489    ) -> Result<String, anyhow::Error> {
1490        let mut expander = StreamingExpand::new(&[], env);
1491        let mut out = Vec::new();
1492        for chunk in input.chunks(size) {
1493            expander.process_bytes(chunk, &mut out)?;
1494        }
1495        expander.flush(&mut out)?;
1496        Ok(String::from_utf8_lossy(&out).into_owned())
1497    }
1498
1499    #[test]
1500    fn escaped_opener_one_byte_chunks_stays_literal() {
1501        let mut env = HashMap::new();
1502        env.insert("NAME".into(), "World".into());
1503        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1504        // resolve to a literal opener, never an expansion.
1505        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1506        assert_eq!(out, "{{ env:NAME }}");
1507    }
1508
1509    #[test]
1510    fn escaped_opener_two_byte_chunks_stays_literal() {
1511        let mut env = HashMap::new();
1512        env.insert("NAME".into(), "World".into());
1513        // Two-byte splits land `\{` and lone `{` at chunk ends.
1514        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1515        assert_eq!(out, "a{{ env:NAME }}b");
1516    }
1517
1518    #[test]
1519    fn escaped_opener_split_variants_stay_literal() {
1520        let mut env = HashMap::new();
1521        env.insert("NAME".into(), "World".into());
1522        for chunks in [
1523            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1524            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1525            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1526        ] {
1527            let mut expander = StreamingExpand::new(&[], &env);
1528            let mut out = Vec::new();
1529            for chunk in chunks {
1530                expander.process_bytes(chunk, &mut out).unwrap();
1531            }
1532            expander.flush(&mut out).unwrap();
1533            assert_eq!(
1534                String::from_utf8_lossy(&out),
1535                "{{ env:NAME }}",
1536                "chunks must not corrupt the escape"
1537            );
1538        }
1539    }
1540
1541    #[test]
1542    fn plain_opener_split_chunks_still_expands() {
1543        let mut env = HashMap::new();
1544        env.insert("NAME".into(), "World".into());
1545        // The fix must not swallow genuine openers fragmented the
1546        // same way: `{` | `{` opens, then the key resolves.
1547        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1548        assert_eq!(out, "World");
1549    }
1550
1551    #[test]
1552    fn double_backslash_split_chunks_still_expands() {
1553        let mut env = HashMap::new();
1554        env.insert("NAME".into(), "World".into());
1555        // `\\` completes to one backslash; the opener after it expands.
1556        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1557        assert_eq!(out, "\\World");
1558    }
1559
1560    #[test]
1561    fn trailing_escape_brace_flushes_literal() {
1562        let env = HashMap::new();
1563        let expander = StreamingExpand::new(&[], &env);
1564        let result = expander.expand_string("end\\{").unwrap();
1565        assert_eq!(result, "end\\{");
1566    }
1567
1568    // ── Single-pass substitution tests ────────────────────────────────────
1569    // Substituted values are emitted verbatim and never re-scanned for
1570    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1571    // itself contains a placeholder stays literal instead of expanding.
1572
1573    #[test]
1574    fn substituted_override_value_is_not_rescanned() {
1575        let mut env = HashMap::new();
1576        env.insert("OTHER".into(), "world".into());
1577        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1578        let expander = StreamingExpand::new(&overrides, &env);
1579        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1580        assert_eq!(result, "Hello {{ env:OTHER }}");
1581    }
1582
1583    #[test]
1584    fn substituted_env_value_is_not_rescanned() {
1585        let mut env = HashMap::new();
1586        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1587        env.insert("OTHER".into(), "world".into());
1588        let expander = StreamingExpand::new(&[], &env);
1589        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1590        assert_eq!(result, "Hello {{ env:OTHER }}");
1591    }
1592
1593    #[test]
1594    fn substituted_script_var_value_is_not_rescanned() {
1595        let mut vars = HashMap::new();
1596        vars.insert(
1597            "inner".into(),
1598            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1599        );
1600        let mut env = HashMap::new();
1601        env.insert("OTHER".into(), "world".into());
1602        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1603        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1604        assert_eq!(result, "Hello {{ env:OTHER }}");
1605    }
1606
1607    /// Echo resolver returning the debug shape of each argument, so
1608    /// literal parsing asserts on values instead of formatting.
1609    fn shape_resolver() -> PlaceholderCall {
1610        Arc::new(|module, func, args| {
1611            if module == "T" && func == "SHAPE" {
1612                let shape = args
1613                    .iter()
1614                    .map(|arg| arg.type_name().to_string())
1615                    .collect::<Vec<_>>()
1616                    .join(",");
1617                return Ok(oxdock_parser::Value::string(shape));
1618            }
1619            bail!("unknown placeholder function '{module}::{func}'")
1620        })
1621    }
1622
1623    #[test]
1624    fn placeholder_call_with_empty_map_literal() {
1625        let expander =
1626            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1627        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1628        assert_eq!(result, "MAP");
1629    }
1630
1631    #[test]
1632    fn placeholder_call_with_map_and_list_literals() {
1633        let expander =
1634            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1635        let result = expander
1636            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1637            .unwrap();
1638        assert_eq!(result, "MAP,LIST");
1639    }
1640
1641    #[test]
1642    fn placeholder_call_map_commas_nest_inside_literals() {
1643        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1644            let map = args[0].as_map().expect("map");
1645            let format = map
1646                .get("format")
1647                .and_then(|v| v.as_str())
1648                .expect("format string");
1649            Ok(oxdock_parser::Value::string(format.to_string()))
1650        });
1651        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1652        let result = expander
1653            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1654            .unwrap();
1655        assert_eq!(result, "a,b");
1656    }
1657
1658    #[test]
1659    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1660        let mut vars = HashMap::new();
1661        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1662        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1663            let map = args[0].as_map().expect("map");
1664            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1665            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1666            Ok(oxdock_parser::Value::string(format!(
1667                "{depth}:{}",
1668                tags.len()
1669            )))
1670        });
1671        let expander = StreamingExpand::new(&[], &HashMap::new())
1672            .with_vars(&vars)
1673            .with_call_resolver(resolver);
1674        let result = expander
1675            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1676            .unwrap();
1677        assert_eq!(result, "2:2");
1678    }
1679
1680    #[test]
1681    fn placeholder_call_rejects_malformed_literals() {
1682        for bad in [
1683            "{{ T::SHAPE({a}) }}",
1684            "{{ T::SHAPE({a: 1, a: 2}) }}",
1685            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1686            "{{ T::SHAPE([1) }}",
1687            "{{ T::SHAPE({a: 1) }}",
1688        ] {
1689            let expander =
1690                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1691            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1692        }
1693    }
1694}