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 if isinstance(a
, str) or isinstance(b
, str):
76 return op(str(a
or 0), str(b
or 0))
77 return op(a
or 0, b
or 0)
82 def _js_ternary(cndn
, if_true
=True, if_false
=False):
83 """Simulate JS's ternary operator (cndn?if_true:if_false)"""
84 if cndn
in (False, None, 0, '', JS_Undefined
):
86 with contextlib
.suppress(TypeError):
87 if math
.isnan(cndn
): # NB: NaN cannot be checked by membership
92 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
93 _OPERATORS
= { # None => Defined in JSInterpreter._operator
99 '|': _js_bit_op(operator
.or_
),
100 '^': _js_bit_op(operator
.xor
),
101 '&': _js_bit_op(operator
.and_
),
104 '!==': operator
.is_not
,
105 '==': _js_eq_op(operator
.eq
),
106 '!=': _js_eq_op(operator
.ne
),
108 '<=': _js_comp_op(operator
.le
),
109 '>=': _js_comp_op(operator
.ge
),
110 '<': _js_comp_op(operator
.lt
),
111 '>': _js_comp_op(operator
.gt
),
113 '>>': _js_bit_op(operator
.rshift
),
114 '<<': _js_bit_op(operator
.lshift
),
116 '+': _js_arith_op(operator
.add
),
117 '-': _js_arith_op(operator
.sub
),
119 '*': _js_arith_op(operator
.mul
),
125 _COMP_OPERATORS
= {'===', '!==', '==', '!=', '<=', '>=', '<', '>'}
127 _NAME_RE
= r
'[a-zA-Z_$][\w$]*'
128 _MATCHING_PARENS
= dict(zip(*zip('()', '{}', '[]')))
136 class JS_Break(ExtractorError
):
138 ExtractorError
.__init
__(self
, 'Invalid break')
141 class JS_Continue(ExtractorError
):
143 ExtractorError
.__init
__(self
, 'Invalid continue')
146 class JS_Throw(ExtractorError
):
147 def __init__(self
, e
):
149 ExtractorError
.__init
__(self
, f
'Uncaught exception {e}')
152 class LocalNameSpace(collections
.ChainMap
):
153 def __setitem__(self
, key
, value
):
154 for scope
in self
.maps
:
158 self
.maps
[0][key
] = value
160 def __delitem__(self
, key
):
161 raise NotImplementedError('Deleting is not supported')
166 ENABLED
= False and 'pytest' in sys
.modules
169 def write(*args
, level
=100):
170 write_string(f
'[debug] JS: {" " * (100 - level)}'
171 f
'{" ".join(truncate_string(str(x), 50, 50) for x in args)}\n')
174 def wrap_interpreter(cls
, f
):
175 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
):
176 if cls
.ENABLED
and stmt
.strip():
177 cls
.write(stmt
, level
=allow_recursion
)
179 ret
, should_ret
= f(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
)
180 except Exception as e
:
182 if isinstance(e
, ExtractorError
):
184 cls
.write('=> Raises:', e
, '<-|', stmt
, level
=allow_recursion
)
186 if cls
.ENABLED
and stmt
.strip():
187 cls
.write(['->', '=>'][should_ret
], repr(ret
), '<-|', stmt
, level
=allow_recursion
)
188 return ret
, should_ret
189 return interpret_statement
193 __named_object_counter
= 0
196 # special knowledge: Python's re flags are bitmask values, current max 128
197 # invent new bitmask values well above that for literal parsing
198 # TODO: new pattern class to execute matches with these flags
199 'd': 1024, # Generate indices for substring matches
200 'g': 2048, # Global search
201 'i': re
.I
, # Case-insensitive search
202 'm': re
.M
, # Multi-line search
203 's': re
.S
, # Allows . to match newline characters
204 'u': re
.U
, # Treat a pattern as a sequence of unicode code points
205 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
208 _EXC_NAME
= '__yt_dlp_exception__'
210 def __init__(self
, code
, objects
=None):
211 self
.code
, self
._functions
= code
, {}
212 self
._objects
= {} if objects
is None else objects
214 class Exception(ExtractorError
):
215 def __init__(self
, msg
, expr
=None, *args
, **kwargs
):
217 msg
= f
'{msg.rstrip()} in: {truncate_string(expr, 50, 50)}'
218 super().__init
__(msg
, *args
, **kwargs
)
220 def _named_object(self
, namespace
, obj
):
221 self
.__named
_object
_counter
+= 1
222 name
= f
'__yt_dlp_jsinterp_obj{self.__named_object_counter}'
223 namespace
[name
] = obj
227 def _regex_flags(cls
, expr
):
231 for idx
, ch
in enumerate(expr
):
232 if ch
not in cls
._RE
_FLAGS
:
234 flags |
= cls
._RE
_FLAGS
[ch
]
235 return flags
, expr
[idx
+ 1:]
238 def _separate(expr
, delim
=',', max_split
=None):
239 OP_CHARS
= '+-*/%&|^=<>!,;{}:['
242 counters
= {k: 0 for k in _MATCHING_PARENS.values()}
243 start
, splits
, pos
, delim_len
= 0, 0, 0, len(delim
) - 1
244 in_quote
, escaping
, after_op
, in_regex_char_group
= None, False, True, False
245 for idx
, char
in enumerate(expr
):
246 if not in_quote
and char
in _MATCHING_PARENS
:
247 counters
[_MATCHING_PARENS
[char
]] += 1
248 elif not in_quote
and char
in counters
:
249 # Something's wrong if we get negative, but ignore it anyway
253 if char
in _QUOTES
and in_quote
in (char
, None):
254 if in_quote
or after_op
or char
!= '/':
255 in_quote
= None if in_quote
and not in_regex_char_group
else char
256 elif in_quote
== '/' and char
in '[]':
257 in_regex_char_group
= char
== '['
258 escaping
= not escaping
and in_quote
and char
== '\\'
259 after_op
= not in_quote
and char
in OP_CHARS
or (char
.isspace() and after_op
)
261 if char
!= delim
[pos
] or any(counters
.values()) or in_quote
:
264 elif pos
!= delim_len
:
267 yield expr
[start
: idx
- delim_len
]
268 start
, pos
= idx
+ 1, 0
270 if max_split
and splits
>= max_split
:
275 def _separate_at_paren(cls
, expr
, delim
=None):
277 delim
= expr
and _MATCHING_PARENS
[expr
[0]]
278 separated
= list(cls
._separate
(expr
, delim
, 1))
279 if len(separated
) < 2:
280 raise cls
.Exception(f
'No terminating paren {delim}', expr
)
281 return separated
[0][1:].strip(), separated
[1].strip()
283 def _operator(self
, op
, left_val
, right_expr
, expr
, local_vars
, allow_recursion
):
284 if op
in ('||', '&&'):
285 if (op
== '&&') ^
_js_ternary(left_val
):
286 return left_val
# short circuiting
288 if left_val
not in (None, JS_Undefined
):
291 right_expr
= _js_ternary(left_val
, *self
._separate
(right_expr
, ':', 1))
293 right_val
= self
.interpret_expression(right_expr
, local_vars
, allow_recursion
)
294 if not _OPERATORS
.get(op
):
298 return _OPERATORS
[op
](left_val
, right_val
)
299 except Exception as e
:
300 raise self
.Exception(f
'Failed to evaluate {left_val!r} {op} {right_val!r}', expr
, cause
=e
)
302 def _index(self
, obj
, idx
, allow_undefined
=False):
306 return obj
[int(idx
)] if isinstance(obj
, list) else obj
[idx
]
307 except Exception as e
:
310 raise self
.Exception(f
'Cannot get index {idx}', repr(obj
), cause
=e
)
312 def _dump(self
, obj
, namespace
):
314 return json
.dumps(obj
)
316 return self
._named
_object
(namespace
, obj
)
318 @Debugger.wrap_interpreter
319 def interpret_statement(self
, stmt
, local_vars
, allow_recursion
=100):
320 if allow_recursion
< 0:
321 raise self
.Exception('Recursion limit reached')
324 should_return
= False
325 sub_statements
= list(self
._separate
(stmt
, ';')) or ['']
326 expr
= stmt
= sub_statements
.pop().strip()
328 for sub_stmt
in sub_statements
:
329 ret
, should_return
= self
.interpret_statement(sub_stmt
, local_vars
, allow_recursion
)
331 return ret
, should_return
333 m
= re
.match(r
'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$
)|
(?P
<throw
>throw\s
+)', stmt)
335 expr = stmt[len(m.group(0)):].strip()
337 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
338 should_return = not m.group('var
')
340 return None, should_return
342 if expr[0] in _QUOTES:
343 inner, outer = self._separate(expr, expr[0], 1)
345 flags, outer = self._regex_flags(outer)
346 # Avoid https://github.com/python/cpython/issues/74534
347 inner = re.compile(inner[1:].replace('[[', r'[\
['), flags=flags)
349 inner = json.loads(js_to_json(f'{inner}{expr[0]}
', strict=True))
351 return inner, should_return
352 expr = self._named_object(local_vars, inner) + outer
354 if expr.startswith('new
'):
356 if obj.startswith('Date('):
357 left, right = self._separate_at_paren(obj[4:])
358 expr = unified_timestamp(
359 self.interpret_expression(left, local_vars, allow_recursion), False)
361 raise self.Exception(f'Failed to parse date {left!r}
', expr)
362 expr = self._dump(int(expr * 1000), local_vars) + right
364 raise self.Exception(f'Unsupported
object {obj}
', expr)
366 if expr.startswith('void
'):
367 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
368 return None, should_return
370 if expr.startswith('{'):
371 inner, outer = self._separate_at_paren(expr)
372 # try for object expression (Map)
373 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
374 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
375 def dict_item(key, val):
376 val = self.interpret_expression(val, local_vars, allow_recursion)
377 if re.match(_NAME_RE, key):
379 return self.interpret_expression(key, local_vars, allow_recursion), val
381 return dict(dict_item(k, v) for k, v in sub_expressions), should_return
383 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
384 if not outer or should_abort:
385 return inner, should_abort or should_return
387 expr = self._dump(inner, local_vars) + outer
389 if expr.startswith('('):
390 inner, outer = self._separate_at_paren(expr)
391 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
392 if not outer or should_abort:
393 return inner, should_abort or should_return
395 expr = self._dump(inner, local_vars) + outer
397 if expr.startswith('['):
398 inner, outer = self._separate_at_paren(expr)
399 name = self._named_object(local_vars, [
400 self.interpret_expression(item, local_vars, allow_recursion)
401 for item in self._separate(inner)])
404 m = re.match(r'''(?x)
406 (?P<switch>switch)\s*\(|
409 md = m.groupdict() if m else {}
411 try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
414 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
417 except Exception as e:
418 # XXX: This works for now, but makes debugging future issues very hard
421 pending = (None, False)
422 m = re.match(r'catch\s
*(?P
<err
>\
(\s
*{_NAME_RE}\s
*\
))?\
{{'.format(**globals()), expr)
424 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
428 catch_vars[m.group('err
')] = err.error if isinstance(err, JS_Throw) else err
429 catch_vars = local_vars.new_child(catch_vars)
430 err, pending = None, self.interpret_statement(sub_expr, catch_vars, allow_recursion)
432 m = re.match(r'finally\s
*\
{', expr)
434 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
435 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
439 ret, should_abort = pending
447 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:])
448 if remaining.startswith('{'):
449 body, expr = self._separate_at_paren(remaining)
451 switch_m = re.match(r'switch\s
*\
(', remaining) # FIXME
453 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
454 body, expr = self._separate_at_paren(remaining, '}')
455 body = 'switch(%s){%s}
' % (switch_val, body)
457 body, expr = remaining, ''
458 start, cndn, increment = self._separate(constructor, ';')
459 self.interpret_expression(start, local_vars, allow_recursion)
461 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
464 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
471 self.interpret_expression(increment, local_vars, allow_recursion)
473 elif md.get('switch
'):
474 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
475 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
476 body, expr = self._separate_at_paren(remaining, '}')
477 items = body.replace('default
:', 'case default
:').split('case
')[1:]
478 for default in (False, True):
481 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
483 matched = matched or case == 'default
'
485 matched = (case != 'default
'
486 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
490 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
499 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
500 return ret, should_abort or should_return
502 # Comma separated statements
503 sub_expressions = list(self._separate(expr))
504 if len(sub_expressions) > 1:
505 for sub_expr in sub_expressions:
506 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
511 for m in re.finditer(rf'''(?x)
512 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
513 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr):
514 var = m.group('var1
') or m.group('var2
')
515 start, end = m.span()
516 sign = m.group('pre_sign
') or m.group('post_sign
')
517 ret = local_vars[var]
518 local_vars[var] += 1 if sign[0] == '+' else -1
519 if m.group('pre_sign
'):
520 ret = local_vars[var]
521 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
524 return None, should_return
526 m = re.match(fr'''(?x)
528 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
529 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
532 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
534 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
536 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
538 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
540 if m and m.group('assign
'):
541 left_val = local_vars.get(m.group('out
'))
543 if not m.group('index
'):
544 local_vars[m.group('out
')] = self._operator(
545 m.group('op
'), left_val, m.group('expr
'), expr, local_vars, allow_recursion)
546 return local_vars[m.group('out
')], should_return
547 elif left_val in (None, JS_Undefined):
548 raise self.Exception(f'Cannot index undefined variable {m.group("out")}
', expr)
550 idx = self.interpret_expression(m.group('index
'), local_vars, allow_recursion)
551 if not isinstance(idx, (int, float)):
552 raise self.Exception(f'List index {idx} must be integer
', expr)
554 left_val[idx] = self._operator(
555 m.group('op
'), self._index(left_val, idx), m.group('expr
'), expr, local_vars, allow_recursion)
556 return left_val[idx], should_return
559 return int(expr), should_return
561 elif expr == 'break':
563 elif expr == 'continue':
565 elif expr == 'undefined
':
566 return JS_Undefined, should_return
568 return float('NaN
'), should_return
570 elif m and m.group('return'):
571 return local_vars.get(m.group('name
'), JS_Undefined), should_return
573 with contextlib.suppress(ValueError):
574 return json.loads(js_to_json(expr, strict=True)), should_return
576 if m and m.group('indexing
'):
577 val = local_vars[m.group('in')]
578 idx = self.interpret_expression(m.group('idx
'), local_vars, allow_recursion)
579 return self._index(val, idx), should_return
581 for op in _OPERATORS:
582 separated = list(self._separate(expr, op))
583 right_expr = separated.pop()
585 if op in '?
<>*-' and len(separated) > 1 and not separated[-1].strip():
587 elif not (separated and op == '?
' and right_expr.startswith('.')):
589 right_expr = f'{op}{right_expr}
'
591 right_expr = f'{separated.pop()}{op}{right_expr}
'
594 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
595 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
597 if m and m.group('attribute
'):
598 variable, member, nullish = m.group('var
', 'member
', 'nullish
')
600 member = self.interpret_expression(m.group('member2
'), local_vars, allow_recursion)
601 arg_str = expr[m.end():]
602 if arg_str.startswith('('):
603 arg_str, remaining = self._separate_at_paren(arg_str)
605 arg_str, remaining = None, arg_str
607 def assertion(cndn, msg):
608 """ assert, but without risk of getting optimized out """
610 raise self.Exception(f'{member} {msg}
', expr)
613 if (variable, member) == ('console
', 'debug
'):
615 Debugger.write(self.interpret_expression(f'[{arg_str}
]', local_vars, allow_recursion))
622 obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
623 if obj is NO_DEFAULT:
624 if variable not in self._objects:
626 self._objects[variable] = self.extract_object(variable)
627 except self.Exception:
630 obj = self._objects.get(variable, JS_Undefined)
632 if nullish and obj is JS_Undefined:
637 return self._index(obj, member, nullish)
641 self.interpret_expression(v, local_vars, allow_recursion)
642 for v in self._separate(arg_str)]
645 if member == 'fromCharCode
':
646 assertion(argvals, 'takes one
or more arguments
')
647 return ''.join(map(chr, argvals))
648 raise self.Exception(f'Unsupported String method {member}
', expr)
651 assertion(len(argvals) == 2, 'takes two arguments
')
652 return argvals[0] ** argvals[1]
653 raise self.Exception(f'Unsupported Math method {member}
', expr)
655 if member == 'split
':
656 assertion(argvals, 'takes one
or more arguments
')
657 assertion(len(argvals) == 1, 'with limit argument
is not implemented
')
658 return obj.split(argvals[0]) if argvals[0] else list(obj)
659 elif member == 'join
':
660 assertion(isinstance(obj, list), 'must be applied on a
list')
661 assertion(len(argvals) == 1, 'takes exactly one argument
')
662 return argvals[0].join(obj)
663 elif member == 'reverse
':
664 assertion(not argvals, 'does
not take any arguments
')
667 elif member == 'slice':
668 assertion(isinstance(obj, list), 'must be applied on a
list')
669 assertion(len(argvals) == 1, 'takes exactly one argument
')
670 return obj[argvals[0]:]
671 elif member == 'splice
':
672 assertion(isinstance(obj, list), 'must be applied on a
list')
673 assertion(argvals, 'takes one
or more arguments
')
674 index, howMany = map(int, (argvals + [len(obj)])[:2])
677 add_items = argvals[2:]
679 for i in range(index, min(index + howMany, len(obj))):
680 res.append(obj.pop(index))
681 for i, item in enumerate(add_items):
682 obj.insert(index + i, item)
684 elif member == 'unshift
':
685 assertion(isinstance(obj, list), 'must be applied on a
list')
686 assertion(argvals, 'takes one
or more arguments
')
687 for item in reversed(argvals):
690 elif member == 'pop
':
691 assertion(isinstance(obj, list), 'must be applied on a
list')
692 assertion(not argvals, 'does
not take any arguments
')
696 elif member == 'push
':
697 assertion(argvals, 'takes one
or more arguments
')
700 elif member == 'forEach
':
701 assertion(argvals, 'takes one
or more arguments
')
702 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
703 f, this = (argvals + [''])[:2]
704 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
705 elif member == 'indexOf
':
706 assertion(argvals, 'takes one
or more arguments
')
707 assertion(len(argvals) <= 2, 'takes at
-most
2 arguments
')
708 idx, start = (argvals + [0])[:2]
710 return obj.index(idx, start)
713 elif member == 'charCodeAt
':
714 assertion(isinstance(obj, str), 'must be applied on a string
')
715 assertion(len(argvals) == 1, 'takes exactly one argument
')
716 idx = argvals[0] if isinstance(argvals[0], int) else 0
721 idx = int(member) if isinstance(obj, list) else member
722 return obj[idx](argvals, allow_recursion=allow_recursion)
725 ret, should_abort = self.interpret_statement(
726 self._named_object(local_vars, eval_method()) + remaining,
727 local_vars, allow_recursion)
728 return ret, should_return or should_abort
730 return eval_method(), should_return
732 elif m and m.group('function
'):
733 fname = m.group('fname
')
734 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
735 for v in self._separate(m.group('args
'))]
736 if fname in local_vars:
737 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
738 elif fname not in self._functions:
739 self._functions[fname] = self.extract_function(fname)
740 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
742 raise self.Exception(
743 f'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}
', stmt)
745 def interpret_expression(self, expr, local_vars, allow_recursion):
746 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
748 raise self.Exception('Cannot
return from an expression
', expr)
751 def extract_object(self, objname):
752 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a
-zA
-Z$
0-9]+')'''
756 (?<!this\.)%s\s*=\s*{\s*
757 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
759 ''' % (re.escape(objname), _FUNC_NAME_RE),
762 raise self.Exception(f'Could
not find
object {objname}
')
763 fields = obj_m.group('fields
')
764 # Currently, it only supports function definitions
765 fields_m = re.finditer(
767 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
768 ''' % (_FUNC_NAME_RE, _NAME_RE),
771 argnames = f.group('args
').split(',')
772 obj[remove_quotes(f.group('key
'))] = self.build_function(argnames, f.group('code
'))
776 def extract_function_code(self, funcname):
777 """ @returns argnames, code """
782 [{;,]\s*%(name)s\s*=\s*function|
783 (?:var|const|let)\s+%(name)s\s*=\s*function
785 \((?P<args>[^)]*)\)\s*
786 (?P<code>{.+})''' % {'name': re.escape(funcname)},
788 code, _ = self._separate_at_paren(func_m.group('code
'))
790 raise self.Exception(f'Could
not find JS function
"{funcname}"')
791 return [x.strip() for x in func_m.group('args
').split(',')], code
793 def extract_function(self, funcname):
794 return self.extract_function_from_code(*self.extract_function_code(funcname))
796 def extract_function_from_code(self, argnames, code, *global_stack):
799 mobj = re.search(r'function\
((?P
<args
>[^
)]*)\
)\s
*{', code)
802 start, body_start = mobj.span()
803 body, remaining = self._separate_at_paren(code[body_start - 1:])
804 name = self._named_object(local_vars, self.extract_function_from_code(
805 [x.strip() for x in mobj.group('args
').split(',')],
806 body, local_vars, *global_stack))
807 code = code[:start] + name + remaining
808 return self.build_function(argnames, code, local_vars, *global_stack)
810 def call_function(self, funcname, *args):
811 return self.extract_function(funcname)(args)
813 def build_function(self, argnames, code, *global_stack):
814 global_stack = list(global_stack) or [{}]
815 argnames = tuple(argnames)
817 def resf(args, kwargs={}, allow_recursion=100):
818 global_stack[0].update(itertools.zip_longest(argnames, args, fillvalue=None))
819 global_stack[0].update(kwargs)
820 var_stack = LocalNameSpace(*global_stack)
821 ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)