Skip to main content

Module data

Module data 

Source
Expand description

Data from scripts: the state a page writes into a <script> as a literal, read as JSON without running anything.

literal turns an expression made only of literals into a Json value, and refuses anything else with the span that stopped it. page_state finds the shapes pages put their state in (window.__NUXT__ = …, var ytInitialData = …, JSON.parse("…"), Next.js’s self.__next_f.push(…)) and reads each one’s value. json parses JSON text strictly, as JSON.parse does, for state that’s in a script as JSON, like Next.js’s __NEXT_DATA__.

Nothing is evaluated. No property is read, no function called and no name looked up, with one exception: the arguments of a Nuxt function that only returns a literal are put in place of its parameters.

use parsec_js::data::{Json, page_state};

let src = r#"window.__STATE__ = {user: {name: "Ada", admin: !1}, cart: [1, , 3]};"#;
let found = page_state(src).unwrap();
assert_eq!(found[0].name, "window.__STATE__");
let value = found[0].value.as_ref().unwrap();
assert_eq!(
    value.to_json_string(),
    r#"{"user":{"name":"Ada","admin":false},"cart":[1,null,3]}"#
);

Structs§

Found
A piece of page state: where a script put it, and its value, or why it isn’t data.
Refused
Why a value isn’t data, and where it stopped being.

Enums§

Json
A JSON value. An object keeps its keys in the order they first appear, each once.

Functions§

json
Parses text as JSON, the way JSON.parse does without a reviver: no comments, no trailing commas, no single quotes, no byte order mark. A key given twice keeps its first place and its last value. Spans in a refusal are byte offsets in text.
literal
The value of expr, an expression in ast parsed from src, if it’s made only of literals:
next_flight
The payload Next.js App Router streamed into the page, put back together from the self.__next_f pushes in found, in order.
page_state
Parses src as a script, the text of one <script> element, and finds the page state in it: see page_state_in. A syntax error is the Err.
page_state_in
The page state in a parsed script, in source order. Only statements at the top level count, and of those:
script_type
How a browser runs a <script> with this type attribute and this language attribute, as the HTML Standard decides it: as a script, as a module, or, for None, not as JavaScript at all (a data block such as application/json, or a template).