Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
1301 lines (1145 loc) · 57.7 KB
/
Copy pathbuild.py
File metadata and controls
1301 lines (1145 loc) · 57.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Build the TendExtensions registry.
For every folder under `extensions/`:
1. Load `extension.json` and `listing.json`.
2. Rebuild the manifest's `integrity` map from the files actually on disk
(every shipped file except `extension.json` and `listing.json` itself)
and rewrite `extension.json` in place — the integrity map is generated,
never hand-edited.
3. Validate the manifest against the same rules the panel enforces
(re-implemented here; this script never imports the panel at runtime —
see `validate_with_panel.py` for that). A non-theme package must also
declare a conforming `glyph` (docs/icons.md); a theme pack must not.
4. Build a deterministic ZIP at `dist/<id>-<version>.zip` (sorted
members, fixed mtime, no directory entries, no dotfiles, no
`listing.json` inside the archive, manifest at the root).
Then writes `dist/registry.json` (schema 1) covering every extension,
sorted by id. `--sequence`/`--revision` override the git-derived defaults
(`git rev-list --count HEAD` / `git rev-parse HEAD`) for tests and for CI
runs on a shallow or detached checkout.
Running this script twice against an unchanged `extensions/` tree produces
byte-identical ZIPs (registry.json legitimately differs — it carries
`generated_at`).
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import math
import re
import subprocess
import sys
import time
import zipfile
from pathlib import Path
from typing import Any
from PIL import Image
try: # imported as `tools.build` (tests) or run as `python tools/build.py`
from tools import component_listing
from tools import glyph as glyph_rules
from tools import validate_recipe as recipe_rules
except ImportError: # pragma: no cover - script mode puts tools/ itself on sys.path
import component_listing
import glyph as glyph_rules
import validate_recipe as recipe_rules
REPO_ROOT = Path(__file__).resolve().parent.parent
# ---------- re-implementation of the panel's manifest rules ----------
# Mirrors app.services.extensions.parse_manifest in the Tend panel core
# (backend/app/services/extensions.py). Kept in sync by hand; a stricter,
# ground-truth check against the real panel code runs in
# validate_with_panel.py.
_ID_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._\-]{1,127}$")
_VERSION_RE = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")
KNOWN_PERMISSIONS = {
"storage",
"notifications",
"network",
"email",
"mascot",
"files.read",
"documents.read",
"documents.write",
"documents.backup",
"sites.source.read",
"sites.source.connect",
"sites.source.write",
"sites.create",
"sites.preview",
"sites.publish",
"ondacast",
}
KNOWN_UI_KINDS = {"shell-app", "tool-window"}
KNOWN_RUNTIME_KINDS = {"game", "utility"}
KNOWN_CATEGORIES = {
"games",
"utilities",
"productivity",
"media",
"developer-tools",
"communication",
"themes",
"other",
}
KNOWN_RUNTIME_MODULES = {"phaser@4"}
KNOWN_RUNTIME_KEYS = {"api", "kind", "modules", "pauseWhenHidden", "targetFps"}
# ---------- shelf widgets (schema-2 only) ----------
# Mirrors app.services.extensions._parse_widgets in the panel core: same
# field rules, same normalized shape. A package that fails this never
# reaches validate_with_panel.py's ground-truth check.
KNOWN_WIDGET_SIZES = ("small", "wide")
KNOWN_WIDGET_KEYS = {"id", "name", "description", "sizes", "module", "preview"}
MAX_WIDGETS_PER_EXTENSION = 8
MAX_WIDGET_NAME_CHARS = 60
MAX_WIDGET_DESCRIPTION_CHARS = 160
WIDGET_MODULE_SUFFIXES = (".js", ".mjs")
WIDGET_PREVIEW_SUFFIXES = (".svg", ".png", ".webp")
_WIDGET_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
# ---------- Sprout tools (schema-2 only) ----------
# Mirrors tools.ParseSproutTools in the panel core (internal/assistant/tools/
# extension_tools.go): same limits, same sentences' intent. The text of a
# tool description reaches the model, so the rules are strict. A package that
# fails this never reaches validate_with_panel.py's ground-truth check.
SPROUT_KINDS = ("read", "ui", "act")
MAX_SPROUT_TOOLS = 8
SPROUT_DESCRIPTION_CHARS = (20, 240)
MAX_SPROUT_DOING_CHARS = 40
MAX_SPROUT_PROPERTIES = 6
MAX_SPROUT_STRING_LENGTH = 120
MAX_SPROUT_ENUM = 12
MAX_SPROUT_ENUM_CHARS = 32
MAX_SPROUT_PROP_DESCRIPTION_CHARS = 120
MAX_SPROUT_INPUT_BYTES = 1024
SPROUT_DENIED_PHRASES = (
"ignore previous", "system prompt", "you are", "assistant:", "developer:", "instructions",
)
_SPROUT_TOOL_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{1,23}$")
_SPROUT_PROP_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,23}$")
# ---------- theme packs (schema-2, category "themes") ----------
# Mirrors the panel core's theme-pack rules (THEME_CONTRACT v1): a pack is a
# declarative `theme` object plus images, never code. Every value that ends up
# in CSS passes the closed colour grammar below; nothing free-form is accepted.
THEME_CATEGORY = "themes"
THEME_API = 1
THEME_MODES = ("dark", "light")
THEME_POSITIONS = ("center", "top", "bottom", "left", "right")
THEME_SHAPES = ("sharp", "default", "round")
THEME_LABELS = ("light", "dark")
THEME_IMAGE_SUFFIXES = (".webp", ".jpg", ".jpeg", ".png")
THEME_FORBIDDEN_SUFFIXES = (".js", ".mjs", ".html", ".htm", ".css", ".svg", ".wasm")
THEME_FORBIDDEN_MANIFEST_KEYS = ("ui", "runtime", "widgets")
THEME_MAX_WALLPAPER_BYTES = 4 * 1024 * 1024
THEME_MAX_THUMB_BYTES = 512 * 1024
THEME_THUMB_WIDTH = 480
THEME_THUMB_HEIGHT = (240, 320)
THEME_WALLPAPER_WIDTH = (1600, 4096)
THEME_WALLPAPER_HEIGHT = (900, 2560)
THEME_MAX_GLOWS = 4
THEME_MIN_CONTRAST = 4.5
THEME_MAX_PATH_CHARS = 128
THEME_MAX_COLOR_CHARS = 64
THEME_MAX_NAME_CHARS = 40
THEME_MAX_DESCRIPTION_CHARS = 160
_NUM = r"\d{1,3}(?:\.\d{1,4})?"
_OKLCH_RE = re.compile(
rf"^oklch\(\s*({_NUM})%\s+({_NUM})\s+({_NUM})(?:\s*/\s*(\d(?:\.\d{{1,4}})?))?\s*\)$"
)
_HEX_RE = re.compile(r"^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$")
KNOWN_THEME_KEYS = {"api", "modes", "wallpaper", "palette", "surface", "icons", "shell"}
KNOWN_WALLPAPER_KEYS = {"image", "thumb", "position", "veil", "gradient", "fallback"}
KNOWN_PALETTE_KEYS = {"primary", "secondary", "primaryContent", "highlight"}
KNOWN_SHELL_KEYS = {"topBar", "glass", "shape", "desktopLabels", "shadow", "wallpaperDim"}
def _theme_error(ext_id: str, where: str, message: str) -> BuildError:
return BuildError(f"{ext_id}: theme{'.' + where if where else ''}: {message}")
def _theme_object(raw: object, allowed: set[str], *, ext_id: str, where: str) -> dict[str, Any]:
if not isinstance(raw, dict):
raise _theme_error(ext_id, where, "must be an object")
unknown = sorted(set(raw) - allowed)
if unknown:
raise _theme_error(ext_id, where, f"unknown key(s): {', '.join(unknown)}")
return raw
def _theme_number(raw: object, lo: float, hi: float, *, ext_id: str, where: str) -> float:
if isinstance(raw, bool) or not isinstance(raw, (int, float)) or not math.isfinite(raw):
raise _theme_error(ext_id, where, "must be a JSON number")
if not lo <= raw <= hi:
raise _theme_error(ext_id, where, f"must be between {lo} and {hi}, got {raw!r}")
return float(raw)
def _theme_enum(raw: object, allowed: tuple[str, ...], *, ext_id: str, where: str) -> str:
if not isinstance(raw, str) or raw not in allowed:
raise _theme_error(ext_id, where, f"must be one of {list(allowed)}")
return raw
def parse_theme_color(raw: object, *, ext_id: str, where: str) -> tuple[float, float, float]:
"""Validate a `<color>` against the closed grammar and return its
approximate sRGB triple (0..1, gamut-clipped, alpha ignored)."""
if not isinstance(raw, str):
raise _theme_error(ext_id, where, "colour must be a string")
text = raw.strip().lower()
if len(text) > THEME_MAX_COLOR_CHARS:
raise _theme_error(ext_id, where, f"colour is longer than {THEME_MAX_COLOR_CHARS} characters")
match = _OKLCH_RE.fullmatch(text)
if match:
lightness, chroma, hue = (float(match.group(i)) for i in (1, 2, 3))
alpha = match.group(4)
if lightness > 100 or chroma > 0.4 or hue > 360 or (alpha is not None and float(alpha) > 1):
raise _theme_error(
ext_id, where, f"oklch out of range (L 0-100%, C 0-0.4, H 0-360, A 0-1): {raw!r}"
)
return _oklch_to_srgb(lightness / 100, chroma, hue)
if _HEX_RE.fullmatch(text):
digits = text[1:]
if len(digits) in (3, 4):
digits = "".join(c * 2 for c in digits)
return tuple(int(digits[i : i + 2], 16) / 255 for i in (0, 2, 4)) # type: ignore[return-value]
raise _theme_error(
ext_id, where, f"colour must be oklch(L% C H [/ A]) or #rgb/#rrggbb/#rrggbbaa, got {raw!r}"
)
def _oklch_to_srgb(lightness: float, chroma: float, hue: float) -> tuple[float, float, float]:
a = chroma * math.cos(math.radians(hue))
b = chroma * math.sin(math.radians(hue))
l_ = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3
m_ = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3
s_ = (lightness - 0.0894841775 * a - 1.2914855480 * b) ** 3
linear = (
4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
-1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
-0.0041960863 * l_ - 0.7034186147 * m_ + 1.7076147010 * s_,
)
def encode(c: float) -> float:
c = max(0.0, min(1.0, c))
return 12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055
return tuple(encode(c) for c in linear) # type: ignore[return-value]
def _relative_luminance(rgb: tuple[float, float, float]) -> float:
def lin(c: float) -> float:
return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
r, g, b = (lin(c) for c in rgb)
return 0.2126 * r + 0.7152 * g + 0.0722 * b
def contrast_ratio(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
la, lb = _relative_luminance(a), _relative_luminance(b)
hi, lo = max(la, lb), min(la, lb)
return (hi + 0.05) / (lo + 0.05)
def _theme_path(raw: object, suffixes: tuple[str, ...], integrity: dict[str, Any], *, ext_id: str, where: str) -> str:
if not isinstance(raw, str) or not raw:
raise _theme_error(ext_id, where, "must be a package-relative file path")
if (
len(raw) > THEME_MAX_PATH_CHARS
or "\\" in raw
or ":" in raw
or raw.startswith("/")
or any(part in ("", ".", "..") for part in raw.split("/"))
):
raise _theme_error(
ext_id, where, f"must be a relative '/'-separated path inside the package (no '..', no ':'), got {raw!r}"
)
if not raw.lower().endswith(suffixes):
raise _theme_error(ext_id, where, f"must end with one of {', '.join(suffixes)}, got {raw!r}")
if raw not in integrity:
raise _theme_error(ext_id, where, f"{raw!r} is not covered by the integrity map (file must exist in the package)")
return raw
def _validate_mode_map(
raw: object, *, ext_id: str, where: str, required: bool, check: Any
) -> None:
# Contract Addendum B: every per-mode object (veil, fallback, gradient,
# topBar.tint, palette) needs both modes. `required` is kept for call-site
# readability; a present map is always complete.
obj = _theme_object(raw, set(THEME_MODES), ext_id=ext_id, where=where)
for mode in THEME_MODES:
if mode not in obj:
raise _theme_error(ext_id, where, f"missing '{mode}'")
check(obj[mode], f"{where}.{mode}")
def validate_theme(manifest: dict[str, Any], ext_id: str) -> None:
"""Validate a theme pack's manifest (the `theme` block and the rules
around it). File-level rules (sizes, magic bytes, forbidden files) live in
`validate_theme_files`."""
theme = manifest.get("theme")
is_theme_category = manifest.get("category") == THEME_CATEGORY
if theme is None:
if is_theme_category:
raise BuildError(f"{ext_id}: category 'themes' requires a 'theme' object")
return
if not is_theme_category:
raise BuildError(f"{ext_id}: a 'theme' object requires category 'themes'")
if manifest.get("schema") != 2:
raise BuildError(f"{ext_id}: theme packs require schema 2")
if manifest.get("permissions"):
raise BuildError(f"{ext_id}: a theme pack must declare no permissions")
if len(manifest["name"]) > THEME_MAX_NAME_CHARS:
raise BuildError(f"{ext_id}: theme pack 'name' must be at most {THEME_MAX_NAME_CHARS} characters")
description = manifest.get("description", "")
if not isinstance(description, str) or len(description) > THEME_MAX_DESCRIPTION_CHARS:
raise BuildError(
f"{ext_id}: theme pack 'description' must be a string of at most {THEME_MAX_DESCRIPTION_CHARS} characters"
)
integrity = manifest["integrity"]
def color(raw: object, where: str) -> tuple[float, float, float]:
return parse_theme_color(raw, ext_id=ext_id, where=where)
def number(raw: object, lo: float, hi: float, where: str) -> float:
return _theme_number(raw, lo, hi, ext_id=ext_id, where=where)
theme = _theme_object(theme, KNOWN_THEME_KEYS, ext_id=ext_id, where="")
if theme.get("api") != THEME_API or isinstance(theme.get("api"), bool):
raise _theme_error(ext_id, "api", f"must be {THEME_API}")
if "modes" in theme:
modes = theme["modes"]
if (
not isinstance(modes, list)
or not modes
or not all(isinstance(m, str) and m in THEME_MODES for m in modes)
or len(set(modes)) != len(modes)
):
raise _theme_error(ext_id, "modes", f"must be a non-empty list of distinct values from {list(THEME_MODES)}")
# wallpaper
wallpaper = _theme_object(theme.get("wallpaper"), KNOWN_WALLPAPER_KEYS, ext_id=ext_id, where="wallpaper")
has_image, has_gradient = "image" in wallpaper, "gradient" in wallpaper
if has_image == has_gradient:
raise _theme_error(ext_id, "wallpaper", "must set exactly one of 'image' or 'gradient'")
if has_image:
_theme_path(wallpaper["image"], THEME_IMAGE_SUFFIXES, integrity, ext_id=ext_id, where="wallpaper.image")
else:
# Photo-only fields, refused on a gradient pack exactly as the panel core does.
for key in ("position", "veil", "fallback"):
if key in wallpaper:
raise _theme_error(ext_id, f"wallpaper.{key}", "only applies to an image wallpaper, not a gradient")
if "thumb" not in wallpaper:
raise _theme_error(ext_id, "wallpaper.thumb", "is required (the store and picker preview)")
_theme_path(wallpaper["thumb"], THEME_IMAGE_SUFFIXES, integrity, ext_id=ext_id, where="wallpaper.thumb")
if "position" in wallpaper:
_theme_enum(wallpaper["position"], THEME_POSITIONS, ext_id=ext_id, where="wallpaper.position")
def check_veil(raw: object, where: str) -> None:
veil = _theme_object(raw, {"color", "top", "middle", "bottom"}, ext_id=ext_id, where=where)
if set(veil) != {"color", "top", "middle", "bottom"}:
raise _theme_error(ext_id, where, "needs color, top, middle and bottom")
color(veil["color"], f"{where}.color")
for key in ("top", "middle", "bottom"):
number(veil[key], 0, 1, f"{where}.{key}")
if "veil" in wallpaper:
_validate_mode_map(wallpaper["veil"], ext_id=ext_id, where="wallpaper.veil", required=False, check=check_veil)
def check_gradient(raw: object, where: str) -> None:
grad = _theme_object(raw, {"base", "glows"}, ext_id=ext_id, where=where)
if "base" not in grad:
raise _theme_error(ext_id, where, "needs a 'base' colour")
color(grad["base"], f"{where}.base")
glows = grad.get("glows", [])
if not isinstance(glows, list) or len(glows) > THEME_MAX_GLOWS:
raise _theme_error(ext_id, f"{where}.glows", f"must be a list of at most {THEME_MAX_GLOWS} glows")
for i, glow in enumerate(glows):
gwhere = f"{where}.glows[{i}]"
glow = _theme_object(glow, {"x", "y", "w", "h", "color", "alpha"}, ext_id=ext_id, where=gwhere)
if set(glow) != {"x", "y", "w", "h", "color", "alpha"}:
raise _theme_error(ext_id, gwhere, "needs x, y, w, h, color and alpha")
number(glow["x"], 0, 100, f"{gwhere}.x")
number(glow["y"], 0, 100, f"{gwhere}.y")
number(glow["w"], 10, 150, f"{gwhere}.w")
number(glow["h"], 10, 150, f"{gwhere}.h")
number(glow["alpha"], 0, 1, f"{gwhere}.alpha")
color(glow["color"], f"{gwhere}.color")
if has_gradient:
_validate_mode_map(
wallpaper["gradient"], ext_id=ext_id, where="wallpaper.gradient", required=True, check=check_gradient
)
if "fallback" in wallpaper:
_validate_mode_map(
wallpaper["fallback"], ext_id=ext_id, where="wallpaper.fallback", required=False,
check=lambda raw, where: color(raw, where),
)
# palette
def check_palette(raw: object, where: str) -> None:
pal = _theme_object(raw, KNOWN_PALETTE_KEYS, ext_id=ext_id, where=where)
for key in ("primary", "secondary", "primaryContent"):
if key not in pal:
raise _theme_error(ext_id, where, f"missing '{key}'")
colours = {key: color(value, f"{where}.{key}") for key, value in pal.items()}
ratio = contrast_ratio(colours["primary"], colours["primaryContent"])
if ratio < THEME_MIN_CONTRAST:
raise _theme_error(
ext_id, where,
f"primary/primaryContent contrast is {ratio:.2f}:1, needs at least {THEME_MIN_CONTRAST}:1",
)
if "palette" not in theme:
raise _theme_error(ext_id, "palette", "is required")
_validate_mode_map(theme["palette"], ext_id=ext_id, where="palette", required=True, check=check_palette)
if "surface" in theme:
surface = _theme_object(theme["surface"], {"hue", "chroma"}, ext_id=ext_id, where="surface")
for key in ("hue", "chroma"):
if key not in surface:
raise _theme_error(ext_id, f"surface.{key}", "is required when 'surface' is set")
number(surface["hue"], 0, 360, "surface.hue")
number(surface["chroma"], 0, 0.05, "surface.chroma")
if "icons" in theme:
icons = _theme_object(theme["icons"], {"hueRotate", "saturate", "brightness"}, ext_id=ext_id, where="icons")
if "hueRotate" in icons:
number(icons["hueRotate"], -180, 180, "icons.hueRotate")
if "saturate" in icons:
number(icons["saturate"], 0, 2, "icons.saturate")
if "brightness" in icons:
number(icons["brightness"], 0.5, 1.5, "icons.brightness")
if "shell" in theme:
shell = _theme_object(theme["shell"], KNOWN_SHELL_KEYS, ext_id=ext_id, where="shell")
if "topBar" in shell:
bar = _theme_object(shell["topBar"], {"opacity", "tint"}, ext_id=ext_id, where="shell.topBar")
if not bar:
raise _theme_error(ext_id, "shell.topBar", "must set 'opacity', 'tint', or both")
if "opacity" in bar:
number(bar["opacity"], 0.4, 1, "shell.topBar.opacity")
if "tint" in bar:
_validate_mode_map(
bar["tint"], ext_id=ext_id, where="shell.topBar.tint", required=False,
check=lambda raw, where: color(raw, where),
)
if "glass" in shell:
glass = _theme_object(shell["glass"], {"blur", "saturate"}, ext_id=ext_id, where="shell.glass")
for key in ("blur", "saturate"):
if key not in glass:
raise _theme_error(ext_id, f"shell.glass.{key}", "is required when 'glass' is set")
number(glass["blur"], 0, 40, "shell.glass.blur")
number(glass["saturate"], 1, 2, "shell.glass.saturate")
if "shape" in shell:
_theme_enum(shell["shape"], THEME_SHAPES, ext_id=ext_id, where="shell.shape")
if "desktopLabels" in shell:
_theme_enum(shell["desktopLabels"], THEME_LABELS, ext_id=ext_id, where="shell.desktopLabels")
if "shadow" in shell:
number(shell["shadow"], 0, 1, "shell.shadow")
if "wallpaperDim" in shell:
number(shell["wallpaperDim"], 0, 0.85, "shell.wallpaperDim")
def _image_matches_extension(head: bytes, suffix: str) -> bool:
if suffix == ".webp":
return head[:4] == b"RIFF" and head[8:12] == b"WEBP"
if suffix in (".jpg", ".jpeg"):
return head[:3] == b"\xff\xd8\xff"
if suffix == ".png":
return head[:8] == b"\x89PNG\r\n\x1a\n"
return False
def _read_image_size(path: Path, *, ext_id: str, field: str, rel: str) -> tuple[int, int]:
"""Image dimensions from the header only (PIL reads no pixels here). An
unreadable header is refused, like the panel does."""
try:
with Image.open(path) as img:
width, height = img.size
except Exception as exc: # noqa: BLE001 - PIL raises several types for bad headers
raise BuildError(f"{ext_id}: theme.wallpaper.{field} {rel!r} has an unreadable image header ({exc.__class__.__name__})") from exc
return int(width), int(height)
def validate_theme_files(ext_dir: Path, manifest: dict[str, Any]) -> None:
"""File-level theme-pack rules: no executable or markup files, and the
images the theme references are real images of the right size."""
if not isinstance(manifest.get("theme"), dict):
return
ext_id = ext_dir.name
for _, rel in package_files(ext_dir):
if rel.lower().endswith(THEME_FORBIDDEN_SUFFIXES):
raise BuildError(
f"{ext_id}: a theme pack must not ship {rel!r} "
f"(no {', '.join(THEME_FORBIDDEN_SUFFIXES)} files)"
)
wallpaper = manifest["theme"]["wallpaper"]
for field, limit in (("image", THEME_MAX_WALLPAPER_BYTES), ("thumb", THEME_MAX_THUMB_BYTES)):
rel = wallpaper.get(field)
if rel is None:
continue
path = ext_dir / rel
size = path.stat().st_size
if size > limit:
raise BuildError(f"{ext_id}: theme.wallpaper.{field} {rel!r} is {size} bytes, over the {limit}-byte limit")
with path.open("rb") as handle:
head = handle.read(32)
if not _image_matches_extension(head, Path(rel).suffix.lower()):
raise BuildError(f"{ext_id}: theme.wallpaper.{field} {rel!r} is not a valid {Path(rel).suffix.lower()} image")
width, height = _read_image_size(path, ext_id=ext_id, field=field, rel=rel)
if field == "thumb":
if width != THEME_THUMB_WIDTH or not THEME_THUMB_HEIGHT[0] <= height <= THEME_THUMB_HEIGHT[1]:
raise BuildError(
f"{ext_id}: {rel} is {width}x{height}; a theme pack thumbnail must be "
f"{THEME_THUMB_WIDTH} px wide and {THEME_THUMB_HEIGHT[0]}-{THEME_THUMB_HEIGHT[1]} px tall"
)
elif (
not THEME_WALLPAPER_WIDTH[0] <= width <= THEME_WALLPAPER_WIDTH[1]
or not THEME_WALLPAPER_HEIGHT[0] <= height <= THEME_WALLPAPER_HEIGHT[1]
or width <= height
):
raise BuildError(
f"{ext_id}: {rel} is {width}x{height}; a theme pack wallpaper must be "
f"{THEME_WALLPAPER_WIDTH[0]}-{THEME_WALLPAPER_WIDTH[1]} px wide, "
f"{THEME_WALLPAPER_HEIGHT[0]}-{THEME_WALLPAPER_HEIGHT[1]} px tall and landscape (wider than tall)"
)
# Files never shipped inside the ZIP or covered by the integrity map.
_LISTING_NAME = "listing.json"
_MANIFEST_NAME = "extension.json"
class BuildError(Exception):
"""A problem with an extension's manifest, listing, or on-disk files.
Raised with a message specific enough to fix without re-reading this
script."""
def _valid_id(ext_id: str) -> bool:
if not isinstance(ext_id, str) or not _ID_RE.match(ext_id):
return False
return "/" not in ext_id and "\\" not in ext_id and ".." not in ext_id
def validate_manifest(manifest: dict[str, Any], *, ext_id_hint: str) -> None:
"""Raise BuildError on anything the panel's parse_manifest would also
reject. Assumes `manifest["integrity"]` already reflects the files on
disk (rebuild_integrity runs before this)."""
if not isinstance(manifest, dict):
raise BuildError(f"{ext_id_hint}: extension.json must be a JSON object")
schema = manifest.get("schema", 1)
if schema not in (1, 2):
raise BuildError(f"{ext_id_hint}: 'schema' must be 1 or 2, got {schema!r}")
for field in ("id", "name", "version"):
if not isinstance(manifest.get(field), str) or not manifest[field].strip():
raise BuildError(f"{ext_id_hint}: missing required field '{field}'")
if manifest["id"] != ext_id_hint:
raise BuildError(
f"{ext_id_hint}: manifest id {manifest['id']!r} does not match its folder name"
)
if not _valid_id(manifest["id"]):
raise BuildError(
f"{ext_id_hint}: 'id' must be reverse-DNS-style "
"(letters, digits, dots, dashes, underscores; 2-128 chars)"
)
if not _VERSION_RE.match(manifest["version"]):
raise BuildError(
f"{ext_id_hint}: 'version' must be strict x.y.z, got {manifest['version']!r}"
)
if manifest.get("category") == THEME_CATEGORY or "theme" in manifest:
for key in THEME_FORBIDDEN_MANIFEST_KEYS:
if key in manifest:
raise BuildError(f"{ext_id_hint}: a theme pack must not declare '{key}'")
perms = manifest.get("permissions") or []
if not isinstance(perms, list) or not all(isinstance(p, str) for p in perms):
raise BuildError(f"{ext_id_hint}: 'permissions' must be a list of strings")
unknown_perms = sorted(set(perms) - KNOWN_PERMISSIONS)
if unknown_perms:
raise BuildError(
f"{ext_id_hint}: unknown permission(s): {', '.join(unknown_perms)}"
)
category = manifest.get("category")
if category is not None and (
not isinstance(category, str) or category not in KNOWN_CATEGORIES
):
raise BuildError(
f"{ext_id_hint}: 'category' must be one of {sorted(KNOWN_CATEGORIES)}"
)
ui = manifest.get("ui")
if ui is not None:
if not isinstance(ui, dict):
raise BuildError(f"{ext_id_hint}: 'ui' must be an object")
if schema == 1:
if not isinstance(ui.get("entry"), str) or not ui["entry"].strip():
raise BuildError(f"{ext_id_hint}: 'ui.entry' is required when 'ui' is set")
kind = ui.get("kind") or "shell-app"
if kind not in KNOWN_UI_KINDS:
raise BuildError(f"{ext_id_hint}: 'ui.kind' must be one of {sorted(KNOWN_UI_KINDS)}")
else:
if not isinstance(ui.get("module"), str) or not ui["module"].strip():
raise BuildError(f"{ext_id_hint}: schema-2 'ui.module' is required when 'ui' is set")
mount = ui.get("mount") or "shell-app"
if mount not in KNOWN_UI_KINDS:
raise BuildError(f"{ext_id_hint}: 'ui.mount' must be one of {sorted(KNOWN_UI_KINDS)}")
if schema == 2:
runtime = manifest.get("runtime")
if runtime is not None:
if not isinstance(runtime, dict):
raise BuildError(f"{ext_id_hint}: schema-2 'runtime' must be an object")
unknown_keys = sorted(set(runtime) - KNOWN_RUNTIME_KEYS)
if unknown_keys:
raise BuildError(
f"{ext_id_hint}: 'runtime' has unknown field(s): {', '.join(unknown_keys)}"
)
if runtime.get("api") != 1:
raise BuildError(f"{ext_id_hint}: 'runtime.api' must be 1")
if runtime.get("kind") not in KNOWN_RUNTIME_KINDS:
raise BuildError(
f"{ext_id_hint}: 'runtime.kind' must be one of {sorted(KNOWN_RUNTIME_KINDS)}"
)
modules = runtime.get("modules", [])
if not isinstance(modules, list) or not all(isinstance(m, str) for m in modules):
raise BuildError(f"{ext_id_hint}: 'runtime.modules' must be a list of strings")
if len(modules) != len(set(modules)):
raise BuildError(f"{ext_id_hint}: 'runtime.modules' cannot contain duplicates")
unknown_modules = sorted(set(modules) - KNOWN_RUNTIME_MODULES)
if unknown_modules:
raise BuildError(
f"{ext_id_hint}: unsupported runtime module(s): {', '.join(unknown_modules)}"
)
pause_when_hidden = runtime.get("pauseWhenHidden", True)
if not isinstance(pause_when_hidden, bool):
raise BuildError(f"{ext_id_hint}: 'runtime.pauseWhenHidden' must be true or false")
target_fps = runtime.get("targetFps", 60)
if isinstance(target_fps, bool) or not isinstance(target_fps, int) or not 15 <= target_fps <= 120:
raise BuildError(f"{ext_id_hint}: 'runtime.targetFps' must be an integer from 15 to 120")
integrity = manifest.get("integrity")
if not isinstance(integrity, dict) or not integrity:
raise BuildError(f"{ext_id_hint}: schema-2 manifest must include a non-empty 'integrity' map")
for key, value in integrity.items():
if not isinstance(key, str) or not isinstance(value, str) or not value.startswith("sha256-"):
raise BuildError(
f"{ext_id_hint}: 'integrity' entries must be 'sha256-<base64>' strings (bad key {key!r})"
)
validate_theme(manifest, ext_id_hint)
widgets = manifest.get("widgets")
if widgets is not None:
if schema != 2:
raise BuildError(
f"{ext_id_hint}: 'widgets' requires schema 2 (schema-1 packages cannot ship shelf widgets)"
)
manifest["widgets"] = validate_widgets(widgets, manifest["integrity"], ext_id_hint)
sprout = manifest.get("sprout")
if sprout is not None:
if schema != 2:
raise BuildError(f"{ext_id_hint}: 'sprout' requires schema 2")
validate_sprout(sprout, ext_id_hint)
def _widget_package_path(
raw: object,
*,
field: str,
widget_id: str,
suffixes: tuple[str, ...],
ext_id_hint: str,
) -> str:
"""Same tightness as the panel's `_widget_package_path`: no absolute
paths, no parent refs, no empty path segments, a known suffix."""
if not isinstance(raw, str) or not raw.strip():
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} must set '{field}' to a file path inside the package"
)
path = raw.strip().replace("\\", "/")
if path.startswith("/"):
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} field '{field}' must be a relative package path "
f"without a leading '/', got {raw!r}"
)
parts = path.split("/")
if any(part in ("", ".", "..") for part in parts) or ":" in path:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} field '{field}' must stay inside the package "
f"(no '..', no empty path segments), got {raw!r}"
)
if not path.lower().endswith(suffixes):
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} field '{field}' must end with one of "
f"{', '.join(suffixes)}, got {raw!r}"
)
return path
def validate_widgets(
raw_widgets: object,
integrity: dict[str, Any],
ext_id_hint: str,
) -> list[dict[str, Any]]:
"""Validate + normalize extension.json's schema-2 `widgets` block.
Raises BuildError on anything the panel's `_parse_widgets` would also
reject; returns the normalized list so a hand-written manifest gets
the exact same defaults (empty description, ordered sizes, null
preview) the panel would store."""
if not isinstance(raw_widgets, list):
raise BuildError(f"{ext_id_hint}: 'widgets' must be a list of widget declarations")
if len(raw_widgets) > MAX_WIDGETS_PER_EXTENSION:
raise BuildError(
f"{ext_id_hint}: declares {len(raw_widgets)} widgets; at most "
f"{MAX_WIDGETS_PER_EXTENSION} are allowed per extension"
)
normalized: list[dict[str, Any]] = []
seen: set[str] = set()
for entry in raw_widgets:
if not isinstance(entry, dict):
raise BuildError(f"{ext_id_hint}: each entry in 'widgets' must be an object")
widget_id = entry.get("id")
if not isinstance(widget_id, str) or not _WIDGET_ID_RE.match(widget_id):
raise BuildError(
f"{ext_id_hint}: widget 'id' must be lowercase letters, digits and dashes "
f"(1-40 chars, starting with a letter or digit), got {widget_id!r}"
)
if widget_id in seen:
raise BuildError(f"{ext_id_hint}: declares duplicate widget id {widget_id!r}")
seen.add(widget_id)
unknown_keys = sorted(set(entry) - KNOWN_WIDGET_KEYS)
if unknown_keys:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} contains unknown field(s): {', '.join(unknown_keys)}"
)
name = entry.get("name")
if not isinstance(name, str) or not name.strip() or len(name) > MAX_WIDGET_NAME_CHARS:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} must set 'name' to a non-empty string of at "
f"most {MAX_WIDGET_NAME_CHARS} characters"
)
description = entry.get("description", "")
if not isinstance(description, str) or len(description) > MAX_WIDGET_DESCRIPTION_CHARS:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} field 'description' must be a string of at "
f"most {MAX_WIDGET_DESCRIPTION_CHARS} characters"
)
sizes = entry.get("sizes", ["small"])
if (
not isinstance(sizes, list)
or not sizes
or not all(isinstance(s, str) for s in sizes)
or len(set(sizes)) != len(sizes)
or any(s not in KNOWN_WIDGET_SIZES for s in sizes)
):
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} field 'sizes' must be a non-empty list of "
f"distinct values from {list(KNOWN_WIDGET_SIZES)}"
)
module = _widget_package_path(
entry.get("module"), field="module", widget_id=widget_id,
suffixes=WIDGET_MODULE_SUFFIXES, ext_id_hint=ext_id_hint,
)
if module not in integrity:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} module {module!r} is not covered by the "
f"integrity map (file must exist in the package)"
)
preview_raw = entry.get("preview")
preview = (
_widget_package_path(
preview_raw, field="preview", widget_id=widget_id,
suffixes=WIDGET_PREVIEW_SUFFIXES, ext_id_hint=ext_id_hint,
)
if preview_raw is not None
else None
)
if preview is not None and preview not in integrity:
raise BuildError(
f"{ext_id_hint}: widget {widget_id!r} preview {preview!r} is not covered by the "
f"integrity map (file must exist in the package)"
)
normalized.append({
"id": widget_id,
"name": name.strip(),
"description": description.strip(),
"sizes": [s for s in KNOWN_WIDGET_SIZES if s in sizes],
"module": module,
"preview": preview,
})
return normalized
def _sprout_text_problem(text: str) -> str:
"""Why `text` may not reach the model, or "" (mirrors checkModelText)."""
for ch in text:
if ch in "\n\r\t":
return "must be a single line"
if not ch.isprintable():
return "must be printable text"
if ch in "<>{}`":
return "must not contain < > { } or a backtick"
if "://" in text:
return "must not contain a link"
folded = " ".join(text.lower().split())
for phrase in SPROUT_DENIED_PHRASES:
if phrase in folded:
return f"must not contain {phrase!r}"
return ""
def _is_whole(value: object) -> bool:
return not isinstance(value, bool) and isinstance(value, (int, float)) and float(value) == int(value)
def _validate_sprout_property(tool: str, key: str, prop: object, ext_id_hint: str) -> None:
where = f"{ext_id_hint}: sprout tool {tool!r} input {key!r}"
if not isinstance(prop, dict):
raise BuildError(f"{where} must be an object")
kind = prop.get("type")
allowed = {"type", "description"}
if kind == "string":
allowed |= {"maxLength", "enum"}
elif kind == "integer":
allowed |= {"minimum", "maximum"}
elif kind != "boolean":
raise BuildError(f"{where} 'type' must be string, integer or boolean")
for name in prop:
if name not in allowed:
raise BuildError(f"{where} '{name}' is not supported for a {kind}")
description = prop.get("description")
if description is not None:
text = description.strip() if isinstance(description, str) else None
if text is None or len(text) > MAX_SPROUT_PROP_DESCRIPTION_CHARS:
raise BuildError(
f"{where} 'description' must be up to {MAX_SPROUT_PROP_DESCRIPTION_CHARS} characters"
)
problem = _sprout_text_problem(text)
if problem:
raise BuildError(f"{where} 'description' {problem}")
if kind == "string":
max_length = prop.get("maxLength")
if max_length is not None and (
not _is_whole(max_length) or not 1 <= max_length <= MAX_SPROUT_STRING_LENGTH
):
raise BuildError(f"{where} 'maxLength' must be a whole number up to {MAX_SPROUT_STRING_LENGTH}")
values = prop.get("enum")
if values is not None:
if not isinstance(values, list) or not 1 <= len(values) <= MAX_SPROUT_ENUM:
raise BuildError(f"{where} 'enum' must list 1-{MAX_SPROUT_ENUM} values")
for value in values:
if not isinstance(value, str) or not value or len(value) > MAX_SPROUT_ENUM_CHARS:
raise BuildError(
f"{where} 'enum' values must be strings of up to {MAX_SPROUT_ENUM_CHARS} characters"
)
problem = _sprout_text_problem(value)
if problem:
raise BuildError(f"{where} 'enum' value {problem}")
elif kind == "integer":
low, high = prop.get("minimum"), prop.get("maximum")
if not (_is_whole(low) and _is_whole(high)) or low > high or abs(low) > 1e9 or abs(high) > 1e9:
raise BuildError(f"{where} needs whole-number 'minimum' and 'maximum'")
def _validate_sprout_input(tool: str, raw: object, ext_id_hint: str) -> None:
if raw is None:
return
where = f"{ext_id_hint}: sprout tool {tool!r}"
if not isinstance(raw, dict):
raise BuildError(f"{where} 'input' must be an object")
for key, value in raw.items():
if key == "type":
if value != "object":
raise BuildError(f"{where} 'input.type' must be \"object\"")
elif key == "additionalProperties":
if value is not False:
raise BuildError(f"{where} 'input.additionalProperties' must be false; the panel always sets it")
elif key not in ("properties", "required"):
raise BuildError(f"{where} 'input.{key}' is not supported")
properties = raw.get("properties")
if properties is None:
properties = {}
if not isinstance(properties, dict):
raise BuildError(f"{where} 'input.properties' must be an object")
if len(properties) > MAX_SPROUT_PROPERTIES:
raise BuildError(f"{where} may declare at most {MAX_SPROUT_PROPERTIES} input properties")
for key, prop in properties.items():
if not _SPROUT_PROP_NAME_RE.match(key):
raise BuildError(f"{where} has an input property name that is not a lowercase word ({key!r})")
_validate_sprout_property(tool, key, prop, ext_id_hint)
required = raw.get("required")
if required is not None:
if not isinstance(required, list) or any(not isinstance(k, str) or k not in properties for k in required):
raise BuildError(f"{where} 'input.required' may only name declared properties")
if len(json.dumps(raw, separators=(",", ":"), ensure_ascii=False).encode("utf-8")) > MAX_SPROUT_INPUT_BYTES:
raise BuildError(f"{where} 'input' is larger than {MAX_SPROUT_INPUT_BYTES} bytes")
def validate_sprout(raw: object, ext_id_hint: str) -> None:
"""Validate extension.json's schema-2 `sprout` block exactly as the panel's
`ParseSproutTools` does. Raises BuildError; the manifest is left as written."""
if not isinstance(raw, dict):
raise BuildError(f"{ext_id_hint}: 'sprout' must be an object")
tools = raw.get("tools")
if tools is None:
return
if not isinstance(tools, list):
raise BuildError(f"{ext_id_hint}: 'sprout.tools' must be a list")
if len(tools) > MAX_SPROUT_TOOLS:
raise BuildError(f"{ext_id_hint}: 'sprout.tools' may declare at most {MAX_SPROUT_TOOLS} tools")
seen: set[str] = set()
for index, entry in enumerate(tools, start=1):
if not isinstance(entry, dict):
raise BuildError(f"{ext_id_hint}: 'sprout.tools' entry {index} must be an object")
name = entry.get("name")
if not isinstance(name, str) or not _SPROUT_TOOL_NAME_RE.match(name):
raise BuildError(
f"{ext_id_hint}: a sprout tool 'name' must be 2-24 characters: a lowercase letter, "
"then lowercase letters, digits or underscores"
)
where = f"{ext_id_hint}: sprout tool {name!r}"
if entry.get("kind") not in SPROUT_KINDS:
raise BuildError(f"{where} 'kind' must be read, ui or act")
description = entry.get("description")
text = description.strip() if isinstance(description, str) else ""
low, high = SPROUT_DESCRIPTION_CHARS
if not low <= len(text) <= high:
raise BuildError(f"{where} 'description' must be {low}-{high} characters")
problem = _sprout_text_problem(text)
if problem:
raise BuildError(f"{where} 'description' {problem}")
if entry.get("doing") is not None:
doing = entry["doing"].strip() if isinstance(entry["doing"], str) else ""
if not doing or len(doing) > MAX_SPROUT_DOING_CHARS:
raise BuildError(f"{where} 'doing' must be up to {MAX_SPROUT_DOING_CHARS} characters")
problem = _sprout_text_problem(doing)
if problem:
raise BuildError(f"{where} 'doing' {problem}")
_validate_sprout_input(name, entry.get("input"), ext_id_hint)
if name in seen:
raise BuildError(f"{ext_id_hint}: 'sprout.tools' declares {name!r} twice")
seen.add(name)
LISTING_REQUIRED_STR_FIELDS = ("publisher", "category", "release_notes")
LISTING_REQUIRED_BOOL_FIELDS = ("featured", "reviewed")
def validate_listing(listing: dict[str, Any], ext_id: str) -> None:
if not isinstance(listing, dict):
raise BuildError(f"{ext_id}: listing.json must be a JSON object")
for field in LISTING_REQUIRED_STR_FIELDS:
if not isinstance(listing.get(field), str) or not listing[field].strip():
raise BuildError(f"{ext_id}: listing.json missing required string field '{field}'")
if listing["category"] not in KNOWN_CATEGORIES:
raise BuildError(f"{ext_id}: listing.json 'category' must be one of {sorted(KNOWN_CATEGORIES)}")
for field in LISTING_REQUIRED_BOOL_FIELDS:
if not isinstance(listing.get(field), bool):
raise BuildError(f"{ext_id}: listing.json field '{field}' must be true or false")
features = listing.get("features")
if not isinstance(features, list) or not all(isinstance(f, str) and f.strip() for f in features):
raise BuildError(f"{ext_id}: listing.json 'features' must be a list of non-empty strings")
if not 3 <= len(features) <= 6:
raise BuildError(f"{ext_id}: listing.json 'features' must have 3-6 entries, got {len(features)}")
requirements = listing.get("requirements")
if not isinstance(requirements, list) or not requirements or not all(
isinstance(r, str) and r.strip() for r in requirements
):
raise BuildError(f"{ext_id}: listing.json 'requirements' must be a non-empty list of strings")
homepage = listing.get("homepage")
if homepage is not None and not isinstance(homepage, str):
raise BuildError(f"{ext_id}: listing.json 'homepage' must be a string when present")
# ---------- files on disk ----------
def _reject_dotfiles(ext_dir: Path, rel_parts: tuple[str, ...]) -> None:
if any(part.startswith(".") for part in rel_parts):
raise BuildError(f"{ext_dir.name}: dotfile not allowed: {'/'.join(rel_parts)}")
def iter_ext_files(ext_dir: Path) -> list[tuple[Path, str]]:
"""Every real file under an extension folder, sorted by posix-relative
path. Rejects dotfiles and directory entries are never yielded (we
only walk real files, so a ZIP built from this list never carries
directory entries)."""
out: list[tuple[Path, str]] = []
for path in sorted(ext_dir.rglob("*")):
if path.is_dir():
continue
rel = path.relative_to(ext_dir)
_reject_dotfiles(ext_dir, rel.parts)
out.append((path, rel.as_posix()))
out.sort(key=lambda item: item[1])
return out
def package_files(ext_dir: Path) -> list[tuple[Path, str]]: