comparison libervia/web/server/tasks/implicit/task_js_modules.py @ 1518:eb00d593801d

refactoring: rename `libervia` to `libervia.web` + update imports following backend changes
author Goffi <goffi@goffi.org>
date Fri, 02 Jun 2023 16:49:28 +0200
parents libervia/server/tasks/implicit/task_js_modules.py@106bae41f5c8
children 038d4bfdd967
comparison
equal deleted inserted replaced
1517:b8ed9726525b 1518:eb00d593801d
1 #!/ur/bin/env python3
2
3 import json
4 from pathlib import Path
5 from libervia.backend.core.i18n import _
6 from libervia.backend.core.log import getLogger
7 from libervia.backend.core import exceptions
8 from libervia.web.server.constants import Const as C
9 from libervia.web.server.tasks import task
10
11
12 log = getLogger(__name__)
13
14
15 class Task(task.Task):
16
17 async def prepare(self):
18 if "js" not in self.resource.browser_modules:
19 raise exceptions.CancelError("No JS module needed")
20
21 async def start(self):
22 js_data = self.resource.browser_modules['js']
23 package = js_data.get('package', {})
24 package_path = self.build_path / 'package.json'
25 with package_path.open('w') as f:
26 json.dump(package, f)
27
28 cmd = self.find_command('yarnpkg', 'yarn')
29 await self.runCommand(cmd, 'install', path=str(self.build_path))
30
31 try:
32 brython_map = js_data['brython_map']
33 except KeyError:
34 pass
35 else:
36 log.info(_("creating JS modules mapping for Brython"))
37 js_modules_path = self.build_path / 'js_modules'
38 js_modules_path.mkdir(exist_ok=True)
39 init_path = js_modules_path / '__init__.py'
40 init_path.touch()
41
42 for module_name, module_data in brython_map.items():
43 log.debug(f"generating mapping for {module_name}")
44 if ' ' in module_name:
45 raise ValueError(
46 f"module {module_name!r} has space(s), it must not!")
47 module_path = js_modules_path / f"{module_name}.py"
48 if isinstance(module_data, str):
49 module_data = {'path': module_data}
50 try:
51 js_path = module_data.pop('path')
52 except KeyError:
53 raise ValueError(
54 f'module data for {module_name} must have a "path" key')
55 module_data['path'] = Path('node_modules') / js_path.strip(' /')
56 export = module_data.get('export') or [module_name]
57 export_objects = '\n'.join(f'{e} = window.{e}' for e in export)
58 extra_kwargs = {"build_dir": C.BUILD_DIR}
59
60 with module_path.open('w') as f:
61 f.write(f"""\
62 #!/usr/bin/env python3
63 from browser import window, load
64 {module_data.get('extra_import', '')}
65
66 load("{Path('/').joinpath(C.BUILD_DIR, module_data['path'])}")
67 {export_objects}
68 {module_data.get('extra_init', '').format(**extra_kwargs)}
69 """)