22 return 0 if x
in (None, JS_Undefined
) else x
25 return op(zeroise(a
), zeroise(b
)) & 0xffffffff
33 if JS_Undefined
in (a
, b
):
35 return op(a
or 0, b
or 0)
41 if JS_Undefined
in (a
, b
) or not (a
and b
):
43 return (a
or 0) / b
if b
else float('inf')
47 if JS_Undefined
in (a
, b
) or not b
:
54 return 1 # even 0 ** 0 !!
55 elif JS_Undefined
in (a
, b
):
63 if {a, b}
<= {None, JS_Undefined}
:
73 if JS_Undefined
in (a
, b
):
75 return op(a
or 0, b
or 0)
80 def _js_ternary(cndn
, if_true
=True, if_false
=False):
81 """Simulate JS's ternary operator (cndn?if_true:if_false)"""
82 if cndn
in (False, None, 0, '', JS_Undefined
):
84 with contextlib
.suppress(TypeError):
85 if math
.isnan(cndn
): # NB: NaN cannot be checked by membership
90 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
91 _OPERATORS
= { # None => Defined in JSInterpreter._operator
97 '|': _js_bit_op(operator
.or_
),
98 '^': _js_bit_op(operator
.xor
),
99 '&': _js_bit_op(operator
.and_
),
102 '!==': operator
.is_not
,
103 '==': _js_eq_op(operator
.eq
),
104 '!=': _js_eq_op(operator
.ne
),
106 '<=': _js_comp_op(operator
.le
),
107 '>=': _js_comp_op(operator
.ge
),
108 '<': _js_comp_op(operator
.lt
),
109 '>': _js_comp_op(operator
.gt
),
111 '>>': _js_bit_op(operator
.rshift
),
112 '<<': _js_bit_op(operator
.lshift
),
114 '+': _js_arith_op(operator
.add
),
115 '-': _js_arith_op(operator
.sub
),
117 '*': _js_arith_op(operator
.mul
),
123 _COMP_OPERATORS
= {'===', '!==', '==', '!=', '<=', '>=', '<', '>'}
125 _NAME_RE
= r
'[a-zA-Z_$][\w$]*'
126 _MATCHING_PARENS
= dict(zip(*zip('()', '{}', '[]')))
134 class JS_Break(ExtractorError
):
136 ExtractorError
.__init
__(self
, 'Invalid break')
139 class JS_Continue(ExtractorError
):
141 ExtractorError
.__init
__(self
, 'Invalid continue')
144 class JS_Throw(ExtractorError
):
145 def __init__(self
, e
):
147 ExtractorError
.__init
__(self
, f
'Uncaught exception {e}')
150 class LocalNameSpace(collections
.ChainMap
):
151 def __setitem__(self
, key
, value
):
152 for scope
in self
.maps
:
156 self
.maps
[0][key
] = value
158 def __delitem__(self
, key
):
159 raise NotImplementedError('Deleting is not supported')
164 ENABLED
= False and 'pytest' in sys
.modules
167 def write(*args
, level
=100):
168 write_string(f
'[debug] JS: {" " * (100 - level)}'
169 f
'{" ".join(truncate_string(str(x), 50, 50) for x in args)}\n')
172 def wrap_interpreter(cls
, f
):
173 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
):
174 if cls
.ENABLED
and stmt
.strip():
175 cls
.write(stmt
, level
=allow_recursion
)
177 ret
, should_ret
= f(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
)
178 except Exception as e
:
180 if isinstance(e
, ExtractorError
):
182 cls
.write('=> Raises:', e
, '<-|', stmt
, level
=allow_recursion
)
184 if cls
.ENABLED
and stmt
.strip():
185 cls
.write(['->', '=>'][should_ret
], repr(ret
), '<-|', stmt
, level
=allow_recursion
)
186 return ret
, should_ret
187 return interpret_statement
191 __named_object_counter
= 0
194 # special knowledge: Python's re flags are bitmask values, current max 128
195 # invent new bitmask values well above that for literal parsing
196 # TODO: new pattern class to execute matches with these flags
197 'd': 1024, # Generate indices for substring matches
198 'g': 2048, # Global search
199 'i': re
.I
, # Case-insensitive search
200 'm': re
.M
, # Multi-line search
201 's': re
.S
, # Allows . to match newline characters
202 'u': re
.U
, # Treat a pattern as a sequence of unicode code points
203 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
206 _EXC_NAME
= '__yt_dlp_exception__'
208 def __init__(self
, code
, objects
=None):
209 self
.code
, self
._functions
= code
, {}
210 self
._objects
= {} if objects
is None else objects
212 class Exception(ExtractorError
):
213 def __init__(self
, msg
, expr
=None, *args
, **kwargs
):
215 msg
= f
'{msg.rstrip()} in: {truncate_string(expr, 50, 50)}'
216 super().__init
__(msg
, *args
, **kwargs
)
218 def _named_object(self
, namespace
, obj
):
219 self
.__named
_object
_counter
+= 1
220 name
= f
'__yt_dlp_jsinterp_obj{self.__named_object_counter}'
221 namespace
[name
] = obj
225 def _regex_flags(cls
, expr
):
229 for idx
, ch
in enumerate(expr
):
230 if ch
not in cls
._RE
_FLAGS
:
232 flags |
= cls
._RE
_FLAGS
[ch
]
233 return flags
, expr
[idx
+ 1:]
236 def _separate(expr
, delim
=',', max_split
=None):
237 OP_CHARS
= '+-*/%&|^=<>!,;{}:'
240 counters
= {k: 0 for k in _MATCHING_PARENS.values()}
241 start
, splits
, pos
, delim_len
= 0, 0, 0, len(delim
) - 1
242 in_quote
, escaping
, after_op
, in_regex_char_group
= None, False, True, False
243 for idx
, char
in enumerate(expr
):
244 if not in_quote
and char
in _MATCHING_PARENS
:
245 counters
[_MATCHING_PARENS
[char
]] += 1
246 elif not in_quote
and char
in counters
:
249 if char
in _QUOTES
and in_quote
in (char
, None):
250 if in_quote
or after_op
or char
!= '/':
251 in_quote
= None if in_quote
and not in_regex_char_group
else char
252 elif in_quote
== '/' and char
in '[]':
253 in_regex_char_group
= char
== '['
254 escaping
= not escaping
and in_quote
and char
== '\\'
255 after_op
= not in_quote
and char
in OP_CHARS
or (char
.isspace() and after_op
)
257 if char
!= delim
[pos
] or any(counters
.values()) or in_quote
:
260 elif pos
!= delim_len
:
263 yield expr
[start
: idx
- delim_len
]
264 start
, pos
= idx
+ 1, 0
266 if max_split
and splits
>= max_split
:
271 def _separate_at_paren(cls
, expr
, delim
):
272 separated
= list(cls
._separate
(expr
, delim
, 1))
273 if len(separated
) < 2:
274 raise cls
.Exception(f
'No terminating paren {delim}', expr
)
275 return separated
[0][1:].strip(), separated
[1].strip()
277 def _operator(self
, op
, left_val
, right_expr
, expr
, local_vars
, allow_recursion
):
278 if op
in ('||', '&&'):
279 if (op
== '&&') ^
_js_ternary(left_val
):
280 return left_val
# short circuiting
282 if left_val
not in (None, JS_Undefined
):
285 right_expr
= _js_ternary(left_val
, *self
._separate
(right_expr
, ':', 1))
287 right_val
= self
.interpret_expression(right_expr
, local_vars
, allow_recursion
)
288 if not _OPERATORS
.get(op
):
292 return _OPERATORS
[op
](left_val
, right_val
)
293 except Exception as e
:
294 raise self
.Exception(f
'Failed to evaluate {left_val!r} {op} {right_val!r}', expr
, cause
=e
)
296 def _index(self
, obj
, idx
, allow_undefined
=False):
300 return obj
[int(idx
)] if isinstance(obj
, list) else obj
[idx
]
301 except Exception as e
:
304 raise self
.Exception(f
'Cannot get index {idx}', repr(obj
), cause
=e
)
306 def _dump(self
, obj
, namespace
):
308 return json
.dumps(obj
)
310 return self
._named
_object
(namespace
, obj
)
312 @Debugger.wrap_interpreter
313 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
=100):
314 if allow_recursion
< 0:
315 raise self
.Exception('Recursion limit reached')
318 should_return
= False
319 sub_statements
= list(self
._separate
(stmt
, ';')) or ['']
320 expr
= stmt
= sub_statements
.pop().strip()
322 for sub_stmt
in sub_statements
:
323 ret
, should_return
= self
.interpret_statement(sub_stmt
, local_vars
, allow_recursion
)
325 return ret
, should_return
327 m
= re
.match(r
'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$
)|
(?P
<throw
>throw\s
+)', stmt)
329 expr = stmt[len(m.group(0)):].strip()
331 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
332 should_return = not m.group('var
')
334 return None, should_return
336 if expr[0] in _QUOTES:
337 inner, outer = self._separate(expr, expr[0], 1)
339 flags, outer = self._regex_flags(outer)
340 inner = re.compile(inner[1:], flags=flags)
342 inner = json.loads(js_to_json(f'{inner}{expr[0]}
', strict=True))
344 return inner, should_return
345 expr = self._named_object(local_vars, inner) + outer
347 if expr.startswith('new
'):
349 if obj.startswith('Date('):
350 left, right = self._separate_at_paren(obj[4:], ')')
351 expr = unified_timestamp(
352 self.interpret_expression(left, local_vars, allow_recursion), False)
354 raise self.Exception(f'Failed to parse date {left!r}
', expr)
355 expr = self._dump(int(expr * 1000), local_vars) + right
357 raise self.Exception(f'Unsupported
object {obj}
', expr)
359 if expr.startswith('void
'):
360 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
361 return None, should_return
363 if expr.startswith('{'):
364 inner, outer = self._separate_at_paren(expr, '}')
366 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
367 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
368 def dict_item(key, val):
369 val = self.interpret_expression(val, local_vars, allow_recursion)
370 if re.match(_NAME_RE, key):
372 return self.interpret_expression(key, local_vars, allow_recursion), val
374 return dict(dict_item(k, v) for k, v in sub_expressions), should_return
376 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
377 if not outer or should_abort:
378 return inner, should_abort or should_return
380 expr = self._dump(inner, local_vars) + outer
382 if expr.startswith('('):
383 inner, outer = self._separate_at_paren(expr, ')')
384 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
385 if not outer or should_abort:
386 return inner, should_abort or should_return
388 expr = self._dump(inner, local_vars) + outer
390 if expr.startswith('['):
391 inner, outer = self._separate_at_paren(expr, ']')
392 name = self._named_object(local_vars, [
393 self.interpret_expression(item, local_vars, allow_recursion)
394 for item in self._separate(inner)])
397 m = re.match(rf'''(?x)
398 (?P<try>try|finally)\s*|
399 (?P<catch>catch\s*(?P<err>\(\s*{_NAME_RE}\s*\)))|
400 (?P<switch>switch)\s*\(|
401 (?P<for>for)\s*\(|''', expr)
402 if m and m.group('try'):
403 if expr[m.end()] == '{':
404 try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
406 try_expr, expr = expr[m.end() - 1:], ''
408 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
411 except JS_Throw as e:
412 local_vars[self._EXC_NAME] = e.error
413 except Exception as e:
414 # XXX: This works for now, but makes debugging future issues very hard
415 local_vars[self._EXC_NAME] = e
416 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
417 return ret, should_abort or should_return
419 elif m and m.group('catch
'):
420 catch_expr, expr = self._separate_at_paren(expr[m.end():], '}')
421 if self._EXC_NAME in local_vars:
422 catch_vars = local_vars.new_child({m.group('err'): local_vars.pop(self._EXC_NAME)})
423 ret, should_abort = self.interpret_statement(catch_expr, catch_vars, allow_recursion)
427 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
428 return ret, should_abort or should_return
430 elif m and m.group('for'):
431 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
432 if remaining.startswith('{'):
433 body, expr = self._separate_at_paren(remaining, '}')
435 switch_m = re.match(r'switch\s
*\
(', remaining) # FIXME
437 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
438 body, expr = self._separate_at_paren(remaining, '}')
439 body = 'switch(%s){%s}
' % (switch_val, body)
441 body, expr = remaining, ''
442 start, cndn, increment = self._separate(constructor, ';')
443 self.interpret_expression(start, local_vars, allow_recursion)
445 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
448 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
455 self.interpret_expression(increment, local_vars, allow_recursion)
456 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
457 return ret, should_abort or should_return
459 elif m and m.group('switch
'):
460 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
461 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
462 body, expr = self._separate_at_paren(remaining, '}')
463 items = body.replace('default
:', 'case default
:').split('case
')[1:]
464 for default in (False, True):
467 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
469 matched = matched or case == 'default
'
471 matched = (case != 'default
'
472 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
476 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
483 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
484 return ret, should_abort or should_return
486 # Comma separated statements
487 sub_expressions = list(self._separate(expr))
488 if len(sub_expressions) > 1:
489 for sub_expr in sub_expressions:
490 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
495 for m in re.finditer(rf'''(?x)
496 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
497 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr):
498 var = m.group('var1
') or m.group('var2
')
499 start, end = m.span()
500 sign = m.group('pre_sign
') or m.group('post_sign
')
501 ret = local_vars[var]
502 local_vars[var] += 1 if sign[0] == '+' else -1
503 if m.group('pre_sign
'):
504 ret = local_vars[var]
505 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
508 return None, should_return
510 m = re.match(fr'''(?x)
512 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
513 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
516 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
518 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
520 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
522 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
524 if m and m.group('assign
'):
525 left_val = local_vars.get(m.group('out
'))
527 if not m.group('index
'):
528 local_vars[m.group('out
')] = self._operator(
529 m.group('op
'), left_val, m.group('expr
'), expr, local_vars, allow_recursion)
530 return local_vars[m.group('out
')], should_return
531 elif left_val in (None, JS_Undefined):
532 raise self.Exception(f'Cannot index undefined variable {m.group("out")}
', expr)
534 idx = self.interpret_expression(m.group('index
'), local_vars, allow_recursion)
535 if not isinstance(idx, (int, float)):
536 raise self.Exception(f'List index {idx} must be integer
', expr)
538 left_val[idx] = self._operator(
539 m.group('op
'), self._index(left_val, idx), m.group('expr
'), expr, local_vars, allow_recursion)
540 return left_val[idx], should_return
543 return int(expr), should_return
545 elif expr == 'break':
547 elif expr == 'continue':
549 elif expr == 'undefined
':
550 return JS_Undefined, should_return
552 return float('NaN
'), should_return
554 elif m and m.group('return'):
555 return local_vars.get(m.group('name
'), JS_Undefined), should_return
557 with contextlib.suppress(ValueError):
558 return json.loads(js_to_json(expr, strict=True)), should_return
560 if m and m.group('indexing
'):
561 val = local_vars[m.group('in')]
562 idx = self.interpret_expression(m.group('idx
'), local_vars, allow_recursion)
563 return self._index(val, idx), should_return
565 for op in _OPERATORS:
566 separated = list(self._separate(expr, op))
567 right_expr = separated.pop()
569 if op in '?
<>*-' and len(separated) > 1 and not separated[-1].strip():
571 elif not (separated and op == '?
' and right_expr.startswith('.')):
573 right_expr = f'{op}{right_expr}
'
575 right_expr = f'{separated.pop()}{op}{right_expr}
'
578 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
579 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
581 if m and m.group('attribute
'):
582 variable, member, nullish = m.group('var
', 'member
', 'nullish
')
584 member = self.interpret_expression(m.group('member2
'), local_vars, allow_recursion)
585 arg_str = expr[m.end():]
586 if arg_str.startswith('('):
587 arg_str, remaining = self._separate_at_paren(arg_str, ')')
589 arg_str, remaining = None, arg_str
591 def assertion(cndn, msg):
592 """ assert, but without risk of getting optimized out """
594 raise self.Exception(f'{member} {msg}
', expr)
597 if (variable, member) == ('console
', 'debug
'):
599 Debugger.write(self.interpret_expression(f'[{arg_str}
]', local_vars, allow_recursion))
606 obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
607 if obj is NO_DEFAULT:
608 if variable not in self._objects:
610 self._objects[variable] = self.extract_object(variable)
611 except self.Exception:
614 obj = self._objects.get(variable, JS_Undefined)
616 if nullish and obj is JS_Undefined:
621 return self._index(obj, member, nullish)
625 self.interpret_expression(v, local_vars, allow_recursion)
626 for v in self._separate(arg_str)]
629 if member == 'fromCharCode
':
630 assertion(argvals, 'takes one
or more arguments
')
631 return ''.join(map(chr, argvals))
632 raise self.Exception(f'Unsupported String method {member}
', expr)
635 assertion(len(argvals) == 2, 'takes two arguments
')
636 return argvals[0] ** argvals[1]
637 raise self.Exception(f'Unsupported Math method {member}
', expr)
639 if member == 'split
':
640 assertion(argvals, 'takes one
or more arguments
')
641 assertion(len(argvals) == 1, 'with limit argument
is not implemented
')
642 return obj.split(argvals[0]) if argvals[0] else list(obj)
643 elif member == 'join
':
644 assertion(isinstance(obj, list), 'must be applied on a
list')
645 assertion(len(argvals) == 1, 'takes exactly one argument
')
646 return argvals[0].join(obj)
647 elif member == 'reverse
':
648 assertion(not argvals, 'does
not take any arguments
')
651 elif member == 'slice':
652 assertion(isinstance(obj, list), 'must be applied on a
list')
653 assertion(len(argvals) == 1, 'takes exactly one argument
')
654 return obj[argvals[0]:]
655 elif member == 'splice
':
656 assertion(isinstance(obj, list), 'must be applied on a
list')
657 assertion(argvals, 'takes one
or more arguments
')
658 index, howMany = map(int, (argvals + [len(obj)])[:2])
661 add_items = argvals[2:]
663 for i in range(index, min(index + howMany, len(obj))):
664 res.append(obj.pop(index))
665 for i, item in enumerate(add_items):
666 obj.insert(index + i, item)
668 elif member == 'unshift
':
669 assertion(isinstance(obj, list), 'must be applied on a
list')
670 assertion(argvals, 'takes one
or more arguments
')
671 for item in reversed(argvals):
674 elif member == 'pop
':
675 assertion(isinstance(obj, list), 'must be applied on a
list')
676 assertion(not argvals, 'does
not take any arguments
')
680 elif member == 'push
':
681 assertion(argvals, 'takes one
or more arguments
')
684 elif member == 'forEach
':
685 assertion(argvals, 'takes one
or more arguments
')
686 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
687 f, this = (argvals + [''])[:2]
688 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
689 elif member == 'indexOf
':
690 assertion(argvals, 'takes one
or more arguments
')
691 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
692 idx, start = (argvals + [0])[:2]
694 return obj.index(idx, start)
697 elif member == 'charCodeAt
':
698 assertion(isinstance(obj, str), 'must be applied on a string
')
699 assertion(len(argvals) == 1, 'takes exactly one argument
')
700 idx = argvals[0] if isinstance(argvals[0], int) else 0
705 idx = int(member) if isinstance(obj, list) else member
706 return obj[idx](argvals, allow_recursion=allow_recursion)
709 ret, should_abort = self.interpret_statement(
710 self._named_object(local_vars, eval_method()) + remaining,
711 local_vars, allow_recursion)
712 return ret, should_return or should_abort
714 return eval_method(), should_return
716 elif m and m.group('function
'):
717 fname = m.group('fname
')
718 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
719 for v in self._separate(m.group('args
'))]
720 if fname in local_vars:
721 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
722 elif fname not in self._functions:
723 self._functions[fname] = self.extract_function(fname)
724 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
726 raise self.Exception(
727 f'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}
', stmt)
729 def interpret_expression(self, expr, local_vars, allow_recursion):
730 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
732 raise self.Exception('Cannot
return from an expression
', expr)
735 def extract_object(self, objname):
736 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a
-zA
-Z$
0-9]+')'''
740 (?<!this\.)%s\s*=\s*{\s*
741 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
743 ''' % (re.escape(objname), _FUNC_NAME_RE),
746 raise self.Exception(f'Could
not find
object {objname}
')
747 fields = obj_m.group('fields
')
748 # Currently, it only supports function definitions
749 fields_m = re.finditer(
751 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
752 ''' % (_FUNC_NAME_RE, _NAME_RE),
755 argnames = f.group('args
').split(',')
756 obj[remove_quotes(f.group('key
'))] = self.build_function(argnames, f.group('code
'))
760 def extract_function_code(self, funcname):
761 """ @returns argnames, code """
766 [{;,]\s*%(name)s\s*=\s*function|
767 (?:var|const|let)\s+%(name)s\s*=\s*function
769 \((?P<args>[^)]*)\)\s*
770 (?P<code>{.+})''' % {'name': re.escape(funcname)},
772 code, _ = self._separate_at_paren(func_m.group('code
'), '}')
774 raise self.Exception(f'Could
not find JS function
"{funcname}"')
775 return [x.strip() for x in func_m.group('args
').split(',')], code
777 def extract_function(self, funcname):
778 return self.extract_function_from_code(*self.extract_function_code(funcname))
780 def extract_function_from_code(self, argnames, code, *global_stack):
783 mobj = re.search(r'function\
((?P
<args
>[^
)]*)\
)\s
*{', code)
786 start, body_start = mobj.span()
787 body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
788 name = self._named_object(local_vars, self.extract_function_from_code(
789 [x.strip() for x in mobj.group('args
').split(',')],
790 body, local_vars, *global_stack))
791 code = code[:start] + name + remaining
792 return self.build_function(argnames, code, local_vars, *global_stack)
794 def call_function(self, funcname, *args):
795 return self.extract_function(funcname)(args)
797 def build_function(self, argnames, code, *global_stack):
798 global_stack = list(global_stack) or [{}]
799 argnames = tuple(argnames)
801 def resf(args, kwargs={}, allow_recursion=100):
802 global_stack[0].update(itertools.zip_longest(argnames, args, fillvalue=None))
803 global_stack[0].update(kwargs)
804 var_stack = LocalNameSpace(*global_stack)
805 ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)