jy.js_parse#

Utils to parse JS

Functions

append_to_func_body(func_def_code, ...)

Append code to the body of a function definition

dflt_py_to_js_value_trans(x)

Python value -> JS literal text, via json.dumps (quotes and nesting are escaped).

extract_func_name_and_params(ast_node)

Extract one or several function (name, params) pair(s) from an AST node

extract_function_def_parts(func_def_code)

Extract the body of a function definition from its code

extract_js_func_params(params_list)

func_name_and_params_pairs(js_code, *[, ...])

Get (name, params) pairs of function definitions extracted from js_code.

if_none_output_raise_unknown_type([context])

parse_js(js_code[, encoding, ingress, egress])

Parse JavaScript source (or a path to a .js file) into an esprima AST.

parse_js_code(js_code[, encoding, ingress, ...])

Parse JavaScript source (or a path to a .js file) into an esprima AST.

replace_ids_in_code(code[, patterns])

Replaces IDs in a mixed HTML, CSS, and JS string with unique versions.

variable_declarations_pairs(src, *[, encoding])

Yield (name, value) pairs for the top-level variable declarations in JS.

Exceptions

UnknownNodeType(node_type[, context])

To be raised when an AST node type wasn't handled by a function

exception jy.js_parse.UnknownNodeType(node_type, context='')[source]#

Bases: ValueError

To be raised when an AST node type wasn’t handled by a function

jy.js_parse.append_to_func_body(func_def_code, code_to_append)[source]#

Append code to the body of a function definition

Return type:

str

jy.js_parse.dflt_py_to_js_value_trans(x)[source]#

Python value -> JS literal text, via json.dumps (quotes and nesting are escaped).

>>> dflt_py_to_js_value_trans(True), dflt_py_to_js_value_trans(None)
('true', 'null')
>>> dflt_py_to_js_value_trans('say "hi"\n')
'"say \\"hi\\"\\n"'
>>> dflt_py_to_js_value_trans([{"a": 1}, {"b": [2, "x"]}])
'[{"a": 1}, {"b": [2, "x"]}]'

Values json cannot encode are passed through unchanged (so a caller can supply a raw JS expression object whose str is the code).

jy.js_parse.extract_func_name_and_params(ast_node)[source]#

Extract one or several function (name, params) pair(s) from an AST node

jy.js_parse.extract_function_def_parts(func_def_code)[source]#

Extract the body of a function definition from its code

Return type:

str

jy.js_parse.func_name_and_params_pairs(js_code, *, encoding=None)[source]#

Get (name, params) pairs of function definitions extracted from js_code.

>>> js_code = '''
... function foo(a, b="hello", c= 3) {
...     return a + b.length * c
... }
... const bar = (y, z = 1) => y * z
... func.assigned.to.nested.prop = function (x) {
...     return x + 3
... }'''
>>> assert list(func_name_and_params_pairs(js_code)) == [
...     ('foo', [
...         {'name': 'a'},
...         {'name': 'b', 'default': 'hello'},
...         {'name': 'c', 'default': 3}
...     ]),
...     ('bar', [
...         {'name': 'y'},
...         {'name': 'z', 'default': 1}
...     ]),
...     ('func.assigned.to.nested.prop', [
...         {'name': 'x'}
...     ])
... ]
jy.js_parse.parse_js(js_code, encoding=None, *, ingress=<function <lambda>>, egress=<function <lambda>>)[source]#

Parse JavaScript source (or a path to a .js file) into an esprima AST.

js_code may be a string of JS or a filesystem path, in which case the file is read (honoring encoding). ingress preprocesses the source before parsing; egress post-processes the resulting AST.

>>> tree = parse_js("const x = 42;")
>>> tree.body[0].type
'VariableDeclaration'
>>> tree.body[0].declarations[0].id.name
'x'
Return type:

Script

jy.js_parse.parse_js_code(js_code, encoding=None, *, ingress=<function <lambda>>, egress=<function <lambda>>)#

Parse JavaScript source (or a path to a .js file) into an esprima AST.

js_code may be a string of JS or a filesystem path, in which case the file is read (honoring encoding). ingress preprocesses the source before parsing; egress post-processes the resulting AST.

>>> tree = parse_js("const x = 42;")
>>> tree.body[0].type
'VariableDeclaration'
>>> tree.body[0].declarations[0].id.name
'x'
Return type:

Script

jy.js_parse.replace_ids_in_code(code, patterns=('id="([^"]+)"', '#([a-zA-Z][\\w\\-]*)', 'document\\.getElementById\\("([^"]+)"\\)'))[source]#

Replaces IDs in a mixed HTML, CSS, and JS string with unique versions.

Args

  • code (str): The input code containing HTML, CSS, and/or JS.

  • patterns (tuple): A tuple of regex patterns to match IDs.

Returns

  • tuple: A tuple containing the modified code and a dictionary of old-to-new ID mappings.

This function is useful to make id-unique copies of HTML/JS components that have IDs. This need was noticed and discussed in: i2mint/jy#3

Return type:

tuple[str, dict]

jy.js_parse.variable_declarations_pairs(src, *, encoding=None)[source]#

Yield (name, value) pairs for the top-level variable declarations in JS.

Literal, object, array and unary-minus initializers are evaluated to their Python equivalents; other initializer kinds yield None. A leading export on a declaration is stripped first, so ES-module sources parse.

>>> list(variable_declarations_pairs("const a = 3; let b = 'hi';"))
[('a', 3), ('b', 'hi')]
>>> list(variable_declarations_pairs("export const config = {x: 1, y: [2, 3]};"))
[('config', {'x': 1, 'y': [2, 3]})]
>>> list(variable_declarations_pairs("var n = -5; const flag = true;"))
[('n', -5), ('flag', True)]