Skip to main content

parsec_js/
data.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Data from scripts: the state a page writes into a `<script>` as a
5//! literal, read as JSON without running anything.
6//!
7//! [`literal`] turns an expression made only of literals into a [`Json`]
8//! value, and refuses anything else with the span that stopped it.
9//! [`page_state`] finds the shapes pages put their state in
10//! (`window.__NUXT__ = …`, `var ytInitialData = …`,
11//! `JSON.parse("…")`, Next.js's `self.__next_f.push(…)`) and reads each
12//! one's value. [`json`] parses JSON text strictly, as `JSON.parse` does,
13//! for state that's in a script as JSON, like Next.js's `__NEXT_DATA__`.
14//!
15//! Nothing is evaluated. No property is read, no function called and no
16//! name looked up, with one exception: the arguments of a Nuxt function
17//! that only returns a literal are put in place of its parameters.
18//!
19//! ```
20//! use parsec_js::data::{Json, page_state};
21//!
22//! let src = r#"window.__STATE__ = {user: {name: "Ada", admin: !1}, cart: [1, , 3]};"#;
23//! let found = page_state(src).unwrap();
24//! assert_eq!(found[0].name, "window.__STATE__");
25//! let value = found[0].value.as_ref().unwrap();
26//! assert_eq!(
27//!     value.to_json_string(),
28//!     r#"{"user":{"name":"Ada","admin":false},"cart":[1,null,3]}"#
29//! );
30//! ```
31
32mod json;
33mod page;
34
35use std::collections::HashMap;
36use std::fmt;
37
38use parsec_base::Span;
39
40use crate::ast::{Ast, LiteralKind, Node, NodeId, PropertyKind, UnaryOp};
41use crate::text;
42
43pub use json::json;
44pub use page::{Found, next_flight, page_state, page_state_in, script_type};
45
46/// A JSON value. An object keeps its keys in the order they first
47/// appear, each once.
48#[derive(Clone, Debug, PartialEq)]
49pub enum Json {
50    Null,
51    Bool(bool),
52    /// Never NaN; it may be infinite, from `1e400`, which JSON writes
53    /// as `null` as `JSON.stringify` does.
54    Number(f64),
55    String(String),
56    Array(Vec<Json>),
57    Object(Vec<(String, Json)>),
58}
59
60impl Json {
61    /// The value as JSON text, the way `JSON.stringify` writes it: no
62    /// spaces, numbers as JavaScript prints them, `-0` as `0`, and an
63    /// infinite number as `null`.
64    pub fn to_json_string(&self) -> String {
65        let mut out = String::new();
66        self.write(&mut out);
67        out
68    }
69
70    fn write(&self, out: &mut String) {
71        match self {
72            Json::Null => out.push_str("null"),
73            Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
74            Json::Number(x) => text::write_js_number(out, *x),
75            Json::String(s) => text::write_json_str(out, s),
76            Json::Array(items) => {
77                out.push('[');
78                for (i, item) in items.iter().enumerate() {
79                    if i > 0 {
80                        out.push(',');
81                    }
82                    item.write(out);
83                }
84                out.push(']');
85            }
86            Json::Object(entries) => {
87                out.push('{');
88                for (i, (key, value)) in entries.iter().enumerate() {
89                    if i > 0 {
90                        out.push(',');
91                    }
92                    text::write_json_str(out, key);
93                    out.push(':');
94                    value.write(out);
95                }
96                out.push('}');
97            }
98        }
99    }
100
101    /// How much copying this value costs: a unit a value, plus its
102    /// strings' bytes.
103    fn weight(&self) -> usize {
104        match self {
105            Json::String(s) => 1 + s.len(),
106            Json::Array(items) => 1 + items.iter().map(Json::weight).sum::<usize>(),
107            Json::Object(entries) => {
108                1 + entries
109                    .iter()
110                    .map(|(k, v)| k.len() + v.weight())
111                    .sum::<usize>()
112            }
113            _ => 1,
114        }
115    }
116}
117
118/// Why a value isn't data, and where it stopped being.
119///
120/// `reason` is one of:
121///
122/// | Reason | What it was |
123/// |---|---|
124/// | `not-a-literal` | a name, a call, an operator, a function: anything that would have to run |
125/// | `substitution` | a template's `${…}`; the span is the expression in it |
126/// | `bigint` | a BigInt, which JSON has no way to write |
127/// | `regexp` | a regular expression literal |
128/// | `computed-key` | `{[k]: v}` |
129/// | `method` | a method, getter or setter |
130/// | `spread` | `...x` in an array, an object or arguments |
131/// | `proto` | `__proto__: v`, which sets the prototype rather than a key |
132/// | `not-a-number` | `-`, `+` or `!` on something other than a number (or, for `!`, a boolean) |
133/// | `undefined` | the whole value is `undefined`, which JSON can't hold |
134/// | `lone-surrogate` | a string with half a surrogate pair, which a Rust string can't hold |
135/// | `parameters` | a Nuxt function's parameter that isn't a plain name |
136/// | `function-body` | a Nuxt function that does more than return a value |
137/// | `too-large` | substituting arguments would copy far more than the source holds |
138/// | `json-syntax` | JSON text that `JSON.parse` would reject |
139/// | `too-deep` | JSON nested deeper than [`DEFAULT_MAX_DEPTH`](crate::DEFAULT_MAX_DEPTH) |
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct Refused {
142    pub span: Span,
143    pub reason: &'static str,
144}
145
146impl fmt::Display for Refused {
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        write!(
149            f,
150            "{} at {}..{}",
151            self.reason, self.span.start, self.span.end
152        )
153    }
154}
155
156impl std::error::Error for Refused {}
157
158fn refuse<T>(span: Span, reason: &'static str) -> Result<T, Refused> {
159    Err(Refused { span, reason })
160}
161
162/// The value of `expr`, an expression in `ast` parsed from `src`, if it's
163/// made only of literals:
164///
165/// - objects with plain keys (names, strings, numbers), arrays, strings,
166///   numbers, `true`, `false`, `null`, and templates without
167///   substitutions;
168/// - `-` and `+` on a number, `!` on a number or boolean (minifiers write
169///   `!0` for `true` and `!1` for `false`), and parentheses;
170/// - `undefined` and `void` on a literal, which, as in `JSON.stringify`,
171///   leave a key out of an object and are `null` in an array; a hole in
172///   an array is `null` too.
173///
174/// A key given twice keeps its first place and its last value, as in
175/// JavaScript. Keys stay in source order; JavaScript would put the ones
176/// that are array indices first. Anything else is refused: see
177/// [`Refused`].
178///
179/// ```
180/// use parsec_js::{Node, parse_script};
181/// use parsec_js::data::literal;
182///
183/// let src = "x = {a: [1, -2.5, `t`], b: void 0, 'c': !0}";
184/// let ast = parse_script(src).unwrap();
185/// let Node::Program { body, .. } = *ast.node(ast.root()) else { unreachable!() };
186/// let Node::Expression { expression, .. } = *ast.node(ast.get(body)[0]) else { unreachable!() };
187/// let Node::Assign { right, .. } = *ast.node(expression) else { unreachable!() };
188/// let value = literal(&ast, src, right).unwrap();
189/// assert_eq!(value.to_json_string(), r#"{"a":[1,-2.5,"t"],"c":true}"#);
190/// ```
191pub fn literal(ast: &Ast, src: &str, expr: NodeId) -> Result<Json, Refused> {
192    Reader::new(ast, src).whole(expr)
193}
194
195/// Reads literals out of a tree, with the parameters of a Nuxt function
196/// bound to their arguments' values.
197struct Reader<'a> {
198    ast: &'a Ast,
199    src: &'a str,
200    /// A parameter's value, `None` for `undefined`.
201    env: HashMap<String, Option<Json>>,
202    /// What substituting may still copy, by [`Json::weight`].
203    budget: usize,
204}
205
206impl<'a> Reader<'a> {
207    fn new(ast: &'a Ast, src: &'a str) -> Reader<'a> {
208        Reader {
209            ast,
210            src,
211            env: HashMap::new(),
212            budget: 0,
213        }
214    }
215
216    /// The value of `id`, which may not be `undefined`.
217    fn whole(&mut self, id: NodeId) -> Result<Json, Refused> {
218        match self.value(id)? {
219            Some(v) => Ok(v),
220            None => refuse(self.ast.span(id), "undefined"),
221        }
222    }
223
224    fn string(&self, span: Span, units: &[u16]) -> Result<String, Refused> {
225        String::from_utf16(units).or_else(|_| refuse(span, "lone-surrogate"))
226    }
227
228    /// The value of `id`, `None` for `undefined`.
229    fn value(&mut self, id: NodeId) -> Result<Option<Json>, Refused> {
230        let span = self.ast.span(id);
231        let v = match *self.ast.node(id) {
232            Node::Paren { expression } => return self.value(expression),
233            Node::Literal(kind) => match kind {
234                LiteralKind::String => {
235                    let body = Span::new(span.start + 1, span.end - 1).text(self.src);
236                    Json::String(self.string(span, &text::string_value(body))?)
237                }
238                LiteralKind::Number => Json::Number(text::number_value(span.text(self.src))),
239                LiteralKind::Boolean => Json::Bool(span.text(self.src) == "true"),
240                LiteralKind::Null => Json::Null,
241                LiteralKind::BigInt => return refuse(span, "bigint"),
242                LiteralKind::RegExp => return refuse(span, "regexp"),
243            },
244            Node::Template {
245                quasis,
246                expressions,
247            } => {
248                if let Some(&first) = self.ast.get(expressions).first() {
249                    return refuse(self.ast.span(first), "substitution");
250                }
251                let quasi = self.ast.get(quasis)[0];
252                let body = self.ast.span(quasi).text(self.src);
253                // An untagged template's escapes are all valid, or it
254                // wouldn't have parsed.
255                let units = text::template_cooked(body).unwrap_or_default();
256                Json::String(self.string(span, &units)?)
257            }
258            Node::Identifier => {
259                let name = text::ident_name(span.text(self.src));
260                if let Some(v) = self.env.get(name.as_ref()) {
261                    let weight = v.as_ref().map_or(1, Json::weight);
262                    if weight > self.budget {
263                        return refuse(span, "too-large");
264                    }
265                    self.budget -= weight;
266                    return Ok(v.clone());
267                }
268                if name == "undefined" {
269                    return Ok(None);
270                }
271                return refuse(span, "not-a-literal");
272            }
273            Node::Unary { operator, argument } => {
274                let arg = self.value(argument)?;
275                return match (operator, arg) {
276                    (UnaryOp::Void, _) => Ok(None),
277                    (UnaryOp::Minus, Some(Json::Number(x))) => Ok(Some(Json::Number(-x))),
278                    (UnaryOp::Plus, Some(Json::Number(x))) => Ok(Some(Json::Number(x))),
279                    (UnaryOp::Not, Some(Json::Number(x))) => {
280                        Ok(Some(Json::Bool(x == 0.0 || x.is_nan())))
281                    }
282                    (UnaryOp::Not, Some(Json::Bool(b))) => Ok(Some(Json::Bool(!b))),
283                    (UnaryOp::Minus | UnaryOp::Plus | UnaryOp::Not, _) => {
284                        refuse(self.ast.span(argument), "not-a-number")
285                    }
286                    _ => refuse(span, "not-a-literal"),
287                };
288            }
289            Node::Array { elements, .. } => {
290                let mut items = Vec::with_capacity(elements.len());
291                for &e in self.ast.get(elements) {
292                    match *self.ast.node(e) {
293                        Node::Elision => items.push(Json::Null),
294                        Node::Spread { .. } => return refuse(self.ast.span(e), "spread"),
295                        _ => items.push(self.value(e)?.unwrap_or(Json::Null)),
296                    }
297                }
298                Json::Array(items)
299            }
300            Node::Object { properties, .. } => {
301                let mut object = Object::default();
302                for &p in self.ast.get(properties) {
303                    let Node::Property {
304                        key,
305                        value,
306                        kind,
307                        method,
308                        shorthand,
309                        computed,
310                    } = *self.ast.node(p)
311                    else {
312                        return refuse(self.ast.span(p), "spread");
313                    };
314                    if method || kind != PropertyKind::Init {
315                        return refuse(self.ast.span(p), "method");
316                    }
317                    if computed {
318                        return refuse(self.ast.span(key), "computed-key");
319                    }
320                    let name = self.key(key)?;
321                    if name == "__proto__" && !shorthand {
322                        return refuse(self.ast.span(key), "proto");
323                    }
324                    let v = self.value(value)?;
325                    object.set(name, v);
326                }
327                object.finish()
328            }
329            _ => return refuse(span, "not-a-literal"),
330        };
331        Ok(Some(v))
332    }
333
334    /// A property key that isn't computed: a name, a string or a number.
335    fn key(&self, key: NodeId) -> Result<String, Refused> {
336        let span = self.ast.span(key);
337        let raw = span.text(self.src);
338        match *self.ast.node(key) {
339            Node::Literal(LiteralKind::String) => {
340                let body = Span::new(span.start + 1, span.end - 1).text(self.src);
341                self.string(span, &text::string_value(body))
342            }
343            Node::Literal(LiteralKind::Number) => {
344                let mut s = String::new();
345                text::write_js_number(&mut s, text::number_value(raw));
346                Ok(s)
347            }
348            Node::Literal(LiteralKind::BigInt) => refuse(span, "bigint"),
349            _ => Ok(text::ident_name(raw).into_owned()),
350        }
351    }
352}
353
354/// An object being built: a key given again keeps its place and takes
355/// the new value, and a key whose value is `undefined` is left out.
356#[derive(Default)]
357struct Object {
358    entries: Vec<(String, Option<Json>)>,
359    index: HashMap<String, usize>,
360}
361
362impl Object {
363    fn set(&mut self, key: String, value: Option<Json>) {
364        match self.index.get(&key) {
365            Some(&i) => self.entries[i].1 = value,
366            None => {
367                self.index.insert(key.clone(), self.entries.len());
368                self.entries.push((key, value));
369            }
370        }
371    }
372
373    fn finish(self) -> Json {
374        Json::Object(
375            self.entries
376                .into_iter()
377                .filter_map(|(k, v)| Some((k, v?)))
378                .collect(),
379        )
380    }
381}