1use 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#[derive(Clone, Debug, PartialEq)]
17pub struct Found {
18 pub name: String,
23 pub span: Span,
25 pub value: Result<Json, Refused>,
26}
27
28impl Found {
29 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
73pub fn page_state(src: &str) -> Result<Vec<Found>, Diagnostic> {
89 Ok(page_state_in(&parse_script(src)?, src))
90}
91
92pub 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
153pub 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
201pub 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
270fn 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
276fn 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
289fn 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
342fn 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
367fn 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 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
387fn 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 ¶m 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 reader.budget = src.len().saturating_mul(16);
426 reader.whole(returned)
427}