echidnae-javascript 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,300 @@
1
+ """Deterministic ES modules for the validated python-browser/1 source profile."""
2
+
3
+ from dataclasses import dataclass
4
+ import hashlib
5
+ from importlib.metadata import version
6
+ import json
7
+ import re
8
+ import unicodedata
9
+
10
+ from .compiler import parse_source
11
+ from ._compiler_runtime import HELPER_BINDINGS, helper_closure, helper_source
12
+
13
+
14
+ def _json(value):
15
+ return json.dumps(value, ensure_ascii=True, separators=(',', ':'))
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class OutputFile:
20
+ path: str
21
+ data: bytes
22
+ role: str
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class CompiledArtifact:
27
+ files: tuple[OutputFile, ...]
28
+ manifest_bytes: bytes
29
+
30
+ @property
31
+ def manifest(self):
32
+ """Return a fresh snapshot; callers cannot mutate artifact metadata."""
33
+ return json.loads(self.manifest_bytes)
34
+
35
+
36
+ def _vlq(value):
37
+ alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
38
+ value = (-value << 1 | 1) if value < 0 else value << 1
39
+ encoded = ''
40
+ while True:
41
+ digit = value & 31
42
+ value >>= 5
43
+ encoded += alphabet[digit | (32 if value else 0)]
44
+ if not value:
45
+ return encoded
46
+
47
+
48
+ def _contains_await(node):
49
+ if not hasattr(node, 'fields'):
50
+ return any(_contains_await(item) for item in node) if isinstance(node, tuple) else False
51
+ return node.kind == 'await' or any(_contains_await(value) for _, value in node.fields)
52
+
53
+
54
+ class _Emitter:
55
+ def __init__(self, module):
56
+ self.module = module
57
+ self.bindings = {binding.id: binding for binding in module.bindings}
58
+ self.names = {binding.id: '$v' + str(index) for index, binding in enumerate(module.bindings)}
59
+ self.required = set()
60
+ self.lines = []
61
+ self.counter = 0
62
+
63
+ def use(self, helper):
64
+ self.required.add(helper)
65
+
66
+ def temporary(self):
67
+ self.counter += 1
68
+ return '$t' + str(self.counter)
69
+
70
+ def location(self, node):
71
+ return _json(vars(node.span))
72
+
73
+ def add(self, text, indent=1, node=None):
74
+ self.lines.append((' ' * indent + text, node.span if node else None))
75
+
76
+ def expression(self, node):
77
+ fields, location = dict(node.fields), self.location(node)
78
+ kind = node.kind
79
+ if kind == 'constant':
80
+ if node.value_type == 'python-int':
81
+ return fields['value'] + 'n'
82
+ if node.value_type == 'python-str':
83
+ self.use('str')
84
+ return '$str(' + _json([ord(character) for character in fields['value']]) + ')'
85
+ return _json(fields['value'])
86
+ if kind == 'tuple':
87
+ self.use('tuple')
88
+ return '$tuple([' + ','.join(map(self.expression, fields['values'])) + '])'
89
+ if kind == 'name':
90
+ binding = self.bindings[fields['binding']]
91
+ if binding.kind == 'builtin':
92
+ name = binding.name
93
+ if name in {'str', 'int', 'bool', 'tuple'}:
94
+ self.use('types')
95
+ return '$types.' + name
96
+ helper, value = {'len': ('len', '$len'), 'print': ('print', '$print'),
97
+ 'isinstance': ('types', '$isinstance'), 'TypeError': ('exception', '$TypeError')}[name]
98
+ self.use(helper)
99
+ return value
100
+ self.use('binding')
101
+ return f'$get({self.names[binding.id]},{_json(binding.name)},{str(binding.kind in {"local", "parameter"}).lower()},{location})'
102
+ if kind == 'await':
103
+ self.use('async')
104
+ return f'(await $await({self.expression(fields["value"])},{location}))'
105
+ if kind == 'async-attribute':
106
+ self.use('async')
107
+ return f'$asyncAttribute({self.expression(fields["value"])},{_json(fields["name"])},{location})'
108
+ if kind == 'attribute':
109
+ self.use('javascript')
110
+ return f'$attribute({self.expression(fields["value"])},{_json(fields["name"])},{location})'
111
+ if kind == 'call':
112
+ self.use('call')
113
+ return f'$call({self.expression(fields["function"])},[{",".join(map(self.expression, fields["arguments"]))}],{location})'
114
+ if kind in {'binary', 'unary', 'index'}:
115
+ self.use(kind)
116
+ if kind == 'binary':
117
+ values = [_json(fields['operator']), self.expression(fields['left']), self.expression(fields['right'])]
118
+ elif kind == 'unary':
119
+ values = [_json(fields['operator']), self.expression(fields['value'])]
120
+ else:
121
+ values = [self.expression(fields['value']), self.expression(fields['index'])]
122
+ return '$' + kind + '(' + ','.join([*values, location]) + ')'
123
+ if kind == 'boolean':
124
+ self.use('truth')
125
+ name = self.temporary()
126
+ values = fields['values']
127
+ pieces = [f'let {name}={self.expression(values[0])};']
128
+ for value in values[1:]:
129
+ condition = f'$truth({name},{location})'
130
+ if fields['operator'] == 'and':
131
+ condition = '!' + condition
132
+ pieces.extend([f'if({condition})return {name};', f'{name}={self.expression(value)};'])
133
+ code = '(()=>{' + ''.join(pieces) + f'return {name};' + '})()'
134
+ return '(await ' + code.replace('(()=>', '(async()=>', 1) + ')' if _contains_await(node) else code
135
+ if kind == 'compare':
136
+ self.use('compare')
137
+ left, right = self.temporary(), self.temporary()
138
+ pieces = [f'let {left}={self.expression(fields["values"][0])};let {right};']
139
+ for operator, value in zip(fields['operators'], fields['values'][1:]):
140
+ pieces.extend([f'{right}={self.expression(value)};',
141
+ f'if(!$compare({_json(operator)},{left},{right},{location}))return false;', f'{left}={right};'])
142
+ code = '(()=>{' + ''.join(pieces) + 'return true;})()'
143
+ return '(await ' + code.replace('(()=>', '(async()=>', 1) + ')' if _contains_await(node) else code
144
+ raise AssertionError('Unrecognized validated expression: ' + kind)
145
+
146
+ def statements(self, nodes, indent=1):
147
+ for node in nodes:
148
+ if 'async/' in self.module.profile:
149
+ self.use('async')
150
+ self.add(f'$checkpoint({self.location(node)});', indent, node)
151
+ self.statement(node, indent)
152
+
153
+ def statement(self, node, indent):
154
+ fields, kind = dict(node.fields), node.kind
155
+ if kind == 'source-import':
156
+ temporary = self.temporary()
157
+ self.add(f'const {temporary}=importModule({_json(fields["module"])});', indent, node)
158
+ for identifier, exported in fields['bindings']:
159
+ self.add(f'{self.names[identifier]}={temporary}[{_json(exported)}];', indent, node)
160
+ elif kind == 'import':
161
+ self.use('javascript')
162
+ for identifier in fields['bindings']:
163
+ target = self.bindings[identifier].target
164
+ if target == 'echidnae.javascript.Promise':
165
+ self.use('async')
166
+ if target.startswith('echidnae.javascript.browser.'):
167
+ self.use('browser')
168
+ value = '$browser[' + _json(target.rsplit('.', 1)[1]) + ']'
169
+ else:
170
+ value = {'echidnae': '$Echidnae', 'echidnae.javascript': '$JS',
171
+ 'echidnae.javascript.Array': '$JArray', 'echidnae.javascript.Promise': '$PromiseRegistry'}[target]
172
+ self.add(f'{self.names[identifier]}={value};', indent, node)
173
+ elif kind == 'function':
174
+ self.use('call')
175
+ binding = self.bindings[fields['binding']]
176
+ defaults = '[' + ','.join(map(self.expression, fields['defaults'])) + ']'
177
+ asynchronous = fields.get('asynchronous', False)
178
+ if asynchronous:
179
+ self.use('async')
180
+ factory, modifier = ('$cfn', 'async ') if asynchronous else ('$fn', '')
181
+ self.add(f'{self.names[binding.id]}={factory}({_json(binding.name)},{len(fields["parameters"])},{defaults},{modifier}($args)=>{{', indent, node)
182
+ locals_ = [item for item in self.module.bindings if item.scope == 'function:' + binding.name]
183
+ if locals_:
184
+ self.use('binding')
185
+ self.add('let ' + ','.join(self.names[item.id] + '=$UNBOUND' for item in locals_) + ';', indent + 1)
186
+ for index, parameter in enumerate(fields['parameters']):
187
+ self.add(f'{self.names[parameter]}=$args[{index}];', indent + 1)
188
+ self.statements(fields['body'], indent + 1)
189
+ self.add('return null;', indent + 1)
190
+ self.add('});', indent)
191
+ elif kind == 'assign':
192
+ temporary = self.temporary()
193
+ self.add(f'const {temporary}={self.expression(fields["value"])};', indent, node)
194
+ for target in fields['targets']:
195
+ self.add(f'{self.names[target]}={temporary};', indent, node)
196
+ elif kind in {'expression', 'return', 'raise'}:
197
+ value = self.expression(fields['value']) if fields['value'] else 'null'
198
+ if kind == 'raise':
199
+ self.use('error')
200
+ self.add(f'$raise({value},{self.location(node)});', indent, node)
201
+ else:
202
+ prefix = 'return ' if kind == 'return' else ''
203
+ self.add(prefix + value + ';', indent, node)
204
+ elif kind == 'if':
205
+ self.use('truth')
206
+ self.add(f'if($truth({self.expression(fields["test"])},{self.location(node)})){{', indent, node)
207
+ self.statements(fields['body'], indent + 1)
208
+ if fields['otherwise']:
209
+ self.add('}else{', indent)
210
+ self.statements(fields['otherwise'], indent + 1)
211
+ self.add('}', indent)
212
+ elif kind == 'for':
213
+ self.use('iterate')
214
+ temporary = self.temporary()
215
+ self.add(f'for(const {temporary} of $iterate({self.expression(fields["value"])},{self.location(node)})){{', indent, node)
216
+ self.add(f'{self.names[fields["target"]]}={temporary};', indent + 1)
217
+ self.statements(fields['body'], indent + 1)
218
+ self.add('}', indent)
219
+ elif kind in {'break', 'continue'}:
220
+ self.add(kind + ';', indent, node)
221
+ elif kind == 'pass':
222
+ self.add(';', indent, node)
223
+ else:
224
+ raise AssertionError('Unrecognized validated statement: ' + kind)
225
+
226
+ def render(self, source, module_name, source_map, *, shared_runtime=False):
227
+ roots = [binding for binding in self.module.bindings if binding.scope == 'module']
228
+ if roots:
229
+ self.use('binding')
230
+ self.add('let ' + ','.join(self.names[binding.id] + '=$UNBOUND' for binding in roots) + ';')
231
+ self.statements(self.module.body)
232
+ exports = [binding for binding in roots if binding.kind != 'javascript']
233
+ items = []
234
+ for binding in exports:
235
+ value = self.names[binding.id]
236
+ if binding.kind == 'function' and not shared_runtime:
237
+ self.use('async-expose' if 'async/' in self.module.profile else 'input')
238
+ definition = next(node for node in self.module.body if node.kind == 'function' and node.field('binding') == binding.id)
239
+ expose = '$asyncExpose' if 'async/' in self.module.profile else '$expose'
240
+ value = f'{expose}({value},{self.location(definition)})'
241
+ items.append(f'[{_json(binding.name)}]:{value}')
242
+ self.add('return Object.freeze({' + ','.join(items) + '});')
243
+ helpers = helper_closure(self.required)
244
+ if shared_runtime:
245
+ names = [name for helper in helpers for name in HELPER_BINDINGS[helper]]
246
+ lines = [('export function initialize(runtime, importModule) {', None)]
247
+ if names:
248
+ lines.append((' const {' + ','.join(names) + '}=runtime;', None))
249
+ else:
250
+ option = ', signal = null' if 'async/' in self.module.profile else ''
251
+ lines = [('export function createModule({write = text => console.log(text.slice(0,-1))' + option + '} = {}) {', None),
252
+ (" if(typeof write !== 'function')throw new TypeError('write must be a function');", None)]
253
+ for helper in helpers:
254
+ lines.extend((' ' + line, None) for line in helper_source(helper).splitlines())
255
+ lines.extend(self.lines)
256
+ lines.append(('}', None))
257
+ mappings, previous_line, previous_column = [], 0, 0
258
+ for text, span in lines:
259
+ if span:
260
+ column = len(text) - len(text.lstrip())
261
+ mappings.append(''.join(_vlq(value) for value in [column, 0, span.line - 1 - previous_line, span.column - 1 - previous_column]))
262
+ previous_line, previous_column = span.line - 1, span.column - 1
263
+ else:
264
+ mappings.append('')
265
+ code = '\n'.join(text for text, _ in lines) + '\n'
266
+ output = [OutputFile(module_name, code.encode('utf-8'), 'executable-module')]
267
+ if source_map:
268
+ code += '//# sourceMappingURL=' + module_name + '.map\n'
269
+ output[0] = OutputFile(module_name, code.encode('utf-8'), 'executable-module')
270
+ data = {'version': 3, 'file': module_name, 'sources': [self.module.filename],
271
+ 'sourcesContent': [source], 'names': [], 'mappings': ';'.join(mappings)}
272
+ output.append(OutputFile(module_name + '.map', (_json(data) + '\n').encode('utf-8'), 'source-map'))
273
+ return output, helpers, [binding.name for binding in exports]
274
+
275
+
276
+ def compile_source(source: str, *, filename: str = 'app.py', module_name: str = 'app.mjs',
277
+ source_map: bool = True, async_enabled: bool = False) -> CompiledArtifact:
278
+ """Compile one approved module to immutable artifacts; do not execute or publish it."""
279
+ if not isinstance(module_name, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]*\.mjs', module_name):
280
+ raise ValueError('module_name must be a portable .mjs basename')
281
+ if type(source_map) is not bool:
282
+ raise TypeError('source_map must be bool')
283
+ module = parse_source(source, filename=filename, async_enabled=async_enabled)
284
+ output, helpers, exports = _Emitter(module).render(source, module_name, source_map)
285
+ compiler_version = version('echidnae-javascript')
286
+ notice = ('Generated by echidnae-javascript ' + compiler_version + '\n'
287
+ 'https://github.com/wispsy/echidnae\n'
288
+ 'Original compiler helper implementation; no third-party runtime is embedded.\n'
289
+ 'This provenance notice grants no additional license rights.\n')
290
+ output.append(OutputFile('NOTICES.txt', notice.encode('utf-8'), 'notice'))
291
+ files = tuple(sorted(output, key=lambda item: item.path))
292
+ manifest = {'kind': 'python-javascript-compiled', 'schema_version': 1,
293
+ 'compiler': {'name': 'echidnae-javascript', 'version': compiler_version, 'abi': 'python-browser-async-esm/1' if async_enabled else 'python-browser-esm/1'},
294
+ 'language_profile': module.profile, 'target': 'ecmascript-2022-module',
295
+ 'unicode_version': unicodedata.unidata_version, 'entrypoint': module_name,
296
+ 'entrypoint_export': 'createModule', 'application_exports': exports,
297
+ 'sources': [{'path': filename, 'sha256': module.source_sha256, 'size': len(source.encode('utf-8'))}],
298
+ 'files': [{'path': item.path, 'size': len(item.data), 'sha256': hashlib.sha256(item.data).hexdigest(), 'role': item.role} for item in files],
299
+ 'imports': [], 'helpers': list(helpers), 'notices': ['NOTICES.txt']}
300
+ return CompiledArtifact(files, (_json(manifest) + '\n').encode('utf-8'))
@@ -0,0 +1,273 @@
1
+ """Compile a closed, verified set of ordinary source modules to local ES modules."""
2
+
3
+ import ast
4
+ from dataclasses import dataclass
5
+ import hashlib
6
+ from importlib.metadata import version
7
+ import keyword
8
+ from pathlib import PurePosixPath
9
+ import re
10
+ import sys
11
+ import unicodedata
12
+
13
+ from .compiler import (CompileError, Diagnostic, ModuleIR, SourceImport, SourceSpan,
14
+ _FrontEnd, _immutable, _literal_type)
15
+ from .emitter import CompiledArtifact, OutputFile, _Emitter, _json
16
+ from ._compiler_runtime import HELPER_BINDINGS, helper_closure, helper_source
17
+
18
+
19
+ def _portable(path):
20
+ relative = PurePosixPath(path)
21
+ reserved = {'CON', 'PRN', 'AUX', 'NUL', *(f'COM{i}' for i in range(1, 10)), *(f'LPT{i}' for i in range(1, 10))}
22
+ return (bool(relative.parts) and not relative.is_absolute() and '..' not in relative.parts and str(relative) == path
23
+ and all(part.split('.')[0].upper() not in reserved and not part.endswith(('.', ' '))
24
+ and not any(ord(character) < 32 or character in '\\:*?"<>|' for character in part)
25
+ for part in relative.parts))
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class SourceModule:
30
+ name: str
31
+ data: bytes
32
+ sha256: str
33
+ is_package: bool = False
34
+ filename: str | None = None
35
+
36
+ def __post_init__(self):
37
+ if (not isinstance(self.name, str) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*', self.name)
38
+ or any(keyword.iskeyword(part) for part in self.name.split('.'))
39
+ or self.name == '__main__' or self.name.split('.')[0] in {*sys.stdlib_module_names, 'echidnae'}):
40
+ raise ValueError('Use an ordinary source module name without stdlib/registry shadowing.')
41
+ if type(self.data) is not bytes or len(self.data) > 1_048_576:
42
+ raise ValueError('Source requires immutable UTF-8 bytes, at most 1 MiB per module.')
43
+ self.data.decode('utf-8')
44
+ if hashlib.sha256(self.data).hexdigest() != self.sha256:
45
+ raise ValueError('Source SHA-256 does not match its supplied bytes.')
46
+ if type(self.is_package) is not bool:
47
+ raise TypeError('is_package must be bool')
48
+ filename = self.filename
49
+ if filename is None:
50
+ filename = self.name.replace('.', '/') + ('/__init__.py' if self.is_package else '.py')
51
+ if not isinstance(filename, str) or not _portable(filename) or not filename.endswith('.py'):
52
+ raise ValueError('filename must be a portable relative logical .py path')
53
+ filename.encode('utf-8')
54
+ object.__setattr__(self, 'filename', filename)
55
+
56
+ @classmethod
57
+ def from_text(cls, name, text, *, is_package=False, filename=None):
58
+ data = text.encode('utf-8')
59
+ return cls(name, data, hashlib.sha256(data).hexdigest(), is_package, filename)
60
+
61
+
62
+ class _Modules:
63
+ def __init__(self, sources, entrypoint, async_enabled, browser_enabled):
64
+ self.browser_enabled = browser_enabled
65
+ self.async_enabled = async_enabled
66
+ if not isinstance(sources, tuple) or any(not isinstance(source, SourceModule) for source in sources):
67
+ raise TypeError('sources must be a tuple of verified SourceModule records')
68
+ if not 1 <= len(sources) <= 32 or sum(len(source.data) for source in sources) > 8_388_608:
69
+ raise ValueError('Declare 1–32 source modules, at most 8 MiB total.')
70
+ if len({source.name.casefold() for source in sources}) != len(sources):
71
+ raise ValueError('Source module identities must be unique and portable.')
72
+ if len({source.filename.casefold() for source in sources}) != len(sources):
73
+ raise ValueError('Logical source filenames must be unique and portable.')
74
+ # Recheck snapshots at the compiler boundary, including constructed records.
75
+ for source in sources:
76
+ source.__post_init__()
77
+ self.sources = {source.name: source for source in sources}
78
+ if entrypoint not in self.sources:
79
+ raise ValueError('entrypoint must name a declared source module')
80
+ self.entrypoint = entrypoint
81
+ self.trees, self.imports, self.dependencies, self.declarations = {}, {}, {}, {}
82
+ pending = [entrypoint]
83
+ while pending:
84
+ name = pending.pop()
85
+ if name in self.trees:
86
+ continue
87
+ source = self.sources[name]
88
+ try:
89
+ tree = ast.parse(source.data.decode('utf-8'), filename=source.filename)
90
+ except SyntaxError as error:
91
+ span = SourceSpan(source.filename, error.lineno or 1, error.offset or 1,
92
+ error.end_lineno or error.lineno or 1, error.end_offset or error.offset or 1)
93
+ raise CompileError(Diagnostic('PJS100', error.msg, span, 'parse')) from None
94
+ self.trees[name] = tree
95
+ self.imports[name], self.dependencies[name], self.declarations[name] = [], set(), {}
96
+ for index in range(1, len(name.split('.'))):
97
+ parent = '.'.join(name.split('.')[:index])
98
+ if parent not in self.sources or not self.sources[parent].is_package:
99
+ self.fail(name, 'Every parent requires an explicitly supplied package initializer.')
100
+ pending.append(parent)
101
+ for node in ast.walk(tree):
102
+ if not isinstance(node, (ast.Import, ast.ImportFrom)):
103
+ continue
104
+ if node not in tree.body:
105
+ self.fail(name, 'Source imports require unconditional module bindings.', node, 'PJS100')
106
+ registry = isinstance(node, ast.Import) and all(alias.name == 'echidnae.javascript' for alias in node.names)
107
+ registry = registry or isinstance(node, ast.ImportFrom) and not node.level and node.module == 'echidnae.javascript'
108
+ registry = registry or (self.browser_enabled and isinstance(node, ast.ImportFrom) and not node.level and node.module == 'echidnae.javascript.browser')
109
+ if registry:
110
+ continue
111
+ if isinstance(node, ast.Import):
112
+ self.fail(name, 'Local modules require explicit named from-imports.', node)
113
+ base = self.absolute(name, node)
114
+ if base not in self.sources or any(alias.name == '*' for alias in node.names):
115
+ self.fail(name, 'Import requires a declared source module and explicit exported names.', node)
116
+ self.imports[name].append((node, base))
117
+ self.dependencies[name].add(base)
118
+ pending.append(base)
119
+ for node in tree.body:
120
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
121
+ self.declarations[name][node.name] = ('function', node)
122
+ elif isinstance(node, ast.Assign):
123
+ if len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):
124
+ self.declarations[name][node.targets[0].id] = ('constant', node)
125
+ for node, base in self.imports[name]:
126
+ for alias in node.names:
127
+ self.declarations[name][alias.asname or alias.name] = ('import', (node, base, alias.name))
128
+ visiting, visited = set(), set()
129
+ def visit(name):
130
+ if name in visiting:
131
+ self.fail(name, 'Explicit source-import cycles are outside this module profile.')
132
+ if name in visited:
133
+ return
134
+ visiting.add(name)
135
+ for dependency in sorted(self.dependencies[name]):
136
+ visit(dependency)
137
+ visiting.remove(name)
138
+ visited.add(name)
139
+ for name in sorted(self.trees):
140
+ visit(name)
141
+
142
+ def fail(self, name, message, node=None, code='PJS110'):
143
+ source = self.sources[name]
144
+ span = SourceSpan(source.filename, 1, 1, 1, 1)
145
+ if node is not None:
146
+ lines = source.data.decode('utf-8').splitlines()
147
+ def column(line, offset):
148
+ return len(lines[line - 1].encode('utf-8')[:offset].decode('utf-8')) + 1
149
+ span = SourceSpan(source.filename, node.lineno, column(node.lineno, node.col_offset),
150
+ node.end_lineno, column(node.end_lineno, node.end_col_offset))
151
+ raise CompileError(Diagnostic(code, message, span, 'bind' if code == 'PJS110' else 'validate'))
152
+
153
+ def absolute(self, name, node):
154
+ if not node.level:
155
+ return node.module
156
+ package = name if self.sources[name].is_package else name.rpartition('.')[0]
157
+ parts = package.split('.') if package else []
158
+ if node.level > len(parts):
159
+ self.fail(name, 'Relative import escapes its declared package.', node)
160
+ return '.'.join([*parts[:len(parts) - node.level + 1], *([node.module] if node.module else [])])
161
+
162
+ def export_type(self, name, exported, requester, node):
163
+ declaration = self.declarations[name].get(exported)
164
+ if declaration is None:
165
+ self.fail(requester, 'Export is outside the declared Python namespace: ' + name + ':' + exported, node)
166
+ kind, value = declaration
167
+ if kind == 'function':
168
+ return 'async-callable' if isinstance(value, ast.AsyncFunctionDef) else 'callable'
169
+ if kind == 'constant':
170
+ if not _immutable(value.value):
171
+ self.fail(name, 'Module bindings require immutable literals.', value, 'PJS100')
172
+ result = _literal_type(ast.literal_eval(value.value))
173
+ if result is None:
174
+ self.fail(name, 'Literal type is outside this profile.', value, 'PJS100')
175
+ return result
176
+ original, base, target = value
177
+ return self.export_type(base, target, name, original)
178
+
179
+ def lower(self, name):
180
+ source = self.sources[name]
181
+ imports = {(node.lineno, node.col_offset): tuple(
182
+ SourceImport(alias.asname or alias.name, base, alias.name,
183
+ self.export_type(base, alias.name, name, node)) for alias in node.names)
184
+ for node, base in self.imports[name]}
185
+ frontend = _FrontEnd(source.data.decode('utf-8'), source.filename, imports, async_enabled=self.async_enabled, browser_enabled=self.browser_enabled)
186
+ body = frontend.statements(frontend.tree.body)
187
+ return ModuleIR(source.filename, source.sha256,
188
+ tuple(frontend.bindings[key] for key in sorted(frontend.bindings)), body,
189
+ profile='python-browser-modules-host-async/1' if self.browser_enabled else 'python-browser-modules-async/1' if self.async_enabled else 'python-browser-modules/1')
190
+
191
+
192
+ def compile_modules(sources: tuple[SourceModule, ...], *, entrypoint: str,
193
+ source_map: bool = True, async_enabled: bool = False, browser_enabled: bool = False, notices: tuple[OutputFile, ...] = ()) -> CompiledArtifact:
194
+ """Compile a verified source allowlist, never reading or executing target files."""
195
+ if type(source_map) is not bool:
196
+ raise TypeError('source_map must be bool')
197
+ if type(async_enabled) is not bool:
198
+ raise TypeError('async_enabled must be bool')
199
+ if type(browser_enabled) is not bool or (browser_enabled and not async_enabled):
200
+ raise ValueError('browser_enabled requires the explicit async profile')
201
+ graph = _Modules(sources, entrypoint, async_enabled, browser_enabled)
202
+ output, required, module_records = [], {'async-expose' if async_enabled else 'input'}, []
203
+ if browser_enabled:
204
+ required.add('browser')
205
+ modules = sorted(graph.trees)
206
+ for index, name in enumerate(modules):
207
+ source = graph.sources[name]
208
+ filename = f'module-{index:03}.mjs'
209
+ files, helpers, exports = _Emitter(graph.lower(name)).render(
210
+ source.data.decode('utf-8'), filename, source_map, shared_runtime=True)
211
+ output.extend(files)
212
+ required.update(helpers)
213
+ module_records.append({'module': name, 'file': filename, 'is_package': source.is_package,
214
+ 'exports': exports, 'source': source.filename, 'sha256': source.sha256})
215
+ helpers = helper_closure(required)
216
+ bindings = [binding for helper in helpers for binding in HELPER_BINDINGS[helper]]
217
+ runtime = ["export function createRuntime(write" + (", signal = null" if async_enabled else "") + (", host = null" if browser_enabled else "") + ") {", " if(typeof write!=='function')throw new TypeError('write must be a function');"]
218
+ for helper in helpers:
219
+ runtime.extend(' ' + line for line in helper_source(helper).splitlines())
220
+ runtime.extend([' return Object.freeze({' + ','.join(bindings) + '});', '}'])
221
+ output.append(OutputFile('runtime.mjs', ('\n'.join(runtime) + '\n').encode(), 'compatibility-helper'))
222
+ imports = ["import {createRuntime} from './runtime.mjs';"]
223
+ imports.extend(f"import {{initialize as module{index}}} from './{record['file']}';" for index, record in enumerate(module_records))
224
+ registry = '[' + ','.join('[' + _json(record['module']) + ',module' + str(index) + ']' for index, record in enumerate(module_records)) + ']'
225
+ packages = _json([record['module'] for record in module_records if record['is_package']])
226
+ location = _json({'filename': graph.sources[entrypoint].filename, 'line': 1, 'column': 1, 'end_line': 1, 'end_column': 1})
227
+ expose = '$asyncExpose' if async_enabled else '$expose'
228
+ signal_option = (', signal = null' if async_enabled else '') + (', host = null' if browser_enabled else '')
229
+ signal_argument = (',signal' if async_enabled else '') + (',host' if browser_enabled else '')
230
+ entry = '\n'.join(imports) + '\n' + f'''
231
+ export function createModule({{write = text => console.log(text.slice(0,-1)){signal_option}}} = {{}}) {{
232
+ const runtime=createRuntime(write{signal_argument}), factories=new Map({registry}), packages=new Set({packages}), cache=new Map(), loading=new Set();
233
+ function importModule(name) {{
234
+ if(cache.has(name))return cache.get(name);
235
+ const parent=name.includes('.')?name.slice(0,name.lastIndexOf('.')):null;
236
+ if(parent && packages.has(parent) && !loading.has(parent))importModule(parent);
237
+ if(cache.has(name))return cache.get(name);
238
+ if(loading.has(name))throw new Error('Source-import cycle is outside this profile.');
239
+ if(!factories.has(name))throw new Error('Undeclared compiled source module.');
240
+ loading.add(name);
241
+ const value=factories.get(name)(runtime,importModule);
242
+ loading.delete(name);cache.set(name,value);return value;
243
+ }}
244
+ const module=importModule({_json(entrypoint)});
245
+ return Object.freeze(Object.fromEntries(Object.entries(module).map(([name,value])=>[name,runtime.{expose}(value,{location})])));
246
+ }}
247
+ '''
248
+ output.append(OutputFile('app.mjs', entry.encode('utf-8'), 'executable-module'))
249
+ compiler_version = version('echidnae-javascript')
250
+ output.append(OutputFile('NOTICES.txt', ('Generated by echidnae-javascript ' + compiler_version +
251
+ '\nhttps://github.com/wispsy/echidnae\nOriginal compiler helpers; no third-party runtime is embedded.\nThis provenance notice grants no additional license rights.\n').encode(), 'notice'))
252
+ if not isinstance(notices, tuple) or any(not isinstance(item, OutputFile) or item.role != 'notice'
253
+ or not item.path.startswith('LICENSES/') or not _portable(item.path)
254
+ or type(item.data) is not bytes or not item.data.strip() for item in notices):
255
+ raise ValueError('notices must contain nonempty immutable notice files under LICENSES/.')
256
+ output.extend(notices)
257
+ if len({item.path.casefold() for item in output}) != len(output):
258
+ raise ValueError('Artifact paths must be unique and portable.')
259
+ if any(left.path.casefold().startswith(right.path.casefold() + '/') for left in output for right in output):
260
+ raise ValueError('Artifact file/directory paths collide.')
261
+ files = tuple(sorted(output, key=lambda item: item.path))
262
+ manifest = {'kind': 'python-javascript-compiled', 'schema_version': 1,
263
+ 'compiler': {'name': 'echidnae-javascript', 'version': compiler_version, 'abi': 'python-browser-host-esm/1' if browser_enabled else 'python-browser-modules-async-esm/1' if async_enabled else 'python-browser-modules-esm/1'},
264
+ 'language_profile': 'python-browser-modules-host-async/1' if browser_enabled else 'python-browser-modules-async/1' if async_enabled else 'python-browser-modules/1', 'target': 'ecmascript-2022-module',
265
+ 'unicode_version': unicodedata.unidata_version, 'entrypoint': 'app.mjs', 'entrypoint_export': 'createModule',
266
+ 'application_exports': next(record['exports'] for record in module_records if record['module'] == entrypoint),
267
+ 'modules': module_records, 'helpers': list(helpers),
268
+ 'sources': [{'path': graph.sources[name].filename, 'sha256': graph.sources[name].sha256, 'size': len(graph.sources[name].data)} for name in modules],
269
+ 'imports': [{'from': 'app.mjs', 'to': name} for name in ['runtime.mjs', *[record['file'] for record in module_records]]],
270
+ 'source_imports': [{'from': name, 'to': dependency} for name in modules for dependency in sorted(graph.dependencies[name])],
271
+ 'notices': sorted(item.path for item in files if item.role == 'notice'),
272
+ 'files': [{'path': item.path, 'size': len(item.data), 'sha256': hashlib.sha256(item.data).hexdigest(), 'role': item.role} for item in files]}
273
+ return CompiledArtifact(files, (_json(manifest) + '\n').encode('utf-8'))
File without changes