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/server.py ADDED
@@ -0,0 +1,468 @@
1
+ import asyncio
2
+ import importlib
3
+ import json
4
+ import secrets
5
+ import sys
6
+ import threading
7
+ from http import HTTPStatus
8
+ from http.cookies import SimpleCookie
9
+ from http.server import BaseHTTPRequestHandler, HTTPServer
10
+ from pathlib import Path
11
+ from urllib.parse import urlsplit
12
+
13
+ from websockets.asyncio.server import ServerConnection
14
+ from websockets.asyncio.server import serve as websocket_serve
15
+ from websockets.datastructures import Headers
16
+ from websockets.http11 import Request, Response
17
+
18
+ from pyjs.transpiler import prepare_bundle
19
+ from pyjs.web.domx import HTMLElement, tag
20
+ from pyjs.web.ssr import render_document, write_html
21
+
22
+ SESSION_COOKIE_NAME = "pyjs-session"
23
+ MAX_REQUEST_BODY_SIZE = 64 * 1024
24
+
25
+
26
+ def _server_url(host, port):
27
+ if not host or host in ("0.0.0.0", "::"):
28
+ host = "127.0.0.1"
29
+ elif ":" in host and not host.startswith("["):
30
+ host = f"[{host}]"
31
+ return f"http://{host}:{port}/"
32
+
33
+
34
+ def _module_name(module):
35
+ path = Path(module)
36
+ if not path.is_file():
37
+ return module
38
+
39
+ source = path.resolve()
40
+ for loaded_module in tuple(sys.modules.values()):
41
+ spec = getattr(loaded_module, "__spec__", None)
42
+ loaded_file = getattr(loaded_module, "__file__", None)
43
+ if spec is not None and loaded_file is not None and Path(loaded_file).resolve() == source:
44
+ return spec.name
45
+ return path.stem
46
+
47
+
48
+ class ServerRequest:
49
+ def __init__(self, method, path, headers, body, session, session_id, new_session):
50
+ self.method = method
51
+ self.path = path
52
+ self.headers = headers
53
+ self.body = body
54
+ self.session = session
55
+ self.session_id = session_id
56
+ self.new_session = new_session
57
+
58
+ def json(self):
59
+ return json.loads(self.body.decode("utf-8"))
60
+
61
+
62
+ class ServerResponse:
63
+ def __init__(self, body="", status=200, content_type="text/plain", headers=None):
64
+ self.body = body
65
+ self.status = status
66
+ self.content_type = content_type
67
+ self.headers = headers or {}
68
+
69
+
70
+ def websocket_response(response, request=None):
71
+ body = response.body
72
+ if isinstance(body, str):
73
+ body = body.encode("utf-8")
74
+ headers = Headers()
75
+ if response.content_type is not None:
76
+ headers["Content-Type"] = response.content_type
77
+ headers["Content-Length"] = str(len(body))
78
+ if request is not None and request.new_session:
79
+ headers["Set-Cookie"] = (
80
+ f"{SESSION_COOKIE_NAME}={request.session_id}; HttpOnly; Path=/; SameSite=Lax"
81
+ )
82
+ for name, value in response.headers.items():
83
+ headers[name] = value
84
+ status = HTTPStatus(response.status)
85
+ return Response(status.value, status.phrase, headers, body)
86
+
87
+
88
+ def html(body, js, css, script_type):
89
+ return tag(
90
+ "html",
91
+ tag(
92
+ "head",
93
+ tag("meta", {"charset": "utf-8"}),
94
+ tag("link", {"rel": "stylesheet", "href": css}),
95
+ ),
96
+ tag("body", body),
97
+ tag("script", {"type": script_type, "src": js}, " "),
98
+ )
99
+
100
+
101
+ def page(body, js, css, script_type="module"):
102
+ return render_document(html(body, js, css, script_type))
103
+
104
+
105
+ def write(parent: HTMLElement, src):
106
+ write_html(parent, src)
107
+
108
+
109
+ class RequestHandler(BaseHTTPRequestHandler):
110
+ def do_GET(self):
111
+ server: PyjsServer = self.server
112
+ server.refresh()
113
+ path = urlsplit(self.path).path
114
+ if path == "/":
115
+ request = server.create_request("GET", path, self.headers, b"")
116
+ response = ServerResponse(
117
+ page(
118
+ server.get_html(request),
119
+ f"{server.entry_point.container.name}.js",
120
+ "index.css",
121
+ ),
122
+ content_type="text/html",
123
+ )
124
+ self.send_server_response(response, request)
125
+ elif path == "/index.css":
126
+ self.send_server_response(ServerResponse(server.get_css(), content_type="text/css"))
127
+ elif path.endswith(".js"):
128
+ module_name = Path(path).stem
129
+ if module_name not in server.package:
130
+ self.send_error(404)
131
+ return
132
+ self.send_server_response(
133
+ ServerResponse(server.package[module_name], content_type="application/javascript")
134
+ )
135
+ else:
136
+ self.send_error(404)
137
+
138
+ def do_POST(self):
139
+ server: PyjsServer = self.server
140
+ server.refresh()
141
+ try:
142
+ content_length = int(self.headers.get("Content-Length", "0"))
143
+ except ValueError:
144
+ self.send_error(400, "Invalid Content-Length")
145
+ return
146
+ if content_length < 0:
147
+ self.send_error(400, "Invalid Content-Length")
148
+ return
149
+ if content_length > MAX_REQUEST_BODY_SIZE:
150
+ self.send_error(413, "Request body is too large")
151
+ return
152
+
153
+ path = urlsplit(self.path).path
154
+ request = server.create_request(
155
+ "POST",
156
+ path,
157
+ self.headers,
158
+ self.rfile.read(content_length),
159
+ )
160
+ try:
161
+ response = server.dispatch(request)
162
+ except ValueError as error:
163
+ response = ServerResponse(str(error), status=400)
164
+ self.send_server_response(response, request)
165
+
166
+ def send_server_response(self, response, request=None):
167
+ body = response.body
168
+ if isinstance(body, str):
169
+ body = body.encode("utf-8")
170
+
171
+ self.send_response(response.status)
172
+ if response.content_type is not None:
173
+ self.send_header("Content-Type", response.content_type)
174
+ if body:
175
+ self.send_header("Content-Length", str(len(body)))
176
+ if request is not None and request.new_session:
177
+ self.send_header(
178
+ "Set-Cookie",
179
+ f"{SESSION_COOKIE_NAME}={request.session_id}; HttpOnly; Path=/; SameSite=Lax",
180
+ )
181
+ for name, value in response.headers.items():
182
+ self.send_header(name, value)
183
+ self.end_headers()
184
+ if body:
185
+ self.wfile.write(body)
186
+
187
+
188
+ class PyjsApplication:
189
+ def __init__(
190
+ self,
191
+ module: str,
192
+ css: str,
193
+ entry_point: str,
194
+ *entry_point_args,
195
+ render=None,
196
+ routes=None,
197
+ ):
198
+ self.module_name = _module_name(module)
199
+ self.module = importlib.import_module(self.module_name)
200
+ self.module_path = Path(self.module.__file__)
201
+ self.module_last_modified = None
202
+ self.package = None
203
+ self.css_provided = bool(css)
204
+ self.css = css
205
+ self.entry_point = None
206
+ self.entry_point_name = entry_point or "main"
207
+ self.entry_point_args = entry_point_args
208
+ self.render_name = self.callback_name(render) if render is not None else None
209
+ self.routes = {
210
+ (method.upper(), path): self.callback_name(callback)
211
+ for (method, path), callback in (routes or {}).items()
212
+ }
213
+ self.sessions = {}
214
+ self.refresh()
215
+
216
+ def callback_name(self, callback):
217
+ if isinstance(callback, str):
218
+ return callback
219
+ name = callback.__name__
220
+ if not hasattr(self.module, name):
221
+ raise ValueError("server callbacks must be module-level functions in the served module")
222
+ return name
223
+
224
+ def resolve_callback(self, name):
225
+ return getattr(self.module, name)
226
+
227
+ def create_request(self, method, path, headers, body):
228
+ cookies = SimpleCookie(headers.get("Cookie", ""))
229
+ session_cookie = cookies.get(SESSION_COOKIE_NAME)
230
+ session_id = session_cookie.value if session_cookie is not None else None
231
+ new_session = session_id not in self.sessions
232
+ if new_session:
233
+ session_id = secrets.token_urlsafe(24)
234
+ self.sessions[session_id] = {}
235
+ return ServerRequest(
236
+ method,
237
+ path,
238
+ headers,
239
+ body,
240
+ self.sessions[session_id],
241
+ session_id,
242
+ new_session,
243
+ )
244
+
245
+ def dispatch(self, request):
246
+ callback_name = self.routes.get((request.method, request.path))
247
+ if callback_name is None:
248
+ return ServerResponse("Not found", status=404)
249
+ response = self.resolve_callback(callback_name)(request)
250
+ if response is None:
251
+ return ServerResponse(status=204, content_type=None)
252
+ if not isinstance(response, ServerResponse):
253
+ raise TypeError("server route callbacks must return ServerResponse or None")
254
+ return response
255
+
256
+ def refresh(self):
257
+ last_modified = self.module_path.stat().st_mtime
258
+ if self.module_last_modified != last_modified:
259
+ self.module_last_modified = last_modified
260
+ importlib.reload(self.module)
261
+ entry_point_py_func = getattr(self.module, self.entry_point_name)
262
+ self.package, self.entry_point, css = prepare_bundle(entry_point_py_func)
263
+ if not self.css_provided:
264
+ self.css = css
265
+ for package_name, js in self.package.items():
266
+ self.package[package_name] = js.encode("utf-8")
267
+
268
+ def get_html(self, request=None):
269
+ if self.render_name is not None:
270
+ return self.resolve_callback(self.render_name)(request)
271
+ return self.entry_point.py_func(*self.entry_point_args)
272
+
273
+ def get_css(self):
274
+ return self.css
275
+
276
+
277
+ class PyjsServer(HTTPServer, PyjsApplication):
278
+ def __init__(
279
+ self,
280
+ module: str,
281
+ css: str,
282
+ entry_point: str,
283
+ *entry_point_args,
284
+ render=None,
285
+ routes=None,
286
+ host="",
287
+ port=8000,
288
+ ):
289
+ HTTPServer.__init__(self, (host, port), RequestHandler)
290
+ PyjsApplication.__init__(
291
+ self,
292
+ module,
293
+ css,
294
+ entry_point,
295
+ *entry_point_args,
296
+ render=render,
297
+ routes=routes,
298
+ )
299
+
300
+ def serve_forever(self, poll_interval=0.5):
301
+ print(f"Serving at {_server_url(self.server_address[0], self.server_port)}")
302
+ super().serve_forever(poll_interval)
303
+
304
+
305
+ class WebSocketPyjsServer(PyjsApplication):
306
+ def __init__(
307
+ self,
308
+ module: str,
309
+ css: str,
310
+ entry_point: str,
311
+ *entry_point_args,
312
+ render=None,
313
+ routes=None,
314
+ websocket_routes=None,
315
+ host="",
316
+ port=8000,
317
+ ):
318
+ super().__init__(
319
+ module,
320
+ css,
321
+ entry_point,
322
+ *entry_point_args,
323
+ render=render,
324
+ routes=routes,
325
+ )
326
+ self.websocket_routes = {
327
+ path: self.callback_name(callback)
328
+ for path, callback in (websocket_routes or {}).items()
329
+ }
330
+ self.host = host
331
+ self.server_port = port
332
+ self.started = threading.Event()
333
+ self._loop = None
334
+ self._shutdown_event = None
335
+ self._shutdown_requested = False
336
+
337
+ async def process_request(
338
+ self,
339
+ connection: ServerConnection,
340
+ request: Request,
341
+ ) -> Response | None:
342
+ self.refresh()
343
+ path = urlsplit(request.path).path
344
+ if path in self.websocket_routes:
345
+ return None
346
+ if path == "/":
347
+ server_request = self.create_request("GET", path, request.headers, b"")
348
+ response = ServerResponse(
349
+ page(
350
+ self.get_html(server_request),
351
+ f"{self.entry_point.container.name}.js",
352
+ "index.css",
353
+ ),
354
+ content_type="text/html",
355
+ )
356
+ return websocket_response(response, server_request)
357
+ if path == "/index.css":
358
+ return websocket_response(ServerResponse(self.get_css(), content_type="text/css"))
359
+ if path.endswith(".js"):
360
+ module_name = Path(path).stem
361
+ if module_name not in self.package:
362
+ return websocket_response(ServerResponse("Not found", status=404))
363
+ return websocket_response(
364
+ ServerResponse(self.package[module_name], content_type="application/javascript")
365
+ )
366
+
367
+ server_request = self.create_request("GET", path, request.headers, b"")
368
+ return websocket_response(self.dispatch(server_request), server_request)
369
+
370
+ async def handle_websocket(self, connection: ServerConnection):
371
+ path = urlsplit(connection.request.path).path
372
+ callback_name = self.websocket_routes.get(path)
373
+ if callback_name is None:
374
+ await connection.close(1008, "Unknown WebSocket route")
375
+ return
376
+ await self.resolve_callback(callback_name)(connection)
377
+
378
+ async def run(self):
379
+ self._loop = asyncio.get_running_loop()
380
+ self._shutdown_event = asyncio.Event()
381
+ if self._shutdown_requested:
382
+ self._shutdown_event.set()
383
+ async with websocket_serve(
384
+ self.handle_websocket,
385
+ self.host,
386
+ self.server_port,
387
+ process_request=self.process_request,
388
+ ) as server:
389
+ self.server_port = server.sockets[0].getsockname()[1]
390
+ self.started.set()
391
+ print(f"Serving at {_server_url(self.host, self.server_port)}")
392
+ await self._shutdown_event.wait()
393
+
394
+ def serve_forever(self):
395
+ asyncio.run(self.run())
396
+
397
+ def shutdown(self):
398
+ self._shutdown_requested = True
399
+ if self._loop is not None and self._shutdown_event is not None:
400
+ self._loop.call_soon_threadsafe(self._shutdown_event.set)
401
+
402
+ def server_close(self):
403
+ pass
404
+
405
+
406
+ def create_server(
407
+ module,
408
+ css="",
409
+ entry_point=None,
410
+ *args,
411
+ render=None,
412
+ routes=None,
413
+ websocket_routes=None,
414
+ host="",
415
+ port=8000,
416
+ ):
417
+ if websocket_routes:
418
+ return WebSocketPyjsServer(
419
+ module,
420
+ css,
421
+ entry_point,
422
+ *args,
423
+ render=render,
424
+ routes=routes,
425
+ websocket_routes=websocket_routes,
426
+ host=host,
427
+ port=port,
428
+ )
429
+ return PyjsServer(
430
+ module,
431
+ css,
432
+ entry_point,
433
+ *args,
434
+ render=render,
435
+ routes=routes,
436
+ host=host,
437
+ port=port,
438
+ )
439
+
440
+
441
+ def serve(
442
+ module,
443
+ css="",
444
+ entry_point=None,
445
+ *args,
446
+ render=None,
447
+ routes=None,
448
+ websocket_routes=None,
449
+ host="",
450
+ port=8000,
451
+ ):
452
+ httpd = create_server(
453
+ module,
454
+ css,
455
+ entry_point,
456
+ *args,
457
+ render=render,
458
+ routes=routes,
459
+ websocket_routes=websocket_routes,
460
+ host=host,
461
+ port=port,
462
+ )
463
+ try:
464
+ httpd.serve_forever()
465
+ except KeyboardInterrupt:
466
+ print("\nServer stopped.")
467
+ finally:
468
+ httpd.server_close()
@@ -0,0 +1,161 @@
1
+ ---
2
+ name: pyjs
3
+ description: Build, modify, run, and test PyJS projects, custom elements, UI components, and browser applications written in Python and compiled to JavaScript.
4
+ ---
5
+
6
+ # PyJS
7
+
8
+ Use the installed examples as the source of truth for this version of PyJS.
9
+
10
+ ## Workflow
11
+
12
+ 1. Run `pyjs template` to list the templates registered by installed packages.
13
+ 2. Run `pyjs template NAME` and inspect the closest application or component example. Add `--src`
14
+ to compare it with the transpiled entry-module JavaScript.
15
+ 3. Prefer adapting a working example over inventing framework APIs.
16
+ 4. Create a project with `pyjs create APP [DESTINATION]`, optionally adding `--src-layout` or
17
+ `--template NAME`.
18
+ 5. Add `--single-file` and use a file template when the application should be one Python file.
19
+ 6. Probe language support with `pyjs -c CODE`; add `-v` to inspect generated JavaScript and get a
20
+ compiler traceback if the probe fails.
21
+ 7. Run the Python and relevant platform test targets before considering the work complete.
22
+
23
+ Install the official examples with `python -m pip install "pyjs[examples]"` if no
24
+ `pyjs_examples.*` templates are listed.
25
+
26
+ ```bash
27
+ pyjs create my_app
28
+ pyjs create my_app .
29
+ pyjs create my_app --src-layout
30
+ python -m my_app
31
+ pyjs create calculator_demo --template pyjs_examples.calculator
32
+ pyjs create counter --single-file --template pyjs_examples.counter
33
+ ```
34
+
35
+ For a small, Node-compatible language experiment, avoid creating a temporary file:
36
+
37
+ ```bash
38
+ pyjs -c 'print(1 + 2)'
39
+ pyjs -v -c 'value = 3 * 3; print(value)'
40
+ pyjs --src -c 'print("JavaScript source only")'
41
+ pyjs --src -c 'from pyjs.web.events import Event; print(Event("ready").type)'
42
+ pyjs --src-all app.py
43
+ pyjs --perf -c 'print(sum(range(10)))'
44
+ ```
45
+
46
+ `pyjs FILE.py`, `pyjs -m MODULE`, and `pyjs -c CODE` run generated JavaScript with the managed Node
47
+ runtime. Imports and decorated declarations in a command string are analyzed at module scope, while
48
+ the executable statements become its entry point. `--src` prints only the entry module; use
49
+ `--src-all` when dependency implementations are also relevant. Use `--json` for structured results
50
+ and compilation errors. Browser-only APIs still require a browser test or a served application.
51
+
52
+ ## Documentation
53
+
54
+ Run `pyjs --version`, then replace `VERSION` in these version-matched locations:
55
+
56
+ - Rendered documentation: `https://pyjs.org/docs/VERSION/`
57
+ - Markdown source: `https://github.com/pyjs/pyjs/tree/vVERSION/docs`
58
+
59
+ Prefer released documentation over the `main` branch when behavior may have changed between
60
+ versions. Inspect the installed `pyjs` package and the source and tests exposed by installed
61
+ templates when the documentation does not cover an advanced case.
62
+
63
+ ## Application model
64
+
65
+ - PyJS statically analyzes typed Python and emits JavaScript without a Python runtime.
66
+ - `CustomElement` classes are browser-native custom elements that can also render on the server.
67
+ - Use `@js` for code that must be available in the browser.
68
+ - Treat the custom element and its DOM as application state when that state must survive server
69
+ rendering and hydration.
70
+ - Use `state()` and `@effect(...)` for reactive values when they make imperative DOM updates clearer.
71
+ - Run a standalone application with `python app.py`; a conventional entry point calls
72
+ `serve(__file__)`.
73
+ - Do not edit generated `.main.js`, `.main.css`, or `.main.html` files.
74
+
75
+ ## Tests
76
+
77
+ Small applications may keep tests in the application file:
78
+
79
+ ```bash
80
+ python -m pytest -q app.py
81
+ python -m pytest -q app.py --pyjs-target=web
82
+ python -m pytest -q app.py --pyjs-target=web --pyjs-browser=managed
83
+ ```
84
+
85
+ Pass the filename explicitly because pytest's default discovery only searches `test_*.py` files.
86
+ Browser tests that must be transpiled should be decorated with `@js`. Larger projects may keep
87
+ ordinary and browser tests in a `tests/` directory.
88
+
89
+ Use `--pyjs-browser=managed` for unattended browser verification. It launches headless Chrome and
90
+ automatically adds a screenshot and JSON diagnostics to failed tests. Add `--pyjs-headed` when a
91
+ visible browser is useful. Prefer the reusable `mount`, `bubbling_click`, `press_key`, and
92
+ `selector_count` helpers from `pyjs.testing.web` in browser-compiled tests. Use
93
+ `assert_render(element, "name")` from the same module for stored-image comparisons of ordinary DOM
94
+ elements; create or replace baselines with `--pyjs-update-renders` and review the resulting PNGs.
95
+ Pass `animation_time_ms=` to pause animations at a deterministic capture point, and use
96
+ `await wait_for_frames()` after DOM changes that only need layout and paint to settle.
97
+ Use `await wait_for_event(target, name, trigger)` to arm the listener before a synchronous action.
98
+
99
+ Projects may set recurring browser defaults under `[tool.pytest.ini_options]` using
100
+ `pyjs_browser`, `pyjs_headed`, `pyjs_browser_width`, `pyjs_browser_height`,
101
+ `pyjs_color_scheme`, `pyjs_artifacts_dir`, `pyjs_timeout`, and `pyjs_retained_iframes`.
102
+ Command-line options override project configuration.
103
+
104
+ For a NativeScript Android project, give interactive controls a stable `testID` and use
105
+ `AndroidTestSession` for UI-tree waits, taps, screenshots, and app-scoped logcat. Android tests are
106
+ explicit because they install and drive a real emulator:
107
+
108
+ ```bash
109
+ python -m pytest -q tests --pyjs-target=android --pyjs-android-avd=NAME
110
+ ```
111
+
112
+ Mark them with `pytest.mark.pyjs_android` and wrap assertions in
113
+ `session.artifacts_on_failure(pyjs_artifacts_dir / "android", NAME)`. Inspect both the PNG and XML
114
+ artifacts: the screenshot reveals visual regressions, while the hierarchy gives exact text,
115
+ test IDs, control classes, state, and bounds. The JSON manifest points to those files and the
116
+ app-scoped logcat. See the installed `pyjs_examples.nativescript_counter` tests for the complete
117
+ build, launch, interaction, and capture pattern.
118
+
119
+ Inspect the relevant template for current testing patterns. Normal application tree shaking omits
120
+ unreferenced test functions from the browser bundle.
121
+
122
+ ## Verification
123
+
124
+ For a generated project, start with:
125
+
126
+ ```bash
127
+ python -m pytest -q
128
+ python -m pytest -q --pyjs-target=web
129
+ python app.py
130
+ ```
131
+
132
+ Use the run command from the template's README when the entry point is not `app.py`.
133
+
134
+ ## Visual inspection
135
+
136
+ After starting a web application, use `pyjs inspect` to create both a screenshot and a JSON
137
+ description of the rendered page. Inspect both artifacts: the image catches layout problems, while
138
+ the JSON exposes visible text, interactive elements, geometry, console output, and browser errors.
139
+
140
+ ```bash
141
+ pyjs inspect http://127.0.0.1:8000
142
+ pyjs inspect http://127.0.0.1:8000 --color-scheme dark --width 390 --height 844
143
+ pyjs inspect http://127.0.0.1:8000 --wait-for '[data-testid="results"]'
144
+ pyjs inspect http://127.0.0.1:8000 --selector dialog-window
145
+ ```
146
+
147
+ The default capture waits for fonts, images, finite animations, and two animation frames. Use a
148
+ timed sequence when debugging a transition or animation:
149
+
150
+ ```bash
151
+ pyjs inspect http://127.0.0.1:8000 --no-settle --interval 0.1 --duration 1
152
+ ```
153
+
154
+ Artifacts default to `screenshots/pyjs-inspect.png` and `screenshots/pyjs-inspect.json`. Use
155
+ `--output` to give a task-specific filename and `--json` when another tool will consume the paths.
156
+ For multi-page interaction or project-specific assertions, use `pyjs.tooling.browser` directly;
157
+ the repository's `scripts/capture_*_screenshot.py` scenarios and
158
+ `examples/chatroom/visual_test.py` are working examples.
159
+ Prefer `wait_for_selector`, `wait_for_attribute`, `wait_for_text`, `wait_for_count`, `click`,
160
+ `fill`, `submit`, `attribute`, `attributes`, `text`, and `texts` over embedding JavaScript for
161
+ ordinary DOM interaction.