Skip to main content

parsec_js/data/
page.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The shapes pages keep their state in, found at a script's top level.
5
6use std::collections::HashMap;
7
8use parsec_base::{Diagnostic, Span};
9
10use super::{Json, Reader, Refused, json, refuse};
11use crate::ast::{AssignOp, Ast, LiteralKind, Node, NodeId};
12use crate::{SourceType, parse_script, text};
13
14/// A piece of page state: where a script put it, and its value, or why
15/// it isn't data.
16#[derive(Clone, Debug, PartialEq)]
17pub struct Found {
18    /// What the script assigned: `window.__NUXT__`, `window.__NUXT__.config`,
19    /// `ytInitialData` for a top-level `var`, `self.__next_f` for each of
20    /// Next.js's pushes. A key that isn't a name is written as a JSON
21    /// string in brackets, `window["a-b"]`.
22    pub name: String,
23    /// The value's expression in the source.
24    pub span: Span,
25    pub value: Result<Json, Refused>,
26}
27
28impl Found {
29    /// The piece as a JSON object, for a binding or a tool that hands
30    /// JSON on: `{"name": …, "value": …}`, or for a value that isn't data
31    /// `{"name": …, "error": {"code": …, "source": …}}`, where `code` is
32    /// the [`Refused`] reason and `source` the start of the text that
33    /// stopped it, at most 80 characters with `…` after a cut. `src` is
34    /// the script the piece was found in.
35    ///
36    /// ```
37    /// use parsec_js::data::page_state;
38    ///
39    /// let src = "window.a = {b: 1}; window.c = f();";
40    /// let found = page_state(src).unwrap();
41    /// let mut out = String::new();
42    /// found[0].write_json(src, &mut out);
43    /// found[1].write_json(src, &mut out);
44    /// assert_eq!(
45    ///     out,
46    ///     r#"{"name":"window.a","value":{"b":1}}{"name":"window.c","error":{"code":"not-a-literal","source":"f()"}}"#
47    /// );
48    /// ```
49    pub fn write_json(&self, src: &str, out: &mut String) {
50        out.push_str(r#"{"name":"#);
51        text::write_json_str(out, &self.name);
52        match &self.value {
53            Ok(value) => {
54                out.push_str(r#","value":"#);
55                out.push_str(&value.to_json_string());
56            }
57            Err(refused) => {
58                out.push_str(r#","error":{"code":"#);
59                text::write_json_str(out, refused.reason);
60                out.push_str(r#","source":"#);
61                let source = refused.span.text(src);
62                match source.char_indices().nth(80) {
63                    Some((cut, _)) => text::write_json_str(out, &format!("{}…", &source[..cut])),
64                    None => text::write_json_str(out, source),
65                }
66                out.push('}');
67            }
68        }
69        out.push('}');
70    }
71}
72
73/// Parses `src` as a script, the text of one `<script>` element, and
74/// finds the page state in it: see [`page_state_in`]. A syntax error is
75/// the `Err`.
76///
77/// ```
78/// use parsec_js::data::page_state;
79///
80/// let src = r#"window.__NUXT__=(function(a,b){return {layout:a,data:[{title:b}]}}("default","Home"));"#;
81/// let found = page_state(src).unwrap();
82/// assert_eq!(found[0].name, "window.__NUXT__");
83/// assert_eq!(
84///     found[0].value.as_ref().unwrap().to_json_string(),
85///     r#"{"layout":"default","data":[{"title":"Home"}]}"#
86/// );
87/// ```
88pub fn page_state(src: &str) -> Result<Vec<Found>, Diagnostic> {
89    Ok(page_state_in(&parse_script(src)?, src))
90}
91
92/// The page state in a parsed script, in source order. Only statements
93/// at the top level count, and of those:
94///
95/// - an assignment with `=` to a property of `window`, `self` or
96///   `globalThis`, however deep (`window.a.b = …`, `window["a"] = …`),
97///   alone or in a comma list;
98/// - a `var`, `let` or `const` declaration, each name with a value;
99/// - `self.__next_f.push(…)`, Next.js App Router's way of handing its
100///   payload over a chunk at a time: [`next_flight`] puts them together.
101///
102/// The value is read with [`literal`](super::literal), with two more
103/// shapes:
104///
105/// - `JSON.parse("…")` with one string literal or template without
106///   substitutions: the string is parsed with [`json`], and a refusal's
107///   span is the string's;
108/// - a function called at once, the way Nuxt 2 writes
109///   `window.__NUXT__=(function(a,b){return {…}}(1,"x"))`: a function
110///   or arrow, not async or a generator, with plain parameters, whose
111///   body only returns a value. Each parameter takes its argument's
112///   value, which must be a literal, or `undefined` past the last one.
113///   Substitution may copy at most 16 times the source's size.
114pub fn page_state_in(ast: &Ast, src: &str) -> Vec<Found> {
115    let mut found = Vec::new();
116    let Node::Program { body, .. } = *ast.node(ast.root()) else {
117        return found;
118    };
119    for &stmt in ast.get(body) {
120        match *ast.node(stmt) {
121            Node::Expression { expression, .. } => {
122                let e = ast.unparenthesized(expression);
123                match *ast.node(e) {
124                    Node::Sequence { expressions } => {
125                        for &e in ast.get(expressions) {
126                            statement(ast, src, ast.unparenthesized(e), &mut found);
127                        }
128                    }
129                    _ => statement(ast, src, e, &mut found),
130                }
131            }
132            Node::VariableDeclaration { declarations, .. } => {
133                for &d in ast.get(declarations) {
134                    let Node::VariableDeclarator {
135                        id,
136                        init: Some(init),
137                    } = *ast.node(d)
138                    else {
139                        continue;
140                    };
141                    if let Node::Identifier = ast.node(id) {
142                        let name = text::ident_name(ast.span(id).text(src)).into_owned();
143                        found.push(read(ast, src, name, init));
144                    }
145                }
146            }
147            _ => {}
148        }
149    }
150    found
151}
152
153/// How a browser runs a `<script>` with this `type` attribute and this
154/// `language` attribute, as the HTML Standard decides it: as a script, as
155/// a module, or, for `None`, not as JavaScript at all (a data block such
156/// as `application/json`, or a template).
157///
158/// ```
159/// use parsec_js::SourceType;
160/// use parsec_js::data::script_type;
161///
162/// assert_eq!(script_type(None, None), Some(SourceType::Script));
163/// assert_eq!(script_type(Some(" Text/JavaScript "), None), Some(SourceType::Script));
164/// assert_eq!(script_type(Some("module"), None), Some(SourceType::Module));
165/// assert_eq!(script_type(Some("application/json"), None), None);
166/// assert_eq!(script_type(None, Some("vbscript")), None);
167/// ```
168pub fn script_type(type_attr: Option<&str>, language: Option<&str>) -> Option<SourceType> {
169    const WS: &[char] = &['\t', '\n', '\x0C', '\r', ' '];
170    let essence = match (type_attr, language) {
171        (Some(""), _) | (None, None | Some("")) => return Some(SourceType::Script),
172        (Some(t), _) => t.trim_matches(WS).to_ascii_lowercase(),
173        (None, Some(l)) => format!("text/{}", l.to_ascii_lowercase()),
174    };
175    if essence == "module" {
176        return Some(SourceType::Module);
177    }
178    let essence = essence.split(';').next().unwrap_or("").trim_matches(WS);
179    let javascript = matches!(
180        essence,
181        "application/ecmascript"
182            | "application/javascript"
183            | "application/x-ecmascript"
184            | "application/x-javascript"
185            | "text/ecmascript"
186            | "text/javascript"
187            | "text/javascript1.0"
188            | "text/javascript1.1"
189            | "text/javascript1.2"
190            | "text/javascript1.3"
191            | "text/javascript1.4"
192            | "text/javascript1.5"
193            | "text/jscript"
194            | "text/livescript"
195            | "text/x-ecmascript"
196            | "text/x-javascript"
197    );
198    javascript.then_some(SourceType::Script)
199}
200
201/// The payload Next.js App Router streamed into the page, put back
202/// together from the `self.__next_f` pushes in `found`, in order.
203///
204/// Each push is an array: `[0]` starts the stream, `[1, "…"]` is a piece
205/// of the payload, `[2, "…"]` is form state and `[3, "…"]` a piece in
206/// base64. Only the type 1 pieces are text, and only together: a row can
207/// start in one push and end in the next. What they make is React's
208/// Flight format, rows of `id:value` ending in newlines; most values are
209/// JSON, and reading them is up to the caller.
210///
211/// ```
212/// use parsec_js::data::{next_flight, page_state};
213///
214/// let src = r#"self.__next_f.push([1,"0:[\"$\",\"div\""]);self.__next_f.push([1,",null,{}]\n"]);"#;
215/// let flight = next_flight(&page_state(src).unwrap());
216/// assert_eq!(flight, "0:[\"$\",\"div\",null,{}]\n");
217/// ```
218pub fn next_flight(found: &[Found]) -> String {
219    let mut out = String::new();
220    for f in found.iter().filter(|f| f.name == "self.__next_f") {
221        if let Ok(Json::Array(items)) = &f.value
222            && let [Json::Number(n), Json::String(s)] = items.as_slice()
223            && *n == 1.0
224        {
225            out.push_str(s);
226        }
227    }
228    out
229}
230
231fn statement(ast: &Ast, src: &str, e: NodeId, found: &mut Vec<Found>) {
232    match *ast.node(e) {
233        Node::Assign {
234            operator: AssignOp::Assign,
235            left,
236            right,
237        } => {
238            if let Some(name) = global(ast, src, left) {
239                found.push(read(ast, src, name, right));
240            }
241        }
242        Node::Call {
243            callee, arguments, ..
244        } => {
245            let [arg] = ast.get(arguments) else { return };
246            let Node::Member {
247                object, property, ..
248            } = *ast.node(callee)
249            else {
250                return;
251            };
252            if name_of(ast, src, property) == Some("push")
253                && member_text(ast, src, object) == Some(("self", "__next_f"))
254            {
255                let value = match ast.node(*arg) {
256                    Node::Spread { .. } => refuse(ast.span(*arg), "spread"),
257                    _ => super::literal(ast, src, *arg),
258                };
259                found.push(Found {
260                    name: "self.__next_f".to_string(),
261                    span: ast.span(*arg),
262                    value,
263                });
264            }
265        }
266        _ => {}
267    }
268}
269
270/// The text of a plain identifier.
271fn name_of<'a>(ast: &Ast, src: &'a str, id: NodeId) -> Option<&'a str> {
272    let span = ast.span(id);
273    matches!(ast.node(id), Node::Identifier).then(|| span.text(src))
274}
275
276/// `a.b` with both plain names, as `("a", "b")`.
277fn member_text<'a>(ast: &Ast, src: &'a str, id: NodeId) -> Option<(&'a str, &'a str)> {
278    match *ast.node(id) {
279        Node::Member {
280            object,
281            property,
282            computed: false,
283            optional: false,
284        } => Some((name_of(ast, src, object)?, name_of(ast, src, property)?)),
285        _ => None,
286    }
287}
288
289/// `window.a.b`'s name, for a chain of properties from `window`, `self`
290/// or `globalThis`, each a name or a string.
291fn global(ast: &Ast, src: &str, left: NodeId) -> Option<String> {
292    let mut keys = Vec::new();
293    let mut id = left;
294    while let Node::Member {
295        object,
296        property,
297        computed,
298        optional: false,
299    } = *ast.node(id)
300    {
301        let span = ast.span(property);
302        let key = match ast.node(property) {
303            Node::Identifier if !computed => text::ident_name(span.text(src)).into_owned(),
304            Node::Literal(LiteralKind::String) if computed => {
305                let body = Span::new(span.start + 1, span.end - 1).text(src);
306                String::from_utf16(&text::string_value(body)).ok()?
307            }
308            _ => return None,
309        };
310        keys.push(key);
311        id = object;
312    }
313    let root = name_of(ast, src, id)?;
314    if keys.is_empty() || !matches!(root, "window" | "self" | "globalThis") {
315        return None;
316    }
317    let mut name = root.to_string();
318    for key in keys.iter().rev() {
319        let plain = key.chars().enumerate().all(|(i, c)| {
320            c == '_' || c == '$' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit())
321        });
322        if plain && !key.is_empty() {
323            name.push('.');
324            name.push_str(key);
325        } else {
326            name.push('[');
327            text::write_json_str(&mut name, key);
328            name.push(']');
329        }
330    }
331    Some(name)
332}
333
334fn read(ast: &Ast, src: &str, name: String, value: NodeId) -> Found {
335    Found {
336        name,
337        span: ast.span(value),
338        value: state(ast, src, value),
339    }
340}
341
342/// The value assigned: `JSON.parse` of a string, a function called with
343/// literals, or a literal.
344fn state(ast: &Ast, src: &str, id: NodeId) -> Result<Json, Refused> {
345    let id = ast.unparenthesized(id);
346    if let Node::Call {
347        callee,
348        arguments,
349        optional: false,
350    } = *ast.node(id)
351    {
352        let callee = ast.unparenthesized(callee);
353        if member_text(ast, src, callee) == Some(("JSON", "parse")) {
354            return json_parse(ast, src, ast.get(arguments))
355                .unwrap_or_else(|| refuse(ast.span(id), "not-a-literal"));
356        }
357        if let Node::Function(f) = *ast.node(callee)
358            && !f.is_async
359            && !f.generator
360        {
361            return call(ast, src, f, ast.get(arguments));
362        }
363    }
364    super::literal(ast, src, id)
365}
366
367/// `JSON.parse(text)`'s value, `None` unless `args` is one string.
368fn json_parse(ast: &Ast, src: &str, args: &[NodeId]) -> Option<Result<Json, Refused>> {
369    let &[arg] = args else { return None };
370    let arg = ast.unparenthesized(arg);
371    if !matches!(
372        ast.node(arg),
373        Node::Literal(LiteralKind::String) | Node::Template { .. }
374    ) {
375        return None;
376    }
377    // The text's offsets don't map back through the string's escapes, so
378    // a refusal points at the string.
379    let span = ast.span(arg);
380    Some(match super::literal(ast, src, arg) {
381        Ok(Json::String(s)) => json(&s).map_err(|r| Refused { span, ..r }),
382        Ok(_) => refuse(span, "not-a-literal"),
383        Err(r) => Err(r),
384    })
385}
386
387/// The value a function returns, called with `args`.
388fn call(ast: &Ast, src: &str, f: crate::ast::Function, args: &[NodeId]) -> Result<Json, Refused> {
389    let mut reader = Reader::new(ast, src);
390    let mut values = Vec::with_capacity(args.len());
391    for &arg in args {
392        if let Node::Spread { .. } = ast.node(arg) {
393            return refuse(ast.span(arg), "spread");
394        }
395        values.push(reader.value(arg)?);
396    }
397    let mut env = HashMap::new();
398    let mut values = values.into_iter();
399    for &param in ast.get(f.params) {
400        if !matches!(ast.node(param), Node::Identifier) {
401            return refuse(ast.span(param), "parameters");
402        }
403        let name = text::ident_name(ast.span(param).text(src)).into_owned();
404        env.insert(name, values.next().flatten());
405    }
406    let returned = if f.expression {
407        f.body
408    } else {
409        let Node::Block { body } = *ast.node(f.body) else {
410            return refuse(ast.span(f.body), "function-body");
411        };
412        match ast.get(body) {
413            [stmt] => match *ast.node(*stmt) {
414                Node::Return {
415                    argument: Some(arg),
416                } => arg,
417                _ => return refuse(ast.span(f.body), "function-body"),
418            },
419            _ => return refuse(ast.span(f.body), "function-body"),
420        }
421    };
422    reader.env = env;
423    // shortcut: a flat cap of 16 bytes copied per source byte, which Nuxt's
424    // output stays far below; a caller-set limit if one ever needs more.
425    reader.budget = src.len().saturating_mul(16);
426    reader.whole(returned)
427}