workpeg 0.149.1__tar.gz → 0.150.0__tar.gz

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 (118) hide show
  1. {workpeg-0.149.1/src/workpeg.egg-info → workpeg-0.150.0}/PKG-INFO +1 -1
  2. {workpeg-0.149.1 → workpeg-0.150.0}/pyproject.toml +1 -1
  3. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/cli.py +11 -7
  4. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/doctor.py +1 -1
  5. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/build.py +395 -28
  6. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/compiler/ast_parser.py +862 -67
  7. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/compiler/js_generator.py +111 -37
  8. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/render_nodes.py +1 -1
  9. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/workpeg-runtime.js +195 -33
  10. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/serve.py +37 -14
  11. {workpeg-0.149.1 → workpeg-0.150.0/src/workpeg.egg-info}/PKG-INFO +1 -1
  12. {workpeg-0.149.1 → workpeg-0.150.0}/LICENSE +0 -0
  13. {workpeg-0.149.1 → workpeg-0.150.0}/MANIFEST.in +0 -0
  14. {workpeg-0.149.1 → workpeg-0.150.0}/README.md +0 -0
  15. {workpeg-0.149.1 → workpeg-0.150.0}/setup.cfg +0 -0
  16. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/__init__.py +0 -0
  17. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/auth.py +0 -0
  18. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/build.py +0 -0
  19. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/cdn.py +0 -0
  20. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/config.py +0 -0
  21. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/context.py +0 -0
  22. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/create_new.py +0 -0
  23. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/project.py +0 -0
  24. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/run.py +0 -0
  25. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/runtime.py +0 -0
  26. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/sandbox/__init__.py +0 -0
  27. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/sandbox/docker_driver.py +0 -0
  28. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/sandbox/driver.py +0 -0
  29. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/submit.py +0 -0
  30. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/__init__.py +0 -0
  31. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/Dockerfile +0 -0
  32. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/LICENSE +0 -0
  33. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/README.md +0 -0
  34. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/app/__init__.py +0 -0
  35. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/app/main.py +0 -0
  36. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/functions/requirements.txt +0 -0
  37. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/README.md +0 -0
  38. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/function/Dockerfile +0 -0
  39. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/function/app/__init__.py +0 -0
  40. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/function/app/main.py +0 -0
  41. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/function/requirements.txt +0 -0
  42. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/ui/main.py +0 -0
  43. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/templates/project/workpeg.json +0 -0
  44. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/__init__.py +0 -0
  45. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/actions.py +0 -0
  46. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/actions_manifest.py +0 -0
  47. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/app.py +0 -0
  48. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/calendar.py +0 -0
  49. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/compiler/__init__.py +0 -0
  50. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/compiler/ir.py +0 -0
  51. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/create.py +0 -0
  52. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/dates.py +0 -0
  53. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/fake_cloud.py +0 -0
  54. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/minify.py +0 -0
  55. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/renderers_manifest.py +0 -0
  56. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/ai-concurrent-replies.md +0 -0
  57. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/ai-prompt-queue.md +0 -0
  58. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/ai-question-frame.md +0 -0
  59. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/ai-subagent-frame.md +0 -0
  60. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/ai.js +0 -0
  61. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/editor.js +0 -0
  62. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/OFL.txt +0 -0
  63. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-italic-cyrillic-ext.af944491.woff2 +0 -0
  64. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-italic-cyrillic.88be6946.woff2 +0 -0
  65. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-italic-latin-ext.370a8962.woff2 +0 -0
  66. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-italic-latin.7611b95c.woff2 +0 -0
  67. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-italic-vietnamese.8dfcf303.woff2 +0 -0
  68. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-normal-cyrillic-ext.b7a545bb.woff2 +0 -0
  69. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-normal-cyrillic.6129fc85.woff2 +0 -0
  70. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-normal-latin-ext.58a6b173.woff2 +0 -0
  71. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-normal-latin.9b6f5ff4.woff2 +0 -0
  72. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/fonts/geist-normal-vietnamese.f689f638.woff2 +0 -0
  73. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/icons.css.gz +0 -0
  74. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/overlay.js +0 -0
  75. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/pegment.css +0 -0
  76. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/runtime/scaffold.js +0 -0
  77. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/scaffold.py +0 -0
  78. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/search_manifest.py +0 -0
  79. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/skills_manifest.py +0 -0
  80. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/state.py +0 -0
  81. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/validators.py +0 -0
  82. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/watcher.py +0 -0
  83. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/__init__.py +0 -0
  84. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/base.py +0 -0
  85. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/canvas.py +0 -0
  86. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/display.py +0 -0
  87. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/fields.py +0 -0
  88. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/forms.py +0 -0
  89. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/futures.py +0 -0
  90. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/gestures.py +0 -0
  91. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/interactive.py +0 -0
  92. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/layout.py +0 -0
  93. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/ui/widgets/pickers.py +0 -0
  94. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg/utils.py +0 -0
  95. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg.egg-info/SOURCES.txt +0 -0
  96. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg.egg-info/dependency_links.txt +0 -0
  97. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg.egg-info/entry_points.txt +0 -0
  98. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg.egg-info/requires.txt +0 -0
  99. {workpeg-0.149.1 → workpeg-0.150.0}/src/workpeg.egg-info/top_level.txt +0 -0
  100. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_auth.py +0 -0
  101. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_build.py +0 -0
  102. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_cdn.py +0 -0
  103. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_cdn_publish.py +0 -0
  104. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_changelog.py +0 -0
  105. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_changelog_guard.py +0 -0
  106. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_cli.py +0 -0
  107. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_config.py +0 -0
  108. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_context.py +0 -0
  109. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_create_new.py +0 -0
  110. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_doctor.py +0 -0
  111. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_project_create.py +0 -0
  112. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_release_script.py +0 -0
  113. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_run.py +0 -0
  114. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_runtime.py +0 -0
  115. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_submit.py +0 -0
  116. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_utils.py +0 -0
  117. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_version.py +0 -0
  118. {workpeg-0.149.1 → workpeg-0.150.0}/tests/test_watch_pipeline.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: workpeg
3
- Version: 0.149.1
3
+ Version: 0.150.0
4
4
  Summary: Workpeg function runtime and SDK
5
5
  Author-email: Workpeg <support@workpeg.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "workpeg"
7
- version = "0.149.1"
7
+ version = "0.150.0"
8
8
  description = "Workpeg function runtime and SDK"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -312,7 +312,7 @@ def build_parser() -> argparse.ArgumentParser:
312
312
  epilog=(
313
313
  "Examples:\n"
314
314
  " workpeg ui build counter/\n"
315
- " workpeg ui build counter/ --out public\n"
315
+ " workpeg ui build counter/ --out build\n"
316
316
  " workpeg ui build counter/main.py\n"
317
317
  ),
318
318
  )
@@ -333,7 +333,7 @@ def build_parser() -> argparse.ArgumentParser:
333
333
  ),
334
334
  )
335
335
 
336
- # Read from the environment so an air-gapped build image sets this once
336
+ # Read from the environment so a dev image or test job sets this once
337
337
  # instead of every build remembering the flag. Read by the CLI, never by
338
338
  # the browser. argparse does not validate an env-supplied default against
339
339
  # choices=, so the ui.build handler re-checks args.chrome itself.
@@ -346,9 +346,9 @@ def build_parser() -> argparse.ArgumentParser:
346
346
  " auto (default) the CDN's current copy, with the app's\n"
347
347
  " bundled copy as the fallback — the Workpeg team's\n"
348
348
  " chrome updates reach the app without a rebuild\n"
349
- " bundled same-origin only, never the network: air-gapped\n"
350
- " installs, a strict script-src 'self' CSP, or a\n"
351
- " byte-pinned deploy\n"
349
+ " bundled same-origin only, never the network: for local\n"
350
+ " development and tests. A released peg is never built\n"
351
+ " this way: it would never receive a chrome update\n"
352
352
  "Env: WORKPEG_CHROME."
353
353
  ),
354
354
  )
@@ -824,6 +824,7 @@ def main(argv=None) -> None:
824
824
  #
825
825
 
826
826
  if args._handler == "ui.new":
827
+ from workpeg.ui.build import PublicAssetError
827
828
  from workpeg.ui.create import ProjectExistsError, create_ui_project
828
829
  from workpeg.ui.compiler.ast_parser import UnsupportedSyntaxError
829
830
 
@@ -838,7 +839,7 @@ def main(argv=None) -> None:
838
839
  except ProjectExistsError as e:
839
840
  print(f"ERROR: {e}", file=sys.stderr)
840
841
  raise SystemExit(2)
841
- except (UnsupportedSyntaxError, SyntaxError) as e:
842
+ except (UnsupportedSyntaxError, SyntaxError, PublicAssetError) as e:
842
843
  print(f"ERROR: {e}", file=sys.stderr)
843
844
  raise SystemExit(2)
844
845
 
@@ -887,6 +888,7 @@ def main(argv=None) -> None:
887
888
  if args._handler == "ui.serve":
888
889
  import pathlib
889
890
 
891
+ from workpeg.ui.build import PublicAssetError
890
892
  from workpeg.ui.compiler.ast_parser import UnsupportedSyntaxError
891
893
  from workpeg.ui.actions_manifest import ActionValidationError
892
894
  from workpeg.ui.search_manifest import ManifestValidationError
@@ -897,6 +899,7 @@ def main(argv=None) -> None:
897
899
  _BUILD_ERRORS = (
898
900
  UnsupportedSyntaxError, SyntaxError,
899
901
  ManifestValidationError, ActionValidationError,
902
+ PublicAssetError,
900
903
  )
901
904
  from workpeg.ui.serve import serve_blocking
902
905
 
@@ -1025,7 +1028,7 @@ def main(argv=None) -> None:
1025
1028
  )
1026
1029
  raise SystemExit(2)
1027
1030
 
1028
- from workpeg.ui.build import build_ui
1031
+ from workpeg.ui.build import PublicAssetError, build_ui
1029
1032
  from workpeg.ui.compiler.ast_parser import UnsupportedSyntaxError
1030
1033
  from workpeg.ui.actions_manifest import ActionValidationError
1031
1034
  from workpeg.ui.search_manifest import ManifestValidationError
@@ -1036,6 +1039,7 @@ def main(argv=None) -> None:
1036
1039
  _BUILD_ERRORS = (
1037
1040
  UnsupportedSyntaxError, SyntaxError,
1038
1041
  ManifestValidationError, ActionValidationError,
1042
+ PublicAssetError,
1039
1043
  )
1040
1044
 
1041
1045
  source_path = pathlib.Path(args.source)
@@ -468,7 +468,7 @@ def _check_env_overrides(ctx: Context) -> Result:
468
468
  f"WORKPEG_CHROME={chrome} is set — every 'workpeg ui build' "
469
469
  f"on this machine defaults to --chrome {chrome}",
470
470
  "unset WORKPEG_CHROME (keep it only if this machine "
471
- "deliberately builds air-gapped images)",
471
+ "builds for local development or tests, never a release)",
472
472
  ))
473
473
  else:
474
474
  findings.append((
@@ -3,18 +3,19 @@ from __future__ import annotations
3
3
  import gzip
4
4
  import hashlib
5
5
  import html
6
+ import itertools
6
7
  import json
7
8
  import os
8
9
  import re
9
10
  import shutil
11
+ import stat
10
12
  import subprocess
11
13
  import sys
12
14
  import tempfile
13
15
  import warnings
14
16
  from pathlib import Path
15
- from urllib.parse import urlparse
16
17
 
17
- from workpeg.ui.compiler.ast_parser import _FONT_HOST_ALLOW, ASTParser
18
+ from workpeg.ui.compiler.ast_parser import ASTParser, _font_url_allowed
18
19
  from workpeg.ui.compiler.js_generator import JSGenerator
19
20
  from workpeg.ui.minify import RUNTIME_BANNER, minify_css, minify_js
20
21
 
@@ -228,16 +229,45 @@ def _subset_icons_css(keep: "set[str]") -> "str | None":
228
229
  #: ``auto`` (the default) takes the CDN's CURRENT copy with the bundled copy
229
230
  #: as the fallback — this is what makes the out-of-band promise true without
230
231
  #: any cooperation from the serving layer. ``bundled`` is same-origin only and
231
- #: never touches the network: air-gapped installs, a strict ``script-src
232
- #: 'self'`` CSP, byte-pinned deploys.
232
+ #: never touches the network. It is for local development and tests: a
233
+ #: released Peg is never built with it, because it would never receive a
234
+ #: chrome update.
233
235
  #:
234
236
  #: The dist carries the bundled copy either way; this only decides whether it
235
- #: is the first choice or the fallback. The decision belongs to whoever ships
236
- #: the Peg — it needs facts only they have — which is why it is a build input
237
- #: baked into the dist, and not something the serving layer, a query string or
238
- #: a runtime global can move.
237
+ #: is the first choice or the fallback. It is a build input baked into the
238
+ #: dist, and not something the serving layer, a query string or a runtime
239
+ #: global can move.
239
240
  CHROME_SOURCES = ("auto", "bundled")
240
241
 
242
+ #: The SDK's own bundles on the CDN: the only script a page may take from off
243
+ #: its own origin. Exact files, never the host, because the CDN serves more
244
+ #: than the SDK. Workpeg._loadOOB asks for these and nothing else, and
245
+ #: test_script_policy holds the two lists together: a loader the policy does
246
+ #: not name would read the refusal as a CDN that is down, and quietly stay on
247
+ #: its bundled copy for good.
248
+ SDK_SCRIPT_URLS = (
249
+ "https://cdn.workpeg.com/ai/ai.js",
250
+ "https://cdn.workpeg.com/scaffold/scaffold.js",
251
+ "https://cdn.workpeg.com/editor/editor.js",
252
+ )
253
+
254
+ #: What every page a build writes says about script, in a <meta> ahead of every
255
+ #: script (DEC-82: a peg is Python only). Fixed, on purpose: no argument, flag
256
+ #: or environment variable reaches it, `bundled` and `workpeg ui serve` carry
257
+ #: the same words, and a host's header can only tighten it. So a script here
258
+ #: never gets 'unsafe-inline' or 'unsafe-eval', or anything wider than these
259
+ #: URLs, for any reason; what seems to need one is a stop-and-ask. Nothing the
260
+ #: SDK puts on a page is inline, so nothing it does needs more.
261
+ #:
262
+ #: A browser ignores the path of a source once a request has been redirected
263
+ #: (CSP3, "paths are ignored after redirects"). So the exact URLs hold only while
264
+ #: nothing on a peg's origin answers a script request with a redirect, and a
265
+ #: host that serves pegs must keep it that way.
266
+ SCRIPT_POLICY = (
267
+ "script-src 'self' " + " ".join(SDK_SCRIPT_URLS)
268
+ + "; object-src 'none'; base-uri 'self'"
269
+ )
270
+
241
271
 
242
272
  def _assert_parses(js: str, source: Path) -> None:
243
273
  """Fail the build if the generated JS does not parse.
@@ -294,6 +324,331 @@ def _assert_parses(js: str, source: Path) -> None:
294
324
  )
295
325
 
296
326
 
327
+ #: What a Peg's ``public/`` can hold, by final suffix, lower-cased.
328
+ #:
329
+ #: A Peg is Python only: the only JavaScript on a page is the SDK's own. This
330
+ #: folder is copied to the Peg's own origin, so a file in it that a browser will
331
+ #: run is a developer's JavaScript, with the same access as the app.
332
+ #:
333
+ #: It is an ALLOW-list because a deny-list has to know every type each browser
334
+ #: runs and every name each publisher mis-types. The obvious seven (.js .mjs
335
+ #: .html .htm .svg .xml .xhtml) left 15 more names that ran script in Chromium,
336
+ #: Firefox and WebKit: Python's mime table calls .rdf .wsdl .xpdl .xsl
337
+ #: application/xml, and a publisher that drops the encoding serves .html.gz and
338
+ #: .svgz as the inner type. Anything new starts out refused, and a suffix joins
339
+ #: this list only once it has been measured inert when opened.
340
+ PUBLIC_SUFFIXES = frozenset({
341
+ ".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".bmp", ".ico",
342
+ ".pdf",
343
+ ".mp3", ".mp4", ".json",
344
+ })
345
+
346
+ #: Files an operating system or git leaves in a folder. They are not content, so
347
+ #: they neither fail a build (one on a Mac would never pass) nor ship.
348
+ _LITTER_NAMES = frozenset({
349
+ ".ds_store", "thumbs.db", "desktop.ini", ".gitkeep", ".gitignore",
350
+ })
351
+
352
+ #: Files that describe the project, by name, in any folder and any case.
353
+ #: ``.json`` is on the list above, so nothing else stops them, and they would go
354
+ #: out at a public URL. A page has no use for one, so it is there by mistake.
355
+ _PROJECT_CONFIG_NAMES = frozenset({"workpeg.json", "package.json", "peg.json"})
356
+
357
+ #: The names a build writes at the site root. ``_sdk_names`` adds whatever else
358
+ #: ``runtime/`` holds.
359
+ _BUILD_WRITES = frozenset({
360
+ "app.js", "workpeg-runtime.js", "pegment.css", "icons.css", "ai.js",
361
+ "scaffold.js", "editor.js", "index.html", "manifest.json",
362
+ })
363
+
364
+ #: Characters that mean something in a URL. The suffix check alone is not enough
365
+ #: for a name holding one: ``mimetypes.guess_type``, which publishers ask for a
366
+ #: Content-Type, reads ``data:text/html,x.png`` as a URL and answers text/html
367
+ #: (Python 3.14 does the same for ``ab:x.html?y.png``), so it would go out as a
368
+ #: page that runs while its suffix says .png.
369
+ _URL_SYNTAX = re.compile(r"[:?#;%\\]")
370
+
371
+ #: How many refusals one error lists. It also stops the walk, because ``--out``
372
+ #: can point at a very large folder by mistake.
373
+ _REFUSALS_SHOWN = 20
374
+
375
+
376
+ class PublicAssetError(ValueError):
377
+ """``public/``, or the folder a build writes to, holds something a Peg
378
+ cannot ship, or could not be read or written to find out."""
379
+
380
+
381
+ def _shown(path: "Path | str") -> str:
382
+ """A path as text that is safe to print. A file name can hold a newline
383
+ that would end the error early, or U+202E, which makes it read as a
384
+ different name, so anything unprintable is shown escaped."""
385
+ text = str(path)
386
+ return text if text.isprintable() else ascii(text)
387
+
388
+
389
+ def _sdk_names() -> "frozenset[str]":
390
+ """The names at the site root that belong to the SDK. Read from the package
391
+ as well as listed, because a list falls behind: a bundle the SDK gains later
392
+ (a PDF viewer and its worker, say) is there on the next build, and being
393
+ refused as a leftover would break every rebuild of the app that uses it."""
394
+ return _BUILD_WRITES | {
395
+ path.name for path in _RUNTIME_JS.parent.iterdir() if path.is_file()
396
+ }
397
+
398
+
399
+ def _walk_no_links(root: Path):
400
+ """Yield ``(path, parts)`` for everything under ``root`` that is not a
401
+ folder it could open, in a stable order. A link is yielded, never followed:
402
+ following one (as ``copytree`` does) ships the bytes of a file outside the
403
+ project under a harmless name, which on a build server reads the host.
404
+
405
+ A folder that will not open is yielded rather than raised, so the refusal
406
+ can name it alongside everything else. It is a loop because a deep enough
407
+ tree would reach Python's recursion limit before any limit on a path."""
408
+ pending = [(str(root), (), True)]
409
+ while pending:
410
+ path, parts, is_folder = pending.pop()
411
+ if not is_folder:
412
+ yield path, parts
413
+ continue
414
+ try:
415
+ with os.scandir(path) as it:
416
+ entries = sorted(it, key=lambda entry: entry.name, reverse=True)
417
+ pending.extend(
418
+ (entry.path, (*parts, entry.name),
419
+ entry.is_dir(follow_symlinks=False))
420
+ for entry in entries)
421
+ except OSError:
422
+ yield path, parts
423
+
424
+
425
+ def _cannot_read(error: OSError) -> str:
426
+ return (f"a build cannot read it ({error.strerror}), so it cannot check "
427
+ "it. Fix the path or its permissions, or remove it.")
428
+
429
+
430
+ def _why_not_shippable(path: str, parts: "tuple[str, ...]") -> "str | None":
431
+ """Why this file cannot ship in a Peg and what to do instead, or None."""
432
+ try:
433
+ # os.lstat and not DirEntry.stat, which leaves st_nlink at 0 on Windows.
434
+ info = os.lstat(path)
435
+ except OSError as error:
436
+ return _cannot_read(error)
437
+ if stat.S_ISLNK(info.st_mode):
438
+ return ("it is a symbolic link, and a build does not follow one. "
439
+ "Replace it with a real file.")
440
+ if stat.S_ISDIR(info.st_mode):
441
+ # The walk only hands back a folder it could not open.
442
+ return ("a build cannot open this folder, so it cannot check what is "
443
+ "in it. Fix its permissions or remove it.")
444
+ if not stat.S_ISREG(info.st_mode):
445
+ return "it is not a regular file. Remove it."
446
+ if info.st_nlink > 1:
447
+ # A second name for bytes that can live anywhere on the disk, which
448
+ # is what refusing a symbolic link is for. A disk does not record which
449
+ # name came first, so every name of the file is refused.
450
+ return ("it is a hard link, so its bytes may be a file outside the "
451
+ "project. Replace it with a real copy.")
452
+ if any(_URL_SYNTAX.search(part) or not part.isprintable() for part in parts):
453
+ return ("its name holds a character that means something in a URL "
454
+ "(: ? # ; % \\) or cannot be printed, so it can be served as a "
455
+ "type its suffix does not say. Rename it.")
456
+ suffix = os.path.splitext(parts[-1])[1].lower()
457
+ if parts[-1].lower() in _PROJECT_CONFIG_NAMES:
458
+ return ("it is your project's config, and this folder is public. Keep "
459
+ "it beside main.py.")
460
+ if suffix in PUBLIC_SUFFIXES:
461
+ try:
462
+ with open(path, "rb"):
463
+ return None
464
+ except OSError as error:
465
+ return _cannot_read(error)
466
+ if suffix in (".js", ".mjs", ".cjs"):
467
+ return ("it is a script, and a Peg is Python only. Move the logic into "
468
+ "your app's Python.")
469
+ if suffix in (".html", ".htm", ".xhtml"):
470
+ return ("a browser opens it as a page that can run script, and a Peg "
471
+ "is Python only. Build the page in Python.")
472
+ if suffix == ".svg":
473
+ return ("an SVG runs script when it is opened. Export it as .png, or "
474
+ "for a logo upload it with `workpeg cdn submit` and draw it "
475
+ "with Logo().")
476
+ return (f"a Peg cannot ship {suffix or 'a file with no suffix'}, because "
477
+ "only types measured safe to open can. Convert it to one that is.")
478
+
479
+
480
+ def _public_problems(public: Path):
481
+ reserved = {name.lower() for name in _sdk_names()}
482
+ for path, parts in _walk_no_links(public):
483
+ name = os.path.basename(path)
484
+ if name.lower() in _LITTER_NAMES or name.startswith("._"):
485
+ continue
486
+ why = _why_not_shippable(path, parts)
487
+ if why is None and parts[0].lower() in reserved:
488
+ why = "the build writes that name itself. Rename it."
489
+ if why is not None:
490
+ yield public.joinpath(*parts), why
491
+
492
+
493
+ def _is_lone_file(path: str) -> bool:
494
+ """A regular file with one name, so a write to it changes nothing else."""
495
+ try:
496
+ info = os.lstat(path)
497
+ except OSError:
498
+ return False
499
+ return stat.S_ISREG(info.st_mode) and info.st_nlink == 1
500
+
501
+
502
+ def _is_vendored_font(parts: "tuple[str, ...]") -> bool:
503
+ return len(parts) == 2 and parts[0] == "fonts" and (
504
+ parts[1].endswith(".woff2") or parts[1] == "OFL.txt")
505
+
506
+
507
+ def _output_problems(out: Path):
508
+ """What a build found in its output folder and did not write. Everything in
509
+ that folder gets uploaded together, so a file planted there, or left by a
510
+ build from before this check, would ship with nothing having looked at it.
511
+
512
+ A file the SDK owns the name of is let through without being looked at,
513
+ which is only safe because ``_clear_sdk_files`` removes it before the build
514
+ writes. Anything other than a lone regular file is judged even then, because
515
+ the write would hang on a FIFO and go through a link to the file behind it.
516
+ """
517
+ if not os.path.isdir(out):
518
+ return
519
+ sdk = _sdk_names()
520
+ for name in sorted(sdk):
521
+ if os.path.isdir(out / name):
522
+ # A file in it is judged by its own name, but an empty one is
523
+ # not seen at all, and the write would die after the whole compile.
524
+ yield out / name, ("it is a folder with the name of a file the "
525
+ "build writes. Remove it.")
526
+ for path, parts in _walk_no_links(out):
527
+ name = os.path.basename(path)
528
+ if _is_lone_file(path):
529
+ if parts == (name,) and name in sdk:
530
+ continue
531
+ if _is_vendored_font(parts):
532
+ continue
533
+ # Exact names only: `._evil.html` here would be uploaded, so it is
534
+ # judged by its suffix, where in public/ it is simply not copied.
535
+ if name.lower() in _LITTER_NAMES:
536
+ continue
537
+ why = _why_not_shippable(path, parts)
538
+ if why is not None:
539
+ yield out.joinpath(*parts), why
540
+
541
+
542
+ def _clear_sdk_files(out: Path) -> None:
543
+ """Remove what ``_output_problems`` let through on its name alone, so that a
544
+ name the SDK owns is only ever what this build writes next.
545
+
546
+ A build writes some of them only when it needs them. Without this, the
547
+ ``manifest.json`` from before an app's last section was taken out, or one
548
+ put there by hand, goes on shipping, and the platform reads it as the Peg's
549
+ own with none of this build's validation.
550
+
551
+ The dev server keeps serving the last good build through a compile error,
552
+ so this runs only once the compile has worked. ``icons.css`` is left to the
553
+ icon step, because a dev build reuses the 26 MB sheet between saves. A folder
554
+ under one of these names was refused before the build began.
555
+ """
556
+ for name in _sdk_names() - {"icons.css"}:
557
+ (out / name).unlink(missing_ok=True)
558
+ fonts = out / "fonts"
559
+ if fonts.is_dir():
560
+ for font in fonts.iterdir():
561
+ if font.is_file() and _is_vendored_font(("fonts", font.name)):
562
+ font.unlink()
563
+
564
+
565
+ def _refuse(problems, heading: str) -> None:
566
+ """Raise if ``problems`` has anything in it, naming every file at once so a
567
+ developer does not rebuild once per file."""
568
+ listed = list(itertools.islice(problems, _REFUSALS_SHOWN + 1))
569
+ if not listed:
570
+ return
571
+ lines = [f" {_shown(path)}: {why}"
572
+ for path, why in listed[:_REFUSALS_SHOWN]]
573
+ if len(listed) > _REFUSALS_SHOWN:
574
+ lines.append(" ...and more.")
575
+ raise PublicAssetError("\n".join((
576
+ heading,
577
+ *lines,
578
+ "A Peg can ship from public/: "
579
+ + " ".join(sorted(PUBLIC_SUFFIXES)) + ".",
580
+ )))
581
+
582
+
583
+ def _same_folder(one: "Path | str", other: "Path | str") -> bool:
584
+ try:
585
+ return os.path.samefile(one, other)
586
+ except OSError:
587
+ return False # It does not exist, so it is not that folder.
588
+
589
+
590
+ def _is_or_is_inside(out: Path, folder: Path) -> bool:
591
+ """Whether ``out`` is ``folder`` or under it, as the disk sees it. Comparing
592
+ the spelling is not enough: ``resolve`` keeps the case that was typed, and
593
+ on a case-insensitive disk, the default on a Mac and on Windows,
594
+ ``Public/sub`` is inside ``public``. ``realpath`` because ``resolve`` raises
595
+ on a link loop before Python 3.13."""
596
+ place = Path(os.path.realpath(out))
597
+ return any(_same_folder(step, folder) for step in (place, *place.parents))
598
+
599
+
600
+ def _check_public_and_output(public: Path, out: Path) -> None:
601
+ """Stop the build if it would ship anything a Peg cannot. This runs before
602
+ anything is written, so a refused build leaves no half of ``public/`` to be
603
+ published by mistake, and the last good build stays in place for the dev
604
+ server to keep serving."""
605
+ if public.is_symlink():
606
+ raise PublicAssetError(
607
+ f"{_shown(public)} is a symbolic link, and a build does not "
608
+ f"follow one. Replace it with a real folder.")
609
+ if os.path.lexists(out) and not os.path.isdir(out):
610
+ raise PublicAssetError(
611
+ f"The output folder {_shown(out)} is not a folder. Build somewhere "
612
+ f"else, for example --out build/.")
613
+ if public.is_dir():
614
+ # Inside public/ there would be no copy for a check to look at: the
615
+ # folder as it stands would be what ships.
616
+ if _is_or_is_inside(out, public):
617
+ raise PublicAssetError(
618
+ f"The output folder {_shown(out)} is {_shown(public)} or inside "
619
+ f"it. That folder holds the files a build copies, so nothing "
620
+ f"would check what ships. Build somewhere else, for example "
621
+ f"--out build/.")
622
+ _refuse(
623
+ _public_problems(public),
624
+ "A Peg is Python only, so the build stopped. These files in "
625
+ "public/ cannot ship:",
626
+ )
627
+ _refuse(
628
+ _output_problems(out),
629
+ "The build stopped. The output folder holds these files, which this "
630
+ "build did not write and a Peg cannot ship. They were left by an "
631
+ "earlier build or put there by hand. Delete them, or delete the "
632
+ "folder and build again:",
633
+ )
634
+ if os.path.isdir(out) and not os.access(out, os.W_OK | os.X_OK):
635
+ raise PublicAssetError(
636
+ f"The build cannot write to the output folder {_shown(out)}. Fix "
637
+ f"its permissions, or build somewhere else, for example --out "
638
+ f"build/.")
639
+
640
+
641
+ def _copy_public(public: Path, out: Path) -> None:
642
+ """Copy what ``_check_public_and_output`` passed to the site root."""
643
+ for path, parts in _walk_no_links(public):
644
+ name = os.path.basename(path)
645
+ if name.lower() in _LITTER_NAMES or name.startswith("._"):
646
+ continue
647
+ target = out.joinpath(*parts)
648
+ target.parent.mkdir(parents=True, exist_ok=True)
649
+ shutil.copy2(path, target, follow_symlinks=False)
650
+
651
+
297
652
  def build_ui(
298
653
  source_path: str,
299
654
  output_dir: str = "dist",
@@ -309,21 +664,33 @@ def build_ui(
309
664
  f'got {chrome_source!r}')
310
665
  source = Path(source_path)
311
666
  out = Path(output_dir)
312
- out.mkdir(parents=True, exist_ok=True)
313
667
 
314
- # Static assets: anything in the project's ``public/`` directory is copied to
315
- # the site root (e.g. ``public/sample.pdf`` → ``/sample.pdf``), so an app can
316
- # ship images, PDFs, fonts, etc. alongside its code and ``workpeg ui serve``
317
- # serves them as-is. Copied first so the compiled output below always wins on
318
- # a name clash (a stray ``public/app.js`` can't shadow the real one).
668
+ # Static assets: what the project's ``public/`` directory holds is copied to
669
+ # the site root (e.g. ``public/sample.pdf`` -> ``/sample.pdf``), so an app
670
+ # can ship images and PDFs alongside its code and ``workpeg ui serve`` serves
671
+ # them as-is. Only what a browser cannot run gets this far: see
672
+ # PUBLIC_SUFFIXES.
319
673
  public = source.parent / "public"
320
- if public.is_dir():
321
- shutil.copytree(public, out, dirs_exist_ok=True)
674
+ _check_public_and_output(public, out)
675
+ try:
676
+ out.mkdir(parents=True, exist_ok=True)
677
+ if public.is_dir():
678
+ _copy_public(public, out)
679
+ except OSError as error:
680
+ # Each side can pass the check and still collide: dist/a.png from an
681
+ # earlier build, and a new folder public/a.png/ to copy.
682
+ raise PublicAssetError(
683
+ f"The build could not write to the output folder {_shown(out)}: "
684
+ f"{_shown(str(error))}") from error
322
685
 
323
686
  parser = ASTParser()
324
687
  ir = parser.parse_file(str(source))
325
688
  gen = JSGenerator()
326
- js = gen.generate(ir)
689
+ # A block, so a peg's classes are its own. app.js is a classic script, and a
690
+ # class at the top level of one is a binding in the scope every script on the
691
+ # page shares: `class URL(Component)` replaced the browser's URL for the
692
+ # runtime's check of which hosts get credentials, and for the chrome.
693
+ js = "{\n" + gen.generate(ir) + "\n}\n"
327
694
  runtime = _RUNTIME_JS.read_text(encoding="utf-8")
328
695
 
329
696
  if minify:
@@ -383,6 +750,7 @@ def build_ui(
383
750
  # on disk from the `ver` hash above — computed on the untranslated string,
384
751
  # so the ?v= cache-buster would stop describing what is served — and
385
752
  # (b) make a dist's bytes depend on the machine that built it.
753
+ _clear_sdk_files(out)
386
754
  (out / "app.js").write_text(js, encoding="utf-8", newline="\n")
387
755
  (out / "workpeg-runtime.js").write_text(
388
756
  runtime, encoding="utf-8", newline="\n")
@@ -437,6 +805,9 @@ def build_ui(
437
805
  or target.stat().st_mtime < _ICONS_CSS.stat().st_mtime):
438
806
  shutil.copy2(_ICONS_CSS, target)
439
807
  icons_ver = _icons_version(True)
808
+ if icons_href != ICONS_HREF:
809
+ # Nothing links it, and everything in this folder gets uploaded.
810
+ (out / "icons.css").unlink(missing_ok=True)
440
811
  (out / "index.html").write_text(
441
812
  _gen_html(
442
813
  ir.name, ns, ver,
@@ -888,14 +1259,7 @@ def _font_links(fonts: "list[str] | None") -> str:
888
1259
  """
889
1260
  if not fonts:
890
1261
  return ""
891
- allowed = []
892
- for url in fonts:
893
- parsed = urlparse(url)
894
- if parsed.scheme != "https" or parsed.hostname not in _FONT_HOST_ALLOW:
895
- continue # off-allowlist → never emit
896
- if any(c.isspace() for c in url):
897
- continue # cannot be a valid URL either way
898
- allowed.append(url)
1262
+ allowed = [url for url in fonts if _font_url_allowed(url)]
899
1263
  if not allowed:
900
1264
  return ""
901
1265
  links = _FONT_PRECONNECT
@@ -954,9 +1318,8 @@ def _gen_html(
954
1318
  # departs from the default, so `grep data-chrome dist/index.html` answers
955
1319
  # "where does this app's chrome come from?" and silence means the default.
956
1320
  # An attribute, not an inline script: this function's contract is that the
957
- # build never emits arbitrary CSS or JS, and that rule is what lets a Peg
958
- # ship a strict CSP — one of the reasons to choose `bundled` in the first
959
- # place.
1321
+ # build never emits arbitrary CSS or JS, and SCRIPT_POLICY would refuse an
1322
+ # inline script if it did.
960
1323
  chrome_attr = ' data-chrome="bundled"' if chrome_source == "bundled" else ""
961
1324
  # Warm the connection for the chrome fetch that happens on the next tick.
962
1325
  # No `crossorigin` — it must match the (non-CORS) script fetch or the
@@ -974,10 +1337,14 @@ def _gen_html(
974
1337
  head_links = (
975
1338
  f"{ns_meta}{chrome_pre}{pegment}{icons}{font_links}"
976
1339
  )
1340
+ # The policy goes straight after the charset. A <meta> policy governs only
1341
+ # what comes after it, so nothing the build fills in from a name, and no
1342
+ # script, stands ahead of it.
977
1343
  return f"""<!DOCTYPE html>
978
1344
  <html lang="en">
979
1345
  <head>
980
1346
  <meta charset="UTF-8">
1347
+ <meta http-equiv="Content-Security-Policy" content="{SCRIPT_POLICY}">
981
1348
  <meta name="viewport" content="width=device-width, initial-scale=1.0">{head_links}
982
1349
  <title>{html.escape(app_name)}</title>
983
1350
  </head>