pyjs 0.0.1__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.
Files changed (146) hide show
  1. pyjs/__init__.py +6 -0
  2. pyjs/__main__.py +6 -0
  3. pyjs/cli.py +816 -0
  4. pyjs/decorators.py +170 -0
  5. pyjs/docs/__init__.py +6 -0
  6. pyjs/docs/builder.py +351 -0
  7. pyjs/docs/cli.py +55 -0
  8. pyjs/docs/config.py +45 -0
  9. pyjs/docs/favicon.svg +18 -0
  10. pyjs/docs/markdown.py +61 -0
  11. pyjs/docs/models.py +38 -0
  12. pyjs/docs/navigation.py +61 -0
  13. pyjs/docs/style.css +901 -0
  14. pyjs/docs/ui.py +349 -0
  15. pyjs/nativescript/__init__.py +77 -0
  16. pyjs/scaffolding/__init__.py +418 -0
  17. pyjs/scaffolding/templates/app/README.md.template +33 -0
  18. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__PYJS_PACKAGE__.py.template +81 -0
  19. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__init__.py.template +0 -0
  20. pyjs/scaffolding/templates/app/__PYJS_SOURCE_ROOT__/__PYJS_PACKAGE__/__main__.py.template +5 -0
  21. pyjs/scaffolding/templates/app/tests/test_app.py.template +22 -0
  22. pyjs/scaffolding/templates/app/tests/test_browser_app.py.template +19 -0
  23. pyjs/scaffolding/templates/app_test.py.template +8 -0
  24. pyjs/server.py +468 -0
  25. pyjs/skills/pyjs/SKILL.md +161 -0
  26. pyjs/state.py +101 -0
  27. pyjs/testing/__init__.py +3 -0
  28. pyjs/testing/android.py +248 -0
  29. pyjs/testing/artifacts.py +37 -0
  30. pyjs/testing/assertion_rewriter.py +125 -0
  31. pyjs/testing/builder.py +191 -0
  32. pyjs/testing/capture.py +133 -0
  33. pyjs/testing/client/__init__.py +1 -0
  34. pyjs/testing/client/app.py +718 -0
  35. pyjs/testing/client/assertions.py +49 -0
  36. pyjs/testing/client/runtime.py +123 -0
  37. pyjs/testing/client/sidebar.py +377 -0
  38. pyjs/testing/client/state.py +107 -0
  39. pyjs/testing/client/viewer.py +361 -0
  40. pyjs/testing/daemon.py +641 -0
  41. pyjs/testing/helpers.py +155 -0
  42. pyjs/testing/protocol.py +56 -0
  43. pyjs/testing/pytest_plugin.py +797 -0
  44. pyjs/testing/web.py +97 -0
  45. pyjs/testing/webgpu.py +27 -0
  46. pyjs/tooling/__init__.py +4 -0
  47. pyjs/tooling/android.py +138 -0
  48. pyjs/tooling/browser.py +676 -0
  49. pyjs/tooling/command.py +75 -0
  50. pyjs/tooling/nativescript.py +156 -0
  51. pyjs/tooling/node.py +170 -0
  52. pyjs/tooling/perf.py +163 -0
  53. pyjs/transpiler/__init__.py +23 -0
  54. pyjs/transpiler/_builtins.py +485 -0
  55. pyjs/transpiler/analyzer.py +1495 -0
  56. pyjs/transpiler/objects.py +1015 -0
  57. pyjs/transpiler/source.py +189 -0
  58. pyjs/transpiler/transpiler.py +748 -0
  59. pyjs/transpiler/utils.py +150 -0
  60. pyjs/web/__init__.py +5 -0
  61. pyjs/web/console.py +16 -0
  62. pyjs/web/dom.py +1529 -0
  63. pyjs/web/domx.py +474 -0
  64. pyjs/web/dragdrop.py +102 -0
  65. pyjs/web/events.py +1306 -0
  66. pyjs/web/files.py +203 -0
  67. pyjs/web/geometry.py +475 -0
  68. pyjs/web/html.py +927 -0
  69. pyjs/web/indexeddb.py +410 -0
  70. pyjs/web/javascript.py +112 -0
  71. pyjs/web/network.py +193 -0
  72. pyjs/web/ssr.py +70 -0
  73. pyjs/web/streams.py +17 -0
  74. pyjs/web/svg.py +684 -0
  75. pyjs/web/timers.py +29 -0
  76. pyjs/web/ui/__init__.py +18 -0
  77. pyjs/web/ui/accordion.py +166 -0
  78. pyjs/web/ui/alert.py +52 -0
  79. pyjs/web/ui/alert_dialog.py +102 -0
  80. pyjs/web/ui/aspect_ratio.py +12 -0
  81. pyjs/web/ui/attachment.py +80 -0
  82. pyjs/web/ui/avatar.py +105 -0
  83. pyjs/web/ui/badge.py +48 -0
  84. pyjs/web/ui/breadcrumb.py +85 -0
  85. pyjs/web/ui/bubble.py +38 -0
  86. pyjs/web/ui/button.py +86 -0
  87. pyjs/web/ui/calendar.py +124 -0
  88. pyjs/web/ui/card.py +58 -0
  89. pyjs/web/ui/carousel.py +99 -0
  90. pyjs/web/ui/chart.py +56 -0
  91. pyjs/web/ui/checkbox.py +31 -0
  92. pyjs/web/ui/collapsible.py +71 -0
  93. pyjs/web/ui/combobox.py +36 -0
  94. pyjs/web/ui/command.py +118 -0
  95. pyjs/web/ui/context_menu.py +65 -0
  96. pyjs/web/ui/date_picker.py +24 -0
  97. pyjs/web/ui/dialog.py +289 -0
  98. pyjs/web/ui/direction.py +9 -0
  99. pyjs/web/ui/drawer.py +72 -0
  100. pyjs/web/ui/dropdown_menu.py +239 -0
  101. pyjs/web/ui/empty.py +69 -0
  102. pyjs/web/ui/field.py +96 -0
  103. pyjs/web/ui/floating.py +90 -0
  104. pyjs/web/ui/hover_card.py +128 -0
  105. pyjs/web/ui/input.py +48 -0
  106. pyjs/web/ui/input_group.py +77 -0
  107. pyjs/web/ui/input_otp.py +76 -0
  108. pyjs/web/ui/item.py +78 -0
  109. pyjs/web/ui/kbd.py +26 -0
  110. pyjs/web/ui/label.py +14 -0
  111. pyjs/web/ui/marker.py +29 -0
  112. pyjs/web/ui/menubar.py +52 -0
  113. pyjs/web/ui/message.py +57 -0
  114. pyjs/web/ui/message_scroller.py +45 -0
  115. pyjs/web/ui/native_select.py +47 -0
  116. pyjs/web/ui/navigation_menu.py +110 -0
  117. pyjs/web/ui/pagination.py +63 -0
  118. pyjs/web/ui/popover.py +217 -0
  119. pyjs/web/ui/progress.py +44 -0
  120. pyjs/web/ui/radio_group.py +129 -0
  121. pyjs/web/ui/resizable.py +194 -0
  122. pyjs/web/ui/scroll_area.py +29 -0
  123. pyjs/web/ui/select.py +83 -0
  124. pyjs/web/ui/separator.py +24 -0
  125. pyjs/web/ui/sheet.py +77 -0
  126. pyjs/web/ui/sidebar.py +162 -0
  127. pyjs/web/ui/skeleton.py +15 -0
  128. pyjs/web/ui/slider.py +46 -0
  129. pyjs/web/ui/sonner.py +70 -0
  130. pyjs/web/ui/spinner.py +14 -0
  131. pyjs/web/ui/switch.py +35 -0
  132. pyjs/web/ui/table.py +84 -0
  133. pyjs/web/ui/tabs.py +167 -0
  134. pyjs/web/ui/text.py +15 -0
  135. pyjs/web/ui/textarea.py +28 -0
  136. pyjs/web/ui/toggle.py +109 -0
  137. pyjs/web/ui/tooltip.py +164 -0
  138. pyjs/web/ui/typography.py +79 -0
  139. pyjs/web/url.py +76 -0
  140. pyjs/web/webgpu.py +496 -0
  141. pyjs-0.0.1.dist-info/METADATA +441 -0
  142. pyjs-0.0.1.dist-info/RECORD +146 -0
  143. pyjs-0.0.1.dist-info/WHEEL +5 -0
  144. pyjs-0.0.1.dist-info/entry_points.txt +5 -0
  145. pyjs-0.0.1.dist-info/licenses/LICENSE +28 -0
  146. pyjs-0.0.1.dist-info/top_level.txt +1 -0
pyjs/cli.py ADDED
@@ -0,0 +1,816 @@
1
+ import argparse
2
+ import asyncio
3
+ import importlib
4
+ import importlib.util
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import textwrap
10
+ import traceback
11
+ from dataclasses import dataclass
12
+ from importlib import resources
13
+ from pathlib import Path
14
+
15
+ from pyjs.docs.cli import add_parser as add_docs_parser
16
+ from pyjs.docs.cli import run as run_docs
17
+ from pyjs.scaffolding import (
18
+ Template,
19
+ create,
20
+ find_template,
21
+ template_sources,
22
+ templates,
23
+ version_string,
24
+ )
25
+ from pyjs.server import page
26
+ from pyjs.testing.capture import capture_url
27
+ from pyjs.tooling.node import Node
28
+ from pyjs.tooling.perf import (
29
+ DEFAULT_SAMPLES,
30
+ DEFAULT_WARMUPS,
31
+ Benchmark,
32
+ benchmark_python,
33
+ calibrate_python,
34
+ javascript_benchmark,
35
+ run_python,
36
+ )
37
+ from pyjs.transpiler import SourceCompilation, bundle, compile_source, prepare_bundle
38
+
39
+ SUBCOMMANDS = {"build", "create", "template", "inspect", "skill", "docs"}
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class DirectInput:
44
+ source: str
45
+ filename: str
46
+ module_name: str
47
+ javascript_name: str
48
+
49
+
50
+ def parser() -> argparse.ArgumentParser:
51
+ version = version_string()
52
+ command = argparse.ArgumentParser(
53
+ prog="pyjs",
54
+ description="Run Python as JavaScript, build web applications, and create PyJS projects.",
55
+ epilog=(
56
+ "Direct execution: pyjs app.py, pyjs -m package.module, or pyjs -c 'print(1)'. "
57
+ "Use --src to print JavaScript without running it."
58
+ ),
59
+ )
60
+ command.add_argument("--version", action="version", version=f"%(prog)s {version}")
61
+ subcommands = command.add_subparsers(dest="command")
62
+
63
+ build = subcommands.add_parser("build", help="build a Python entry point for the browser")
64
+ build.add_argument(
65
+ "module",
66
+ help="module containing the entry point, optionally followed by :function",
67
+ )
68
+ build.add_argument("--only-js", action="store_true", help="only generate JavaScript")
69
+ build.add_argument(
70
+ "--include-main",
71
+ action="store_true",
72
+ help="include and call the entry-point function in the browser bundle",
73
+ )
74
+ build.add_argument("--args", help="JSON list of arguments passed to the entry point")
75
+
76
+ create_command = subcommands.add_parser("create", help="create a PyJS project or file")
77
+ create_command.add_argument(
78
+ "name",
79
+ help="application and Python package name",
80
+ )
81
+ create_command.add_argument(
82
+ "destination",
83
+ nargs="?",
84
+ help="directory to populate; defaults to NAME",
85
+ )
86
+ create_command.add_argument("--template", help="start from a registered template")
87
+ create_command.add_argument(
88
+ "--src-layout",
89
+ action="store_true",
90
+ help="place the application package under a src directory",
91
+ )
92
+ create_command.add_argument(
93
+ "--single-file",
94
+ action="store_true",
95
+ help="create one standalone Python file instead of a project directory",
96
+ )
97
+
98
+ template_command = subcommands.add_parser(
99
+ "template",
100
+ help="list templates or print a template's source",
101
+ )
102
+ template_command.add_argument("name", nargs="?", help="registered template to inspect")
103
+ template_command.add_argument(
104
+ "--src",
105
+ action="store_true",
106
+ help="print the template's transpiled entry-module JavaScript",
107
+ )
108
+ template_command.add_argument("--json", action="store_true", help="emit the catalog as JSON")
109
+
110
+ inspect = subcommands.add_parser(
111
+ "inspect",
112
+ help="capture and inspect a running web application",
113
+ )
114
+ inspect.add_argument("url", nargs="?", default="http://127.0.0.1:8000")
115
+ inspect.add_argument(
116
+ "-o",
117
+ "--output",
118
+ type=Path,
119
+ default=Path("screenshots/pyjs-inspect.png"),
120
+ )
121
+ inspect.add_argument("--width", type=int, default=1280)
122
+ inspect.add_argument("--height", type=int, default=800)
123
+ inspect.add_argument("--scale", type=float, default=1)
124
+ inspect.add_argument("--color-scheme", choices=("light", "dark"))
125
+ inspect.add_argument("--wait-for", metavar="SELECTOR")
126
+ inspect.add_argument("--selector", help="capture only the matching element")
127
+ inspect.add_argument("--delay", type=float, default=0, help="seconds to wait before capture")
128
+ inspect.add_argument("--frames", type=int, default=2, help="animation frames to wait")
129
+ inspect.add_argument("--full-page", action="store_true")
130
+ inspect.add_argument("--interval", type=float, help="seconds between repeated captures")
131
+ inspect.add_argument("--duration", type=float, help="total repeated-capture duration")
132
+ inspect.add_argument("--no-settle", action="store_true")
133
+ inspect.add_argument("--headed", action="store_true")
134
+ inspect.add_argument("--json", action="store_true", help="print artifact paths as JSON")
135
+
136
+ subcommands.add_parser(
137
+ "skill",
138
+ help="print version-matched instructions for coding agents",
139
+ )
140
+ add_docs_parser(subcommands)
141
+ return command
142
+
143
+
144
+ def direct_parser() -> argparse.ArgumentParser:
145
+ command = argparse.ArgumentParser(
146
+ prog="pyjs",
147
+ description="Transpile Python and run the result with PyJS-managed Node.",
148
+ )
149
+ input_group = command.add_mutually_exclusive_group()
150
+ input_group.add_argument("-c", dest="code", help="Python program passed as a string")
151
+ input_group.add_argument("-m", dest="module", help="run a Python module as JavaScript")
152
+ command.add_argument("source", nargs="?", help="Python file, or - to read standard input")
153
+ source_group = command.add_mutually_exclusive_group()
154
+ source_group.add_argument(
155
+ "--src", action="store_true", help="print the entry module without running it"
156
+ )
157
+ source_group.add_argument(
158
+ "--src-all",
159
+ action="store_true",
160
+ help="print the entry module and all tree-shaken dependencies",
161
+ )
162
+ command.add_argument(
163
+ "-v",
164
+ action="count",
165
+ default=0,
166
+ help="show generated source and diagnostics; repeat for more detail",
167
+ )
168
+ command.add_argument("--json", action="store_true", help="emit machine-readable results")
169
+ command.add_argument("--perf", action="store_true", help="compare Python and JavaScript speed")
170
+ command.add_argument("--loops", type=int, help="iterations in each performance sample")
171
+ command.add_argument(
172
+ "--samples",
173
+ type=int,
174
+ default=DEFAULT_SAMPLES,
175
+ help=f"performance samples (default: {DEFAULT_SAMPLES})",
176
+ )
177
+ command.add_argument(
178
+ "--warmups",
179
+ type=int,
180
+ default=DEFAULT_WARMUPS,
181
+ help=f"warmup samples (default: {DEFAULT_WARMUPS})",
182
+ )
183
+ return command
184
+
185
+
186
+ def _is_direct_invocation(argv: list[str]) -> bool:
187
+ if argv and argv[0] in SUBCOMMANDS:
188
+ return False
189
+ direct_options = {
190
+ "-c",
191
+ "-m",
192
+ "--src",
193
+ "--src-all",
194
+ "--json",
195
+ "--perf",
196
+ "--loops",
197
+ "--samples",
198
+ "--warmups",
199
+ }
200
+ if any(
201
+ argument in direct_options
202
+ or (argument.startswith("-") and argument[1:] and set(argument[1:]) == {"v"})
203
+ for argument in argv
204
+ ):
205
+ return True
206
+ return any(argument == "-" for argument in argv) or any(
207
+ not argument.startswith("-") and argument not in SUBCOMMANDS for argument in argv
208
+ )
209
+
210
+
211
+ def _direct_input(args, command_parser: argparse.ArgumentParser) -> DirectInput:
212
+ selected = sum(value is not None for value in (args.code, args.module, args.source))
213
+ if selected != 1:
214
+ command_parser.error("provide exactly one of a Python file, -, -c CODE, or -m MODULE")
215
+
216
+ if args.code is not None:
217
+ return DirectInput(args.code, "<string>", "__pyjs_command__", ".js")
218
+
219
+ if args.module is not None:
220
+ spec = importlib.util.find_spec(args.module)
221
+ if spec is None or spec.origin is None:
222
+ command_parser.error(f"cannot find module {args.module!r}")
223
+ module_name = args.module
224
+ if spec.submodule_search_locations is not None:
225
+ module_name = f"{args.module}.__main__"
226
+ spec = importlib.util.find_spec(module_name)
227
+ if spec is None or spec.origin is None:
228
+ command_parser.error(f"package {args.module!r} has no __main__ module")
229
+ path = Path(spec.origin)
230
+ if path.suffix != ".py":
231
+ command_parser.error(f"module {args.module!r} does not have Python source")
232
+ return DirectInput(
233
+ path.read_text(encoding="utf-8"),
234
+ str(path),
235
+ module_name,
236
+ f"{module_name}.js",
237
+ )
238
+
239
+ if args.source == "-":
240
+ source = sys.stdin.read()
241
+ return DirectInput(source, "<stdin>", "__pyjs_stdin__", "stdin.js")
242
+
243
+ path = Path(args.source)
244
+ if not path.is_file():
245
+ command_parser.error(f"cannot open {args.source!r}: no such file")
246
+ source = path.read_text(encoding="utf-8")
247
+ return DirectInput(source, str(path), path.stem.replace("-", "_"), str(path.with_suffix(".js")))
248
+
249
+
250
+ def _compile_direct(program: DirectInput) -> SourceCompilation:
251
+ return compile_source(
252
+ program.source,
253
+ filename=program.filename,
254
+ module_name=program.module_name,
255
+ )
256
+
257
+
258
+ def _executable_javascript(compilation: SourceCompilation) -> str:
259
+ return compilation.javascript + textwrap.dedent("""\
260
+ Promise.resolve(__pyjsEntry__.main()).catch((error) => {
261
+ console.error(error);
262
+ process.exitCode = 1;
263
+ });
264
+ """)
265
+
266
+
267
+ def _direct(args, command_parser: argparse.ArgumentParser) -> int:
268
+ source_only = args.src or args.src_all
269
+ if source_only and args.json:
270
+ command_parser.error("--src and --src-all cannot be combined with --json")
271
+ if source_only and args.perf:
272
+ command_parser.error("--src and --src-all cannot be combined with --perf")
273
+ if args.loops is not None and args.loops <= 0:
274
+ command_parser.error("--loops must be positive")
275
+ if args.samples <= 0 or args.warmups < 0:
276
+ command_parser.error("--samples must be positive and --warmups cannot be negative")
277
+
278
+ try:
279
+ program = _direct_input(args, command_parser)
280
+ compilation = _compile_direct(program)
281
+ except Exception as error:
282
+ if args.json:
283
+ details = {
284
+ "type": type(error).__name__,
285
+ "message": str(error),
286
+ }
287
+ if args.v:
288
+ details["traceback"] = traceback.format_exc()
289
+ print(json.dumps({"error": details}, indent=2))
290
+ return 2
291
+ if args.v:
292
+ traceback.print_exc()
293
+ print(f"pyjs: error: {error}", file=sys.stderr)
294
+ return 2
295
+ command_parser.error(str(error))
296
+
297
+ javascript = _executable_javascript(compilation)
298
+ if source_only:
299
+ _print_sources(
300
+ program,
301
+ compilation,
302
+ include_dependencies=args.src_all,
303
+ headings=args.src_all,
304
+ )
305
+ return 0
306
+ if args.perf:
307
+ return _perf(args, program, compilation, javascript, command_parser)
308
+
309
+ node = Node()
310
+ try:
311
+ result = node.run_javascript(javascript)
312
+ except (OSError, RuntimeError) as error:
313
+ command_parser.error(str(error))
314
+
315
+ if args.json:
316
+ payload = {
317
+ "input": program.filename,
318
+ "javascript_name": program.javascript_name,
319
+ "node": {"version": node.version, "path": str(node.executable)},
320
+ "exit_code": result.returncode,
321
+ "stdout": result.stdout,
322
+ "stderr": result.stderr,
323
+ }
324
+ if args.v:
325
+ payload["sources"] = _source_files(program, compilation, include_dependencies=False)
326
+ if args.v >= 2:
327
+ payload["compilation"] = _compilation_metadata(compilation, javascript, node)
328
+ if args.v >= 3:
329
+ payload["types"] = _analyzed_types(compilation)
330
+ print(json.dumps(payload, indent=2))
331
+ return result.returncode
332
+
333
+ if args.v >= 2:
334
+ _print_compilation(compilation, javascript, node)
335
+ if args.v >= 3:
336
+ _print_section("analyzed types")
337
+ print(_analyzed_types(compilation))
338
+ if args.v:
339
+ _print_sources(program, compilation, include_dependencies=False)
340
+ _print_section(f"node v{node.version} output")
341
+ print(result.stdout, end="")
342
+ print(result.stderr, end="", file=sys.stderr)
343
+ return result.returncode
344
+
345
+
346
+ def _print_section(name: str) -> None:
347
+ print(f"===== {name} =====")
348
+
349
+
350
+ def _compilation_metadata(
351
+ compilation: SourceCompilation, javascript: str, node: Node | None = None
352
+ ) -> dict:
353
+ metadata = {
354
+ "entry": f"{compilation.entry_point.container.name}.{compilation.entry_point.name}",
355
+ "modules": list(compilation.module_names),
356
+ "transpile_ms": round(compilation.elapsed * 1000, 3),
357
+ "generated_source_bytes": sum(
358
+ len(source.encode()) for source in compilation.sources.values()
359
+ ),
360
+ "executable_bundle_bytes": len(javascript.encode()),
361
+ "runtime_wrapper": "hidden from source display",
362
+ }
363
+ if node is not None:
364
+ metadata.update(node_version=node.version, node_path=str(node.executable))
365
+ return metadata
366
+
367
+
368
+ def _print_compilation(compilation: SourceCompilation, javascript: str, node: Node) -> None:
369
+ _print_section("compilation")
370
+ for name, value in _compilation_metadata(compilation, javascript, node).items():
371
+ if isinstance(value, list):
372
+ value = ", ".join(value)
373
+ print(f"{name}: {value}")
374
+
375
+
376
+ def _analyzed_types(compilation: SourceCompilation) -> str:
377
+ try:
378
+ return compilation.analysis.types
379
+ except Exception as error:
380
+ return f"[type-tree output unavailable: {error}]"
381
+
382
+
383
+ def _source_files(
384
+ program: DirectInput,
385
+ compilation: SourceCompilation,
386
+ *,
387
+ include_dependencies: bool,
388
+ ) -> dict[str, str]:
389
+ entry_module = compilation.entry_point.container.name
390
+ return {
391
+ program.javascript_name if name == entry_module else f"{name}.js": source
392
+ for name, source in compilation.sources.items()
393
+ if include_dependencies or name == entry_module
394
+ }
395
+
396
+
397
+ def _print_sources(
398
+ program: DirectInput,
399
+ compilation: SourceCompilation,
400
+ *,
401
+ include_dependencies: bool,
402
+ headings: bool = True,
403
+ ) -> None:
404
+ sources = _source_files(
405
+ program,
406
+ compilation,
407
+ include_dependencies=include_dependencies,
408
+ )
409
+ for index, (name, source) in enumerate(sources.items()):
410
+ if headings:
411
+ if index:
412
+ print()
413
+ _print_section(name)
414
+ print(source, end="" if source.endswith("\n") else "\n")
415
+
416
+
417
+ def _perf(args, program, compilation, javascript, command_parser) -> int:
418
+ node = Node()
419
+ python_entry = compilation.analysis.module.main
420
+ python_stdout, python_stderr, python_error = run_python(python_entry)
421
+ try:
422
+ node_result = node.run_javascript(javascript)
423
+ except (OSError, RuntimeError) as error:
424
+ command_parser.error(str(error))
425
+
426
+ if python_error is not None:
427
+ python_stderr += "".join(
428
+ traceback.format_exception(type(python_error), python_error, python_error.__traceback__)
429
+ )
430
+ outputs_match = (
431
+ python_error is None
432
+ and node_result.returncode == 0
433
+ and python_stdout == node_result.stdout
434
+ and python_stderr == node_result.stderr
435
+ )
436
+
437
+ try:
438
+ calibration = None
439
+ loops = args.loops
440
+ if loops is None:
441
+ python_loops = calibrate_python(python_entry)
442
+ javascript_loops = _benchmark_javascript(
443
+ node,
444
+ compilation.javascript,
445
+ is_async=compilation.entry_point.is_async,
446
+ loops=None,
447
+ samples=0,
448
+ warmups=0,
449
+ ).loops
450
+ loops = max(python_loops, javascript_loops)
451
+ calibration = {
452
+ "python_loops": python_loops,
453
+ "javascript_loops": javascript_loops,
454
+ "selected_loops": loops,
455
+ }
456
+ python_benchmark = benchmark_python(
457
+ python_entry,
458
+ loops=loops,
459
+ samples=args.samples,
460
+ warmups=args.warmups,
461
+ )
462
+ node_benchmark = _benchmark_javascript(
463
+ node,
464
+ compilation.javascript,
465
+ is_async=compilation.entry_point.is_async,
466
+ loops=loops,
467
+ samples=args.samples,
468
+ warmups=args.warmups,
469
+ )
470
+ except Exception as error:
471
+ command_parser.error(f"performance measurement failed: {error}")
472
+
473
+ python_stats = python_benchmark.json()
474
+ node_stats = node_benchmark.json()
475
+ ratio = python_stats["median"] / node_stats["median"]
476
+ payload = {
477
+ "input": program.filename,
478
+ "correctness": {
479
+ "matches": outputs_match,
480
+ "python": {
481
+ "version": sys.version.split()[0],
482
+ "stdout": python_stdout,
483
+ "stderr": python_stderr,
484
+ "exit_code": 0 if python_error is None else 1,
485
+ },
486
+ "node": {
487
+ "version": node.version,
488
+ "stdout": node_result.stdout,
489
+ "stderr": node_result.stderr,
490
+ "exit_code": node_result.returncode,
491
+ },
492
+ },
493
+ "performance": {
494
+ "python": python_stats,
495
+ "javascript": node_stats,
496
+ "python_to_javascript_ratio": ratio,
497
+ },
498
+ }
499
+ if calibration is not None:
500
+ payload["performance"]["calibration"] = calibration
501
+ if args.v:
502
+ payload["sources"] = _source_files(program, compilation, include_dependencies=False)
503
+ if args.v >= 2:
504
+ payload["compilation"] = _compilation_metadata(compilation, javascript, node)
505
+ if args.v >= 3:
506
+ payload["types"] = _analyzed_types(compilation)
507
+
508
+ if args.json:
509
+ print(json.dumps(payload, indent=2))
510
+ return 0 if outputs_match else 1
511
+
512
+ if args.v >= 2:
513
+ _print_compilation(compilation, javascript, node)
514
+ if args.v >= 3:
515
+ _print_section("analyzed types")
516
+ print(_analyzed_types(compilation))
517
+ if args.v:
518
+ _print_sources(program, compilation, include_dependencies=False)
519
+ _print_section("correctness")
520
+ print(f"outputs match: {'yes' if outputs_match else 'no'}")
521
+ if args.v >= 2 or not outputs_match:
522
+ print(f"python stdout: {python_stdout!r}")
523
+ print(f"node stdout: {node_result.stdout!r}")
524
+ print(f"python stderr: {python_stderr!r}")
525
+ print(f"node stderr: {node_result.stderr!r}")
526
+ _print_section("performance")
527
+ if calibration is not None:
528
+ print(
529
+ f"Auto-calibrated {calibration['selected_loops']} common loops "
530
+ f"(Python {calibration['python_loops']}, "
531
+ f"JavaScript {calibration['javascript_loops']})"
532
+ )
533
+ _print_benchmark("Python", python_stats)
534
+ _print_benchmark("JavaScript", node_stats)
535
+ faster = "JavaScript" if ratio > 1 else "Python"
536
+ factor = ratio if ratio > 1 else 1 / ratio
537
+ print(f"{faster} is {factor:.2f}x faster (median per loop)")
538
+ return 0 if outputs_match else 1
539
+
540
+
541
+ def _print_benchmark(name: str, stats: dict) -> None:
542
+ print(
543
+ f"{name}: {stats['median'] * 1e6:.3f} us median "
544
+ f"({stats['loops']} loops x {len(stats['samples'])} samples; "
545
+ f"mean {stats['mean'] * 1e6:.3f} us, "
546
+ f"stdev {stats['stdev'] * 1e6:.3f} us, "
547
+ f"range {stats['min'] * 1e6:.3f}-{stats['max'] * 1e6:.3f} us)"
548
+ )
549
+
550
+
551
+ def _benchmark_javascript(
552
+ node: Node,
553
+ source: str,
554
+ *,
555
+ is_async: bool,
556
+ loops: int | None,
557
+ samples: int,
558
+ warmups: int,
559
+ ) -> Benchmark:
560
+ benchmark_source = javascript_benchmark(
561
+ source,
562
+ is_async=is_async,
563
+ loops=loops,
564
+ samples=samples,
565
+ warmups=warmups,
566
+ )
567
+ result = node.run_javascript(benchmark_source)
568
+ if result.returncode:
569
+ raise RuntimeError(result.stderr.strip() or "Node benchmark failed")
570
+ marker = next(
571
+ line.removeprefix("__PYJS_PERF__")
572
+ for line in result.stdout.splitlines()
573
+ if line.startswith("__PYJS_PERF__")
574
+ )
575
+ values = json.loads(marker)
576
+ return Benchmark(values["loops"], tuple(values["values"]))
577
+
578
+
579
+ def _build(args, command_parser: argparse.ArgumentParser) -> int:
580
+ if args.module.endswith(".py"):
581
+ suggestion = f"perhaps try: {Path(args.module).stem}"
582
+ command_parser.error(
583
+ f"{args.module} appears to be a Python file; a module name is expected, {suggestion}"
584
+ )
585
+
586
+ module_name, entry = args.module, "main"
587
+ if ":" in args.module:
588
+ module_name, entry = args.module.split(":", 1)
589
+
590
+ entry_args = []
591
+ if args.args:
592
+ try:
593
+ entry_args = json.loads(args.args)
594
+ except json.JSONDecodeError as error:
595
+ command_parser.error(f"--args must be valid JSON: {error.msg}")
596
+ if not isinstance(entry_args, list):
597
+ command_parser.error("--args must be a JSON list")
598
+
599
+ module = importlib.import_module(module_name)
600
+ entry_point = getattr(module, entry)
601
+ file_stem = f"{module_name}.{entry}"
602
+
603
+ js_file_name = f"{file_stem}.js"
604
+ print(f"Writing {module_name}:{entry} JavaScript to ./{js_file_name}")
605
+ javascript, css = bundle(entry_point, args.include_main)
606
+ Path(js_file_name).write_text(javascript, encoding="utf-8")
607
+
608
+ if args.only_js:
609
+ return 0
610
+
611
+ css_file_name = f"{file_stem}.css"
612
+ print(f"Writing {module_name}:{entry} CSS to ./{css_file_name}")
613
+ Path(css_file_name).write_text(css, encoding="utf-8")
614
+
615
+ html = page(entry_point(*entry_args), js_file_name, css_file_name, "text/javascript")
616
+ html_file_name = f"{file_stem}.html"
617
+ print(f"Writing {module_name}:{entry} HTML to ./{html_file_name}")
618
+ Path(html_file_name).write_text(html, encoding="utf-8")
619
+ return 0
620
+
621
+
622
+ def _create(args, command_parser: argparse.ArgumentParser) -> int:
623
+ try:
624
+ destination = create(
625
+ args.name,
626
+ args.destination,
627
+ template=args.template,
628
+ single_file=args.single_file,
629
+ src_layout=args.src_layout,
630
+ )
631
+ except (FileExistsError, OSError, ValueError) as error:
632
+ command_parser.error(str(error))
633
+
634
+ if args.single_file:
635
+ print(f"Created PyJS application at {destination}")
636
+ print()
637
+ print(f" python {destination}")
638
+ return 0
639
+
640
+ print(f"Created PyJS project in {destination}")
641
+ print()
642
+ if Path.cwd().resolve() != destination:
643
+ print(f" cd {destination}")
644
+ print(' python -m pip install -e ".[test]"')
645
+ if args.template is None:
646
+ print(f" python -m {args.name}")
647
+ else:
648
+ print(" See README.md for the run command")
649
+ return 0
650
+
651
+
652
+ def _template_javascript(template: Template) -> str:
653
+ module_name = template.name
654
+ if template.kind == "directory":
655
+ module_name += f".{template.primary_module}"
656
+ module = importlib.import_module(module_name)
657
+ package, entry_point, _ = prepare_bundle(
658
+ module.main,
659
+ include_main=True,
660
+ include_css=False,
661
+ )
662
+ return package[entry_point.container.name]
663
+
664
+
665
+ def _template(args, command_parser: argparse.ArgumentParser) -> int:
666
+ if args.name is not None:
667
+ if args.json:
668
+ command_parser.error("--json cannot be combined with a template name")
669
+ try:
670
+ template = find_template(args.name)
671
+ except ValueError as error:
672
+ command_parser.error(str(error))
673
+ if args.src:
674
+ try:
675
+ source = _template_javascript(template)
676
+ except Exception as error:
677
+ command_parser.error(f"could not transpile template {template.name!r}: {error}")
678
+ print(f"===== {template.primary_module}.js =====")
679
+ print(source, end="" if source.endswith("\n") else "\n")
680
+ return 0
681
+ sources = template_sources(template)
682
+ for index, (name, content) in enumerate(sources):
683
+ if index:
684
+ print()
685
+ print(f"===== {name} =====")
686
+ if content is None:
687
+ print("[binary file omitted]")
688
+ else:
689
+ print(content, end="" if content.endswith("\n") else "\n")
690
+ return 0
691
+
692
+ if args.src:
693
+ command_parser.error("--src requires a template name")
694
+
695
+ catalog = templates()
696
+ if args.json:
697
+ print(
698
+ json.dumps(
699
+ [
700
+ {
701
+ "name": template.name,
702
+ "title": template.title,
703
+ "description": template.description,
704
+ "kind": template.kind,
705
+ }
706
+ for template in catalog
707
+ ],
708
+ indent=2,
709
+ )
710
+ )
711
+ return 0
712
+
713
+ if not catalog:
714
+ print("No PyJS templates are installed.")
715
+ print()
716
+ print("Install the official templates with:")
717
+ print()
718
+ print(" python -m pip install pyjs-examples")
719
+ return 0
720
+
721
+ width = max(
722
+ (len(template.name) for template in catalog),
723
+ default=len("Template"),
724
+ )
725
+ description_indent = width + 10
726
+ description_width = max(
727
+ 20,
728
+ shutil.get_terminal_size(fallback=(100, 24)).columns - description_indent,
729
+ )
730
+ print(f" {'Template':<{width}} {'Type':<4} Description")
731
+ for template in catalog:
732
+ description = textwrap.wrap(template.description, width=description_width) or [""]
733
+ kind = "dir" if template.kind == "directory" else template.kind
734
+ print(f" {template.name:<{width}} {kind:<4} {description[0]}")
735
+ for line in description[1:]:
736
+ print(f"{'':<{description_indent}}{line}")
737
+ return 0
738
+
739
+
740
+ def _skill() -> int:
741
+ skill = resources.files("pyjs").joinpath("skills", "pyjs", "SKILL.md")
742
+ content = skill.read_text(encoding="utf-8")
743
+ print(content, end="" if content.endswith("\n") else "\n")
744
+ return 0
745
+
746
+
747
+ def _inspect(args, command_parser: argparse.ArgumentParser) -> int:
748
+ if args.width <= 0 or args.height <= 0 or args.scale <= 0:
749
+ command_parser.error("--width, --height, and --scale must be positive")
750
+ if args.delay < 0 or args.frames < 0:
751
+ command_parser.error("--delay and --frames cannot be negative")
752
+ if (args.interval is None) != (args.duration is None):
753
+ command_parser.error("--interval and --duration must be used together")
754
+ if args.interval is not None and (args.interval <= 0 or args.duration <= 0):
755
+ command_parser.error("--interval and --duration must be positive")
756
+
757
+ try:
758
+ result = asyncio.run(
759
+ capture_url(
760
+ args.url,
761
+ args.output,
762
+ width=args.width,
763
+ height=args.height,
764
+ scale=args.scale,
765
+ color_scheme=args.color_scheme,
766
+ wait_for_selector=args.wait_for,
767
+ selector=args.selector,
768
+ delay=args.delay,
769
+ frames=args.frames,
770
+ full_page=args.full_page,
771
+ settle=not args.no_settle,
772
+ interval=args.interval,
773
+ duration=args.duration,
774
+ headed=args.headed,
775
+ )
776
+ )
777
+ except (ConnectionError, OSError, RuntimeError, TimeoutError) as error:
778
+ command_parser.error(str(error))
779
+
780
+ if args.json:
781
+ print(json.dumps(result.json(), indent=2))
782
+ else:
783
+ for screenshot in result.screenshots:
784
+ print(f"Saved screenshot: {screenshot}")
785
+ print(f"Saved diagnostics: {result.diagnostics}")
786
+ return 0
787
+
788
+
789
+ def main(argv: list[str] | None = None) -> int:
790
+ sys.path.insert(0, os.getcwd())
791
+ argv = list(sys.argv[1:] if argv is None else argv)
792
+ if _is_direct_invocation(argv):
793
+ command_parser = direct_parser()
794
+ return _direct(command_parser.parse_args(argv), command_parser)
795
+ command_parser = parser()
796
+ args = command_parser.parse_args(argv)
797
+ if args.command is None:
798
+ command_parser.print_help()
799
+ return 0
800
+ if args.command == "build":
801
+ return _build(args, command_parser)
802
+ if args.command == "create":
803
+ return _create(args, command_parser)
804
+ if args.command == "template":
805
+ return _template(args, command_parser)
806
+ if args.command == "inspect":
807
+ return _inspect(args, command_parser)
808
+ if args.command == "skill":
809
+ return _skill()
810
+ if args.command == "docs":
811
+ return run_docs(args)
812
+ raise AssertionError(f"unknown command: {args.command}")
813
+
814
+
815
+ if __name__ == "__main__":
816
+ sys.exit(main())