Skip to main content

kumosql_sql/
js.rs

1//! Read plain data out of Dataform JavaScript without running it.
2//!
3//! Mirrors `kumosql.js_literals`: strings, arrays and objects written as literals, the exports of a
4//! module, `require` bindings and loop substitution. Anything computed is reported as computed
5//! ([`JsValue::Expression`] in lenient parsing, `None` in strict parsing), never guessed.
6
7use std::sync::OnceLock;
8
9use indexmap::IndexMap;
10use regex::Regex;
11use serde::{Deserialize, Serialize};
12
13/// A JavaScript value read from source text.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub enum JsValue {
16    String(String),
17    /// A number as written.
18    Number(String),
19    Bool(bool),
20    Null,
21    Undefined,
22    Array(Vec<JsValue>),
23    Object(IndexMap<String, JsValue>),
24    /// Anything that is only known by running the code (`a + b`, `vars.x`, `` `${x}` ``), as written.
25    Expression(String),
26}
27
28impl JsValue {
29    pub fn as_str(&self) -> Option<&str> {
30        match self {
31            JsValue::String(s) => Some(s),
32            _ => None,
33        }
34    }
35
36    pub fn as_bool(&self) -> Option<bool> {
37        match self {
38            JsValue::Bool(b) => Some(*b),
39            _ => None,
40        }
41    }
42
43    pub fn as_array(&self) -> Option<&[JsValue]> {
44        match self {
45            JsValue::Array(items) => Some(items),
46            _ => None,
47        }
48    }
49
50    pub fn as_object(&self) -> Option<&IndexMap<String, JsValue>> {
51        match self {
52            JsValue::Object(map) => Some(map),
53            _ => None,
54        }
55    }
56
57    /// Whether the value, or anything inside it, is computed.
58    pub fn is_computed(&self) -> bool {
59        match self {
60            JsValue::Expression(_) => true,
61            JsValue::Array(items) => items.iter().any(JsValue::is_computed),
62            JsValue::Object(map) => map.values().any(JsValue::is_computed),
63            _ => false,
64        }
65    }
66
67    /// A string, or every string of an array of strings; `None` for anything else.
68    pub fn string_list(&self) -> Option<Vec<String>> {
69        match self {
70            JsValue::String(s) => Some(vec![s.clone()]),
71            JsValue::Array(items) => items
72                .iter()
73                .map(|i| i.as_str().map(str::to_string))
74                .collect(),
75            _ => None,
76        }
77    }
78
79    /// The value as JSON (expressions become `{"$expression": text}`).
80    pub fn to_json(&self) -> serde_json::Value {
81        use serde_json::Value;
82        match self {
83            JsValue::String(s) => Value::String(s.clone()),
84            JsValue::Number(n) => n
85                .replace('_', "")
86                .parse::<serde_json::Number>()
87                .map(Value::Number)
88                .unwrap_or_else(|_| Value::String(n.clone())),
89            JsValue::Bool(b) => Value::Bool(*b),
90            JsValue::Null | JsValue::Undefined => Value::Null,
91            JsValue::Array(items) => Value::Array(items.iter().map(JsValue::to_json).collect()),
92            JsValue::Object(map) => {
93                Value::Object(map.iter().map(|(k, v)| (k.clone(), v.to_json())).collect())
94            }
95            JsValue::Expression(text) => serde_json::json!({ "$expression": text }),
96        }
97    }
98}
99
100// ------------------------------------------------------------------------ scanning
101
102fn is_ident_start(c: char) -> bool {
103    c.is_alphabetic() || c == '_' || c == '$'
104}
105
106fn is_ident_char(c: char) -> bool {
107    c.is_alphanumeric() || c == '_' || c == '$'
108}
109
110/// The end (exclusive) of the JS string or template starting at `start` (a quote), or `None`
111/// when it never closes. A template's `${...}` parts are skipped as code.
112pub(crate) fn skip_js_string(text: &str, start: usize) -> Option<usize> {
113    let bytes = text.as_bytes();
114    let quote = bytes[start];
115    let mut i = start + 1;
116    while i < bytes.len() {
117        let c = bytes[i];
118        if c == b'\\' {
119            i += 2;
120            continue;
121        }
122        if quote == b'`' && c == b'$' && bytes.get(i + 1) == Some(&b'{') {
123            i = skip_js_braces(text, i + 1)?;
124            continue;
125        }
126        if c == quote {
127            return Some(i + 1);
128        }
129        if quote != b'`' && c == b'\n' {
130            return None;
131        }
132        i += 1;
133    }
134    None
135}
136
137/// The end (exclusive) of the balanced `{...}`, `[...]` or `(...)` opening at `start`.
138pub(crate) fn skip_js_braces(text: &str, start: usize) -> Option<usize> {
139    let bytes = text.as_bytes();
140    let mut depth = 0i32;
141    let mut i = start;
142    while i < bytes.len() {
143        match bytes[i] {
144            b'\'' | b'"' | b'`' => {
145                i = skip_js_string(text, i)?;
146                continue;
147            }
148            b'/' if bytes.get(i + 1) == Some(&b'/') => {
149                while i < bytes.len() && bytes[i] != b'\n' {
150                    i += 1;
151                }
152                continue;
153            }
154            b'/' if bytes.get(i + 1) == Some(&b'*') => {
155                i = text[i + 2..].find("*/").map(|e| i + 2 + e + 2)?;
156                continue;
157            }
158            b'{' | b'[' | b'(' => depth += 1,
159            b'}' | b']' | b')' => {
160                depth -= 1;
161                if depth == 0 {
162                    return Some(i + 1);
163                }
164            }
165            _ => {}
166        }
167        i += 1;
168    }
169    None
170}
171
172/// `text` without `//` and `/* */` comments (string contents are left alone).
173pub fn strip_comments(text: &str) -> String {
174    let bytes = text.as_bytes();
175    let mut out = String::with_capacity(text.len());
176    let mut i = 0;
177    while i < bytes.len() {
178        let c = bytes[i];
179        if c == b'\'' || c == b'"' || c == b'`' {
180            let end = simple_string_end(text, i).unwrap_or(i + 1);
181            out.push_str(&text[i..end]);
182            i = end;
183        } else if text[i..].starts_with("//") {
184            while i < bytes.len() && bytes[i] != b'\n' {
185                i += 1;
186            }
187            out.push(' ');
188        } else if text[i..].starts_with("/*") {
189            i = text[i + 2..]
190                .find("*/")
191                .map_or(bytes.len(), |e| i + 2 + e + 2);
192            out.push(' ');
193        } else {
194            let ch = text[i..].chars().next().unwrap_or(' ');
195            out.push(ch);
196            i += ch.len_utf8();
197        }
198    }
199    out
200}
201
202/// End of a quoted string with no template interpolation (as `js_literals._STRING_RE` reads one).
203fn simple_string_end(text: &str, start: usize) -> Option<usize> {
204    let bytes = text.as_bytes();
205    let quote = bytes[start];
206    let mut i = start + 1;
207    while i < bytes.len() {
208        let c = bytes[i];
209        if c == b'\\' {
210            i += 2;
211            continue;
212        }
213        if quote == b'`' && c == b'$' {
214            return None;
215        }
216        if c == quote {
217            return Some(i + 1);
218        }
219        i += 1;
220    }
221    None
222}
223
224fn unescape_js(body: &str) -> String {
225    let mut out = String::with_capacity(body.len());
226    let mut chars = body.chars().peekable();
227    while let Some(c) = chars.next() {
228        if c != '\\' {
229            out.push(c);
230            continue;
231        }
232        match chars.next() {
233            Some('n') => out.push('\n'),
234            Some('t') => out.push('\t'),
235            Some('r') => out.push('\r'),
236            Some('b') => out.push('\u{08}'),
237            Some('f') => out.push('\u{0C}'),
238            Some('v') => out.push('\u{0B}'),
239            Some('0') => out.push('\0'),
240            Some('u') => {
241                let hex: String = chars.by_ref().take(4).collect();
242                match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
243                    Some(ch) => out.push(ch),
244                    None => out.push_str(&hex),
245                }
246            }
247            Some('x') => {
248                let hex: String = chars.by_ref().take(2).collect();
249                match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
250                    Some(ch) => out.push(ch),
251                    None => out.push_str(&hex),
252                }
253            }
254            Some('\n') => {}
255            Some(other) => out.push(other),
256            None => {}
257        }
258    }
259    out
260}
261
262// ------------------------------------------------------------------------ parsing
263
264struct JsParser<'a> {
265    text: &'a str,
266    pos: usize,
267    lenient: bool,
268}
269
270impl<'a> JsParser<'a> {
271    fn peek(&self) -> Option<char> {
272        self.text[self.pos..].chars().next()
273    }
274
275    fn skip_trivia(&mut self) {
276        loop {
277            let rest = &self.text[self.pos..];
278            if let Some(c) = rest.chars().next().filter(|c| c.is_whitespace()) {
279                self.pos += c.len_utf8();
280            } else if self.lenient && rest.starts_with("//") {
281                self.pos += rest.find('\n').unwrap_or(rest.len());
282            } else if self.lenient && rest.starts_with("/*") {
283                self.pos += rest[2..].find("*/").map_or(rest.len(), |e| e + 4);
284            } else {
285                break;
286            }
287        }
288    }
289
290    /// The text of a computed expression starting here, up to the next `,`, `}`, `]` or `)`
291    /// outside brackets, strings and comments.
292    fn expression(&mut self) -> Option<JsValue> {
293        let start = self.pos;
294        let bytes = self.text.as_bytes();
295        let mut i = self.pos;
296        while i < bytes.len() {
297            match bytes[i] {
298                b'\'' | b'"' | b'`' => {
299                    i = skip_js_string(self.text, i)?;
300                    continue;
301                }
302                b'/' if bytes.get(i + 1) == Some(&b'/') => {
303                    while i < bytes.len() && bytes[i] != b'\n' {
304                        i += 1;
305                    }
306                    continue;
307                }
308                b'/' if bytes.get(i + 1) == Some(&b'*') => {
309                    i = self.text[i + 2..].find("*/").map(|e| i + 2 + e + 2)?;
310                    continue;
311                }
312                b'{' | b'[' | b'(' => {
313                    i = skip_js_braces(self.text, i)?;
314                    continue;
315                }
316                b',' | b'}' | b']' | b')' => break,
317                _ => i += 1,
318            }
319        }
320        let expr = strip_comments(&self.text[start..i]).trim().to_string();
321        if expr.is_empty() {
322            return None;
323        }
324        self.pos = i;
325        Some(JsValue::Expression(expr))
326    }
327
328    fn value(&mut self) -> Option<JsValue> {
329        self.skip_trivia();
330        let start = self.pos;
331        let literal = self.literal();
332        if !self.lenient {
333            return literal;
334        }
335        // a literal followed by more code (`"a" + x`, `[1].map(f)`) is an expression
336        let save = self.pos;
337        self.skip_trivia();
338        let complete = literal.is_some()
339            && matches!(
340                self.peek(),
341                None | Some(',') | Some('}') | Some(']') | Some(')')
342            );
343        if complete {
344            self.pos = save;
345            return literal;
346        }
347        self.pos = start;
348        self.expression()
349    }
350
351    fn literal(&mut self) -> Option<JsValue> {
352        let c = self.peek()?;
353        match c {
354            '\'' | '"' | '`' => {
355                let end = simple_string_end(self.text, self.pos)?;
356                let body = &self.text[self.pos + 1..end - 1];
357                self.pos = end;
358                Some(JsValue::String(unescape_js(body)))
359            }
360            '[' => {
361                self.pos += 1;
362                let mut items = Vec::new();
363                loop {
364                    self.skip_trivia();
365                    match self.peek()? {
366                        ']' => {
367                            self.pos += 1;
368                            return Some(JsValue::Array(items));
369                        }
370                        _ => {
371                            items.push(self.value()?);
372                            self.skip_trivia();
373                            match self.peek()? {
374                                ',' => self.pos += 1,
375                                ']' => {}
376                                _ => return None,
377                            }
378                        }
379                    }
380                }
381            }
382            '{' => {
383                self.pos += 1;
384                let mut map = IndexMap::new();
385                loop {
386                    self.skip_trivia();
387                    if self.peek()? == '}' {
388                        self.pos += 1;
389                        return Some(JsValue::Object(map));
390                    }
391                    let key = self.key()?;
392                    self.skip_trivia();
393                    let value = if self.peek() == Some(':') {
394                        self.pos += 1;
395                        self.value()?
396                    } else if self.lenient && matches!(self.peek(), Some(',') | Some('}')) {
397                        // shorthand `{ a }`: the value of a variable
398                        JsValue::Expression(key.clone())
399                    } else {
400                        return None;
401                    };
402                    map.insert(key, value);
403                    self.skip_trivia();
404                    match self.peek()? {
405                        ',' => self.pos += 1,
406                        '}' => {}
407                        _ => return None,
408                    }
409                }
410            }
411            _ => {
412                let rest = &self.text[self.pos..];
413                let number_re = number_re();
414                if let Some(m) = number_re.find(rest) {
415                    self.pos += m.end();
416                    return Some(JsValue::Number(m.as_str().to_string()));
417                }
418                for (word, value) in [
419                    ("true", JsValue::Bool(true)),
420                    ("false", JsValue::Bool(false)),
421                    ("null", JsValue::Null),
422                    ("undefined", JsValue::Undefined),
423                ] {
424                    if rest.starts_with(word) && !rest[word.len()..].starts_with(is_ident_char) {
425                        self.pos += word.len();
426                        return Some(value);
427                    }
428                }
429                None
430            }
431        }
432    }
433
434    fn key(&mut self) -> Option<String> {
435        let c = self.peek()?;
436        if c == '\'' || c == '"' {
437            let end = simple_string_end(self.text, self.pos)?;
438            let key = unescape_js(&self.text[self.pos + 1..end - 1]);
439            self.pos = end;
440            return Some(key);
441        }
442        if is_ident_start(c) || c.is_ascii_digit() {
443            let rest = &self.text[self.pos..];
444            let len = rest
445                .find(|ch: char| !is_ident_char(ch))
446                .unwrap_or(rest.len());
447            self.pos += len;
448            return Some(rest[..len].to_string());
449        }
450        None
451    }
452}
453
454fn number_re() -> &'static Regex {
455    static RE: OnceLock<Regex> = OnceLock::new();
456    RE.get_or_init(|| Regex::new(r"^-?\d[\d_.]*(?:[eE][+-]?\d+)?").expect("valid regex"))
457}
458
459/// Parse one literal value at byte `index` (strings, arrays, objects, numbers, booleans, null):
460/// `(value, end)`, or `None` when the value is computed or malformed.
461pub fn parse_literal(text: &str, index: usize) -> Option<(JsValue, usize)> {
462    let mut parser = JsParser {
463        text,
464        pos: index,
465        lenient: false,
466    };
467    let value = parser.value()?;
468    Some((value, parser.pos))
469}
470
471/// Like [`parse_literal`], but the literal must end its expression (`[...].map(f)` is not one).
472pub fn parse_complete(text: &str, index: usize) -> Option<(JsValue, usize)> {
473    let (value, end) = parse_literal(text, index)?;
474    let rest: String = text[end..].chars().take(40).collect();
475    let rest = rest.trim_start_matches([' ', '\t']);
476    match rest.chars().next() {
477        None => Some((value, end)),
478        Some(c) if ";\n\r,})".contains(c) => Some((value, end)),
479        _ => None,
480    }
481}
482
483/// Parse a value leniently: comments are skipped, trailing commas and unquoted keys allowed, and
484/// anything computed becomes [`JsValue::Expression`]. Returns the value and where it ends.
485pub fn parse_lenient(text: &str, index: usize) -> Option<(JsValue, usize)> {
486    let mut parser = JsParser {
487        text,
488        pos: index,
489        lenient: true,
490    };
491    let value = parser.value()?;
492    Some((value, parser.pos))
493}
494
495// ------------------------------------------------------------------------ modules
496
497fn declaration_re() -> &'static Regex {
498    static RE: OnceLock<Regex> = OnceLock::new();
499    RE.get_or_init(|| {
500        Regex::new(r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*").expect("valid regex")
501    })
502}
503
504/// What a module offers a `require`: `{"": whole export, "name": member}`, literals only.
505///
506/// Understands `module.exports = <literal>`, `module.exports = { a, b: <literal> }` with `a` a
507/// literal `const`, and `exports.name = <literal>`.
508pub fn module_exports(text: &str) -> IndexMap<String, JsValue> {
509    let text = strip_comments(text);
510    let mut constants: IndexMap<String, Option<JsValue>> = IndexMap::new();
511    for caps in declaration_re().captures_iter(&text) {
512        let name = caps[1].to_string();
513        let end = caps.get(0).map_or(0, |m| m.end());
514        if let Some((value, _)) = parse_complete(&text, end) {
515            let entry = if constants.contains_key(&name) {
516                None
517            } else {
518                Some(value)
519            };
520            constants.insert(name, entry);
521        }
522    }
523    let mut exports = IndexMap::new();
524    static WHOLE: OnceLock<Regex> = OnceLock::new();
525    let whole = WHOLE.get_or_init(|| Regex::new(r"\bmodule\.exports\s*=\s*").expect("valid regex"));
526    if let Some(m) = whole.find(&text) {
527        if let Some((value, _)) = parse_complete(&text, m.end()) {
528            if let JsValue::Object(map) = &value {
529                exports.insert(String::new(), value.clone());
530                for (k, v) in map {
531                    exports.insert(k.clone(), v.clone());
532                }
533            } else {
534                exports.insert(String::new(), value);
535            }
536        } else {
537            let after = &text[m.end()..];
538            let trimmed = after.trim_start();
539            if trimmed.starts_with('{') {
540                let start = m.end() + (after.len() - trimmed.len());
541                for (name, local) in shorthand_members(&text, start) {
542                    if let Some(Some(value)) = constants.get(&local) {
543                        exports.insert(name, value.clone());
544                    }
545                }
546            }
547        }
548    }
549    static MEMBER: OnceLock<Regex> = OnceLock::new();
550    let member = MEMBER
551        .get_or_init(|| Regex::new(r"\bexports\.([A-Za-z_$][\w$]*)\s*=\s*").expect("valid regex"));
552    static IDENT_END: OnceLock<Regex> = OnceLock::new();
553    let ident_end =
554        IDENT_END.get_or_init(|| Regex::new(r"^([A-Za-z_$][\w$]*)\s*[;\n]").expect("valid regex"));
555    for caps in member.captures_iter(&text) {
556        let name = caps[1].to_string();
557        let end = caps.get(0).map_or(0, |m| m.end());
558        if let Some((value, _)) = parse_complete(&text, end) {
559            exports.insert(name, value);
560        } else if let Some(ident) = ident_end.captures(&text[end..]) {
561            if let Some(Some(value)) = constants.get(&ident[1]) {
562                exports.insert(name, value.clone());
563            }
564        }
565    }
566    exports
567}
568
569/// `{ a, b: c }` after `module.exports =`: `[(exported name, local name)]`.
570fn shorthand_members(text: &str, start: usize) -> Vec<(String, String)> {
571    let bytes = text.as_bytes();
572    let mut depth = 0i32;
573    let mut i = start;
574    while i < bytes.len() {
575        if bytes[i] == b'{' {
576            depth += 1;
577        } else if bytes[i] == b'}' {
578            depth -= 1;
579            if depth == 0 {
580                break;
581            }
582        }
583        i += 1;
584    }
585    let body = &text[(start + 1).min(i)..i];
586    let mut members = Vec::new();
587    let ident =
588        |s: &str| !s.is_empty() && s.starts_with(is_ident_start) && s.chars().all(is_ident_char);
589    for part in body.split(',') {
590        let part = part.trim();
591        if ident(part) {
592            members.push((part.to_string(), part.to_string()));
593        } else if let Some((name, local)) = part.split_once(':') {
594            let (name, local) = (name.trim(), local.trim());
595            if ident(name) && ident(local) {
596                members.push((name.to_string(), local.to_string()));
597            }
598        }
599    }
600    members
601}
602
603/// The exports of `require(spec)` from the project-relative file `from_file`, if known.
604pub fn resolve_module<'m>(
605    spec: &str,
606    from_file: &str,
607    modules: &'m IndexMap<String, IndexMap<String, JsValue>>,
608) -> Option<&'m IndexMap<String, JsValue>> {
609    let base: Vec<&str> = {
610        let mut parts: Vec<&str> = from_file.split('/').collect();
611        parts.pop();
612        parts
613    };
614    let mut candidates: Vec<Vec<&str>> = Vec::new();
615    let spec_parts: Vec<&str> = spec.split('/').collect();
616    if spec.starts_with('.') {
617        candidates.push(
618            base.iter()
619                .copied()
620                .chain(spec_parts.iter().copied())
621                .collect(),
622        );
623    } else {
624        candidates.push(spec_parts.clone());
625        candidates.push(
626            base.iter()
627                .copied()
628                .chain(spec_parts.iter().copied())
629                .collect(),
630        );
631    }
632    for candidate in candidates {
633        let mut parts: Vec<&str> = Vec::new();
634        for part in candidate {
635            match part {
636                ".." => {
637                    parts.pop();
638                }
639                "." | "" => {}
640                other => parts.push(other),
641            }
642        }
643        let mut key = parts.join("/");
644        if let Some(stripped) = key.strip_suffix(".js") {
645            key = stripped.to_string();
646        }
647        for option in [key.clone(), format!("{key}/index")] {
648            if let Some(found) = modules.get(&option) {
649                return Some(found);
650            }
651        }
652    }
653    None
654}
655
656/// Names this file binds from `require`: `const x = require("m")` and `const { a, b } = require("m")`.
657/// A name bound more than once is left out.
658pub fn required_bindings(
659    text: &str,
660    from_file: &str,
661    modules: &IndexMap<String, IndexMap<String, JsValue>>,
662) -> IndexMap<String, JsValue> {
663    static RE: OnceLock<Regex> = OnceLock::new();
664    let re = RE.get_or_init(|| {
665        Regex::new(
666            r#"\b(?:const|let|var)\s+(?:(\w+)|\{([^}]*)\})\s*=\s*require\(\s*(?:'([^'"`]+)'|"([^'"`]+)"|`([^'"`]+)`)\s*\)(\.\w+)?"#,
667        )
668        .expect("valid regex")
669    });
670    let text = strip_comments(text);
671    let mut bound: IndexMap<String, JsValue> = IndexMap::new();
672    let mut seen: IndexMap<String, usize> = IndexMap::new();
673    for caps in re.captures_iter(&text) {
674        let spec = caps
675            .get(3)
676            .or(caps.get(4))
677            .or(caps.get(5))
678            .map_or("", |m| m.as_str());
679        let Some(exported) = resolve_module(spec, from_file, modules) else {
680            continue;
681        };
682        let member = caps.get(6).map(|m| m.as_str()[1..].to_string());
683        let mut names: Vec<(String, Option<JsValue>)> = Vec::new();
684        if let Some(name) = caps.get(1) {
685            let value = match &member {
686                Some(m) => exported.get(m).cloned(),
687                None => match exported.get("") {
688                    Some(whole) => Some(whole.clone()),
689                    None => Some(JsValue::Object(
690                        exported
691                            .iter()
692                            .filter(|(k, _)| !k.is_empty())
693                            .map(|(k, v)| (k.clone(), v.clone()))
694                            .collect(),
695                    )),
696                },
697            };
698            names.push((name.as_str().to_string(), value));
699        } else if let Some(list) = caps.get(2) {
700            for item in list.as_str().split(',') {
701                let pair: Vec<&str> = item.split(':').map(str::trim).collect();
702                if let Some(first) = pair.first().filter(|f| !f.is_empty()) {
703                    let local = pair.last().copied().unwrap_or(first);
704                    names.push((local.to_string(), exported.get(*first).cloned()));
705                }
706            }
707        }
708        for (name, value) in names {
709            *seen.entry(name.clone()).or_insert(0) += 1;
710            if let Some(value) = value {
711                bound.insert(name, value);
712            }
713        }
714    }
715    bound
716        .into_iter()
717        .filter(|(name, _)| seen.get(name) == Some(&1))
718        .collect()
719}
720
721/// Literal `const` values defined once in this file.
722pub fn local_constants(text: &str) -> IndexMap<String, JsValue> {
723    let text = strip_comments(text);
724    let mut found = IndexMap::new();
725    let mut counts: IndexMap<String, usize> = IndexMap::new();
726    for caps in declaration_re().captures_iter(&text) {
727        let name = caps[1].to_string();
728        *counts.entry(name.clone()).or_insert(0) += 1;
729        let end = caps.get(0).map_or(0, |m| m.end());
730        if let Some((value, _)) = parse_complete(&text, end) {
731            found.insert(name, value);
732        }
733    }
734    found
735        .into_iter()
736        .filter(|(name, _)| counts.get(name) == Some(&1))
737        .collect()
738}
739
740/// The items a loop ranges over when `expression` is a literal array, a name in `scope` or
741/// `name.member`; `None` when unknown.
742pub fn source_items(expression: &str, scope: &IndexMap<String, JsValue>) -> Option<Vec<JsValue>> {
743    let expression = expression.trim();
744    let value = match parse_literal(expression, 0) {
745        Some((value, end)) => {
746            if !expression[end..].trim().is_empty() {
747                return None;
748            }
749            value
750        }
751        None => {
752            let parts: Vec<&str> = expression.split('.').collect();
753            let ident = |s: &str| {
754                !s.is_empty() && s.starts_with(is_ident_start) && s.chars().all(is_ident_char)
755            };
756            if !parts.iter().all(|p| ident(p)) {
757                return None;
758            }
759            let mut value = scope.get(parts[0])?.clone();
760            for member in &parts[1..] {
761                value = value.as_object()?.get(*member)?.clone();
762            }
763            value
764        }
765    };
766    match value {
767        JsValue::Array(items) => Some(items),
768        _ => None,
769    }
770}
771
772fn js_quote(value: &JsValue) -> Option<String> {
773    let s = value.as_str()?;
774    Some(format!(
775        "\"{}\"",
776        s.replace('\\', "\\\\").replace('"', "\\\"")
777    ))
778}
779
780fn word_char(c: char) -> bool {
781    c.is_alphanumeric() || c == '_'
782}
783
784/// Occurrences of `variable` in `text` whose previous character satisfies `before_ok` and that
785/// are not followed by an identifier character.
786fn occurrences(text: &str, variable: &str, before_ok: impl Fn(Option<char>) -> bool) -> Vec<usize> {
787    let mut out = Vec::new();
788    let mut from = 0;
789    while let Some(found) = text[from..].find(variable) {
790        let start = from + found;
791        let end = start + variable.len();
792        let before = text[..start].chars().next_back();
793        let after = text[end..].chars().next();
794        if before_ok(before) && !after.is_some_and(|c| word_char(c) || c == '$') {
795            out.push(start);
796        }
797        from = start + variable.len().max(1);
798    }
799    out
800}
801
802fn followed_by_colon(text: &str, end: usize) -> bool {
803    text[end..].trim_start().starts_with(':')
804}
805
806/// `config` with the loop variable replaced by this item's literals; `None` when a member is
807/// missing or not a string, or the variable is still used afterwards.
808pub fn substitute(config: &str, variable: &str, item: &JsValue) -> Option<String> {
809    if variable.is_empty() {
810        return None;
811    }
812    let mut failed = false;
813    // `variable.member`, `variable['member']`, `variable["member"]`
814    let mut out = String::with_capacity(config.len());
815    let mut cursor = 0;
816    let boundary = |before: Option<char>| !before.is_some_and(word_char);
817    let mut from = 0;
818    while let Some(found) = config[from..].find(variable) {
819        let start = from + found;
820        let end = start + variable.len();
821        from = end;
822        if !boundary(config[..start].chars().next_back()) {
823            continue;
824        }
825        let rest = &config[end..];
826        let (key, used) = if let Some(member) = rest.strip_prefix('.') {
827            let len = member
828                .find(|c: char| !is_ident_char(c))
829                .unwrap_or(member.len());
830            if len == 0 || !member.starts_with(is_ident_start) {
831                continue;
832            }
833            (member[..len].to_string(), 1 + len)
834        } else if let Some(inner) = rest.strip_prefix('[') {
835            let trimmed = inner.trim_start();
836            let ws = inner.len() - trimmed.len();
837            let Some(q) = trimmed.chars().next().filter(|c| *c == '\'' || *c == '"') else {
838                continue;
839            };
840            let Some(close) = trimmed[1..].find(q) else {
841                continue;
842            };
843            let after = &trimmed[1 + close + 1..];
844            let after_trim = after.trim_start();
845            if !after_trim.starts_with(']') {
846                continue;
847            }
848            let key = trimmed[1..1 + close].to_string();
849            (
850                key,
851                1 + ws + 1 + close + 1 + (after.len() - after_trim.len()) + 1,
852            )
853        } else {
854            continue;
855        };
856        let replacement = match item {
857            JsValue::Object(map) => match map.get(&key) {
858                None => Some("undefined".to_string()),
859                Some(value) => js_quote(value),
860            },
861            _ => None,
862        };
863        out.push_str(&config[cursor..start]);
864        match replacement {
865            Some(text) => out.push_str(&text),
866            None => {
867                failed = true;
868                out.push_str(&config[start..end + used]);
869            }
870        }
871        cursor = end + used;
872        from = cursor;
873    }
874    out.push_str(&config[cursor..]);
875    if let Some(quoted) = js_quote(item) {
876        // shorthand `{ variable }` / `, variable,` becomes `variable: "item"`
877        let mut next = String::with_capacity(out.len());
878        let mut cursor = 0;
879        for start in occurrences(&out, variable, |_| true) {
880            let before = &out[..start];
881            let trimmed = before.trim_end();
882            let after = &out[start + variable.len()..];
883            let after_trim = after.trim_start();
884            if (trimmed.ends_with('{') || trimmed.ends_with(','))
885                && (after_trim.starts_with(',') || after_trim.starts_with('}'))
886            {
887                next.push_str(&out[cursor..start]);
888                next.push_str(&format!("{variable}: {quoted}"));
889                cursor = start + variable.len();
890            }
891        }
892        next.push_str(&out[cursor..]);
893        out = next;
894        // a bare use of the variable becomes the item
895        let not_member =
896            |before: Option<char>| !before.is_some_and(|c| word_char(c) || "$.\"'".contains(c));
897        let mut next = String::with_capacity(out.len());
898        let mut cursor = 0;
899        for start in occurrences(&out, variable, not_member) {
900            if followed_by_colon(&out, start + variable.len()) {
901                continue;
902            }
903            next.push_str(&out[cursor..start]);
904            next.push_str(&quoted);
905            cursor = start + variable.len();
906        }
907        next.push_str(&out[cursor..]);
908        out = next;
909    }
910    let not_member =
911        |before: Option<char>| !before.is_some_and(|c| word_char(c) || "$.\"'".contains(c));
912    let still_used = occurrences(&out, variable, not_member)
913        .into_iter()
914        .any(|start| !followed_by_colon(&out, start + variable.len()));
915    if failed || still_used {
916        return None;
917    }
918    Some(out)
919}
920
921#[cfg(test)]
922mod tests {
923    use super::*;
924
925    fn s(v: &str) -> JsValue {
926        JsValue::String(v.into())
927    }
928
929    #[test]
930    fn strips_comments_outside_strings() {
931        assert_eq!(strip_comments("a // it's {\nb"), "a  \nb");
932        assert_eq!(strip_comments("'//x' /* y */ z"), "'//x'   z");
933    }
934
935    #[test]
936    fn parses_literals() {
937        let (v, end) = parse_literal(" ['a', \"b\", `c`, 1, true]", 0).unwrap();
938        assert_eq!(
939            v,
940            JsValue::Array(vec![
941                s("a"),
942                s("b"),
943                s("c"),
944                JsValue::Number("1".into()),
945                JsValue::Bool(true)
946            ])
947        );
948        assert_eq!(end, 25);
949        let (v, _) = parse_literal("{a: 'x', 'b': [1,], c: {d: null},}", 0).unwrap();
950        assert_eq!(v.as_object().unwrap().len(), 3);
951        assert!(parse_literal("`${x}`", 0).is_none());
952        assert!(parse_literal("foo", 0).is_none());
953        assert!(parse_complete("[1].map(f)", 0).is_none());
954        assert!(parse_complete("[1];", 0).is_some());
955    }
956
957    #[test]
958    fn lenient_parsing_keeps_expressions() {
959        let (v, _) = parse_lenient(
960            "{ type: \"table\", schema: vars.s, name: 'a' + b, // c\n tags: [], x }",
961            0,
962        )
963        .unwrap();
964        let map = v.as_object().unwrap();
965        assert_eq!(map["type"], s("table"));
966        assert_eq!(map["schema"], JsValue::Expression("vars.s".into()));
967        assert_eq!(map["name"], JsValue::Expression("'a' + b".into()));
968        assert_eq!(map["tags"], JsValue::Array(vec![]));
969        assert_eq!(map["x"], JsValue::Expression("x".into()));
970    }
971
972    #[test]
973    fn reads_module_exports_and_requires() {
974        let exports = module_exports(
975            "const SOURCES = ['a', 'b'];\nmodule.exports = { SOURCES, other: 'x' };",
976        );
977        assert_eq!(exports["SOURCES"], JsValue::Array(vec![s("a"), s("b")]));
978        let exports2 =
979            module_exports("exports.tables = ['t1'];\nexports.n = NAME;\nconst NAME = 'n';");
980        assert_eq!(exports2["tables"], JsValue::Array(vec![s("t1")]));
981        let mut modules = IndexMap::new();
982        modules.insert("includes/sources".to_string(), exports);
983        let bound = required_bindings(
984            "const { SOURCES } = require('../includes/sources');\nconst all = require(\"includes/sources\");",
985            "definitions/x.js",
986            &modules,
987        );
988        assert_eq!(bound["SOURCES"], JsValue::Array(vec![s("a"), s("b")]));
989        assert!(bound["all"].as_object().is_some());
990        let consts = local_constants("const a = 'x'; const b = [1]; let a = 'y';");
991        assert!(!consts.contains_key("a"));
992        assert!(consts.contains_key("b"));
993    }
994
995    #[test]
996    fn loops_and_substitution() {
997        let mut scope = IndexMap::new();
998        scope.insert(
999            "m".to_string(),
1000            JsValue::Object(
1001                [("list".to_string(), JsValue::Array(vec![s("a")]))]
1002                    .into_iter()
1003                    .collect(),
1004            ),
1005        );
1006        assert_eq!(source_items("m.list", &scope), Some(vec![s("a")]));
1007        assert_eq!(
1008            source_items("['x', 'y']", &scope),
1009            Some(vec![s("x"), s("y")])
1010        );
1011        assert_eq!(source_items("f()", &scope), None);
1012
1013        let item = JsValue::Object(
1014            [
1015                ("name".to_string(), s("t1")),
1016                ("schema".to_string(), s("raw")),
1017            ]
1018            .into_iter()
1019            .collect(),
1020        );
1021        assert_eq!(
1022            substitute(
1023                "{ name: src.name, schema: src['schema'], x: src.missing }",
1024                "src",
1025                &item
1026            )
1027            .as_deref(),
1028            Some("{ name: \"t1\", schema: \"raw\", x: undefined }")
1029        );
1030        assert_eq!(
1031            substitute("{ name: t }", "t", &s("tbl")).as_deref(),
1032            Some("{ name: \"tbl\" }")
1033        );
1034        assert_eq!(
1035            substitute("{ t, schema: 's' }", "t", &s("tbl")).as_deref(),
1036            Some("{ t: \"tbl\", schema: 's' }")
1037        );
1038        assert_eq!(substitute("{ name: f(src) }", "src", &item), None);
1039    }
1040}