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
textas JSON, the wayJSON.parsedoes 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 intext. - literal
- The value of
expr, an expression inastparsed fromsrc, 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_fpushes infound, in order. - page_
state - Parses
srcas a script, the text of one<script>element, and finds the page state in it: seepage_state_in. A syntax error is theErr. - 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 thistypeattribute and thislanguageattribute, as the HTML Standard decides it: as a script, as a module, or, forNone, not as JavaScript at all (a data block such asapplication/json, or a template).