srcset 0.2.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 (51) hide show
  1. srcset-0.2.0/.gitattributes +1 -0
  2. srcset-0.2.0/.gitignore +16 -0
  3. srcset-0.2.0/CHANGELOG.md +46 -0
  4. srcset-0.2.0/CONTRIBUTING.md +19 -0
  5. srcset-0.2.0/LICENSE +21 -0
  6. srcset-0.2.0/PKG-INFO +198 -0
  7. srcset-0.2.0/README.md +161 -0
  8. srcset-0.2.0/pyproject.toml +70 -0
  9. srcset-0.2.0/requirements-dev.txt +3 -0
  10. srcset-0.2.0/scripts/check.ps1 +16 -0
  11. srcset-0.2.0/scripts/fetch_upstream.py +37 -0
  12. srcset-0.2.0/scripts/release.ps1 +28 -0
  13. srcset-0.2.0/src/srcset/__init__.py +26 -0
  14. srcset-0.2.0/src/srcset/__main__.py +10 -0
  15. srcset-0.2.0/src/srcset/_build.py +57 -0
  16. srcset-0.2.0/src/srcset/_calc.py +142 -0
  17. srcset-0.2.0/src/srcset/_cli.py +78 -0
  18. srcset-0.2.0/src/srcset/_css_reader.py +98 -0
  19. srcset-0.2.0/src/srcset/_css_tokens.py +152 -0
  20. srcset-0.2.0/src/srcset/_css_values.py +113 -0
  21. srcset-0.2.0/src/srcset/_descriptors.py +57 -0
  22. srcset-0.2.0/src/srcset/_math_functions.py +81 -0
  23. srcset-0.2.0/src/srcset/_media.py +130 -0
  24. srcset-0.2.0/src/srcset/_media_features.py +115 -0
  25. srcset-0.2.0/src/srcset/_model.py +111 -0
  26. srcset-0.2.0/src/srcset/_numbers.py +62 -0
  27. srcset-0.2.0/src/srcset/_parse.py +32 -0
  28. srcset-0.2.0/src/srcset/_scan.py +85 -0
  29. srcset-0.2.0/src/srcset/_select.py +81 -0
  30. srcset-0.2.0/src/srcset/_sizes.py +102 -0
  31. srcset-0.2.0/src/srcset/_validate.py +111 -0
  32. srcset-0.2.0/src/srcset/py.typed +0 -0
  33. srcset-0.2.0/tests/conftest.py +51 -0
  34. srcset-0.2.0/tests/test_build.py +79 -0
  35. srcset-0.2.0/tests/test_cli.py +73 -0
  36. srcset-0.2.0/tests/test_contract.py +38 -0
  37. srcset-0.2.0/tests/test_css.py +88 -0
  38. srcset-0.2.0/tests/test_css_boundaries.py +93 -0
  39. srcset-0.2.0/tests/test_docs.py +97 -0
  40. srcset-0.2.0/tests/test_e2e_wheel.py +96 -0
  41. srcset-0.2.0/tests/test_edges.py +90 -0
  42. srcset-0.2.0/tests/test_media.py +81 -0
  43. srcset-0.2.0/tests/test_model.py +90 -0
  44. srcset-0.2.0/tests/test_parse.py +105 -0
  45. srcset-0.2.0/tests/test_review_regressions.py +136 -0
  46. srcset-0.2.0/tests/test_select.py +81 -0
  47. srcset-0.2.0/tests/test_sizes.py +166 -0
  48. srcset-0.2.0/tests/test_typing.py +79 -0
  49. srcset-0.2.0/tests/test_validate.py +90 -0
  50. srcset-0.2.0/tests/test_wpt.py +78 -0
  51. srcset-0.2.0/tests/upstream/MANIFEST.json +29 -0
@@ -0,0 +1 @@
1
+ * text=auto eol=lf
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # Third-party test files, fetched locally by scripts/fetch_upstream.py; only the manifest is tracked.
15
+ tests/upstream/*
16
+ !tests/upstream/MANIFEST.json
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.0]
10
+
11
+ ### Added
12
+
13
+ - `parse_sizes` reads a sizes attribute with the WHATWG algorithm on top of a CSS tokenizer:
14
+ absolute, font and viewport lengths, the CSS math functions, and media
15
+ conditions with `not`, `and`, `or`, range syntax and three-valued logic. `auto` resolves
16
+ to a width the caller passes when the value starts with it.
17
+ - `source_set` and `select` build and normalize the source set (with the `src` fallback)
18
+ and pick the image a browser fetches for an `Environment` (viewport, pixel ratio, font
19
+ size).
20
+ - `validate` lists authoring errors with stable codes.
21
+ - The `srcset` command (`parse`, `select`, `check`) and `python -m srcset`.
22
+ - Tests against the web-platform-tests srcset and sizes cases, fetched locally by
23
+ `scripts/fetch_upstream.py`, plus executed README examples, a typing check and an
24
+ installed-wheel test.
25
+
26
+ ### Changed
27
+
28
+ - `Candidate` is a frozen, validated value with `url`, `width`, `density` and `height`;
29
+ its `descriptor` property gives the text. It replaces the `(url, descriptor)` tuple.
30
+ - `build` also accepts `Candidate` values, normalizes descriptor text and refuses a URL
31
+ that starts with a comma.
32
+
33
+ ### Fixed
34
+
35
+ - Numbers follow the HTML microsyntaxes: `1.x` is no longer accepted, `0x` and `-0x` are
36
+ kept, and only ASCII digits count.
37
+ - `100w 50h` is a valid candidate: the `h` descriptor is accepted next to a width.
38
+ - Widths of any length parse exactly, past the interpreter's digit limit.
39
+
40
+ ## [0.1.0]
41
+
42
+ - `parse` reads a srcset attribute into a list of `Candidate` values, following the
43
+ WHATWG splitting algorithm so URLs that contain commas stay intact.
44
+ - `build` serialises candidates back into a srcset value and rejects anything that
45
+ cannot round-trip (empty URLs, whitespace in a URL, a trailing comma, bad descriptors).
46
+ - `Candidate` named tuple and `SrcsetError` are part of the public surface.
@@ -0,0 +1,19 @@
1
+ # Contributing
2
+
3
+ Thanks for taking the time. This project keeps a small, predictable shape.
4
+
5
+ ## Setup
6
+
7
+ ```
8
+ pip install -r requirements-dev.txt
9
+ ```
10
+
11
+ ## Before you open a pull request
12
+
13
+ - Keep public API in `src/srcset/__init__.py`; internals live in `_`-prefixed modules.
14
+ - Add a test for the behaviour you change. Tests inject time, disk and network; they
15
+ never touch the real thing.
16
+ - Run `scripts/check.ps1` (format, lint, types, tests) and make sure it passes.
17
+ - One logical change per commit, imperative subject line.
18
+
19
+ Open an issue first if the change is large or shifts the public API.
srcset-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Javier Lianes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
srcset-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.5
2
+ Name: srcset
3
+ Version: 0.2.0
4
+ Summary: Parse, build, check and resolve the HTML srcset and sizes attributes like a browser
5
+ Project-URL: Homepage, https://lianes8studio.com
6
+ Project-URL: Repository, https://github.com/JaviLianes8/srcset
7
+ Project-URL: Issues, https://github.com/JaviLianes8/srcset/issues
8
+ Project-URL: Changelog, https://github.com/JaviLianes8/srcset/blob/main/CHANGELOG.md
9
+ Project-URL: LinkedIn, https://www.linkedin.com/in/jlianes/
10
+ Project-URL: Funding, https://buymeacoffee.com/jlianesglrs
11
+ Author-email: Javier Lianes <javier@lianes8studio.com>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: html,image,media-queries,parser,picture,responsive-images,sizes,srcset,whatwg
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Environment :: Console
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
27
+ Classifier: Topic :: Text Processing :: Markup :: HTML
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.10
30
+ Provides-Extra: dev
31
+ Requires-Dist: build; extra == 'dev'
32
+ Requires-Dist: mypy; extra == 'dev'
33
+ Requires-Dist: pytest; extra == 'dev'
34
+ Requires-Dist: ruff; extra == 'dev'
35
+ Requires-Dist: twine; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # srcset
39
+
40
+ Parse, build, check and resolve the HTML `srcset` and `sizes` attributes with the WHATWG
41
+ algorithms, checked against the web-platform-tests cases browsers run: which candidates
42
+ survive, what layout width `sizes` gives, and which image a browser fetches for a viewport
43
+ and a device pixel ratio.
44
+
45
+ ## Install
46
+
47
+ ```
48
+ pip install srcset
49
+ ```
50
+
51
+ Python 3.10 or newer, no dependencies.
52
+
53
+ ## Usage
54
+
55
+ Parse a `srcset` value into typed candidates. Invalid candidates are dropped, as browsers
56
+ drop them, and a comma inside a URL (a data URI, for example) does not split the list:
57
+
58
+ ```python
59
+ from srcset import Candidate, build, parse
60
+
61
+ candidates = parse("small.png 1x, large.png 2x, data:image/png;base64,iVBO 3x")
62
+ print([c.url for c in candidates])
63
+ # ['small.png', 'large.png', 'data:image/png;base64,iVBO']
64
+ print(parse("hero.jpg 800w, bad.jpg 1.x"))
65
+ # [Candidate(url='hero.jpg', width=800, density=None, height=None)]
66
+ print(build([Candidate("a.png", 320), ("b.png", "2x")]))
67
+ # a.png 320w, b.png 2x
68
+ ```
69
+
70
+ Resolve `sizes` and pick the image a browser would load:
71
+
72
+ ```python
73
+ from srcset import Environment, parse_sizes, select
74
+
75
+ phone = Environment(width=390, height=844, density=3)
76
+ sizes = "(min-width: 1024px) 33vw, calc(100vw - 2rem)"
77
+ print(parse_sizes(sizes, phone))
78
+ # 358.0
79
+ srcset = "s.jpg 480w, m.jpg 960w, l.jpg 1440w"
80
+ print(select(srcset, phone, sizes=sizes))
81
+ # ImageSource(url='l.jpg', density=4.022346368715084)
82
+ print(select(srcset, Environment(width=1440), sizes=sizes).url)
83
+ # s.jpg
84
+ ```
85
+
86
+ Check what authors wrote:
87
+
88
+ ```python
89
+ from srcset import validate
90
+
91
+ for issue in validate("a.jpg 400w, b.jpg 400w, c.jpg 2x", sizes="100vw"):
92
+ print(issue.code)
93
+ # duplicate-width
94
+ # mixed-descriptors
95
+ # sizes-without-width
96
+ ```
97
+
98
+ ## Command line
99
+
100
+ ```
101
+ $ srcset parse "a.png 100w 50h, b.png 2x"
102
+ [{"url": "a.png", "width": 100, "density": null, "height": 50}, {"url": "b.png", "width": null, "density": 2.0, "height": null}]
103
+ $ srcset select "s.jpg 480w, l.jpg 1440w" --sizes "50vw" --width 1280 --dpr 2
104
+ l.jpg
105
+ $ srcset check "a.png 1x,, b.png 1x"
106
+ extra-comma: a comma with no image candidate before it
107
+ duplicate-density: 2 candidates share the density 1
108
+ ```
109
+
110
+ `select` takes `--sizes`, `--src`, `--width` (1280 by default), `--height`, `--dpr` and
111
+ `--json`. `check` exits with status 1 when it finds an issue. `python -m srcset` works too.
112
+
113
+ ## API
114
+
115
+ | Name | What it does |
116
+ | --- | --- |
117
+ | `parse(value)` | The candidates a browser keeps, as `Candidate` values. Never raises for malformed input. |
118
+ | `build(candidates)` | Serializes `Candidate` values or `(url, descriptor)` pairs; raises `SrcsetError` for anything that would not read back the same. |
119
+ | `parse_sizes(value, environment, *, auto_width=None)` | The layout width in CSS pixels, `100vw` when no entry applies. |
120
+ | `source_set(srcset, environment, *, sizes="", src="", auto_width=None)` | Every candidate as an `ImageSource` with the density it stands for, later duplicates removed. |
121
+ | `select(srcset, environment, *, sizes="", src="", auto_width=None)` | The `ImageSource` a browser would fetch, or `None`. |
122
+ | `validate(srcset, sizes=None)` | Authoring errors as `Issue` values; `sizes=None` means the attribute is absent. |
123
+ | `Candidate(url, width=None, density=None, height=None)` | A frozen candidate; `descriptor` gives its text, such as `320w` or `1.5x`. |
124
+ | `Environment(width, height=None, density=1.0, font_size=16.0)` | Viewport size in CSS pixels, device pixel ratio and root font size. |
125
+ | `ImageSource(url, density)` | A named tuple from a normalized source set. |
126
+ | `Issue(code, message)` | A named tuple with a stable code. |
127
+ | `SrcsetError` | A `ValueError` for values that cannot be built or are out of range. Wrong types raise `TypeError`. |
128
+
129
+ ## Behaviour
130
+
131
+ - **Descriptors.** A width is a valid non-negative integer above zero followed by `w`; a
132
+ density is a valid HTML floating-point number followed by `x` (`.5x` and `1e1x` are fine,
133
+ `1.x`, `+1x` and `1X` are not), with only ASCII digits. `0x` is kept, as browsers keep it.
134
+ The `h` descriptor is accepted only next to a width. Two descriptors of one kind, or a
135
+ width with a density, drop the candidate.
136
+ - **Sizes.** Entries are read with a CSS tokenizer (comments, escapes, unclosed blocks).
137
+ Lengths cover the absolute units, `em`, `rem`, and the viewport units with their `s`, `l`
138
+ and `d` forms. Math functions: `calc`, `min`, `max`, `clamp`, `abs`, `sign`, `round`,
139
+ `mod`, `rem`, `hypot`, `sqrt`, `pow`, `exp` and `log`, with the constants `e` and `pi`.
140
+ A negative literal is invalid and a negative math result becomes 0. A result that is
141
+ infinite or not a number (division by zero, for example) makes the entry invalid, which
142
+ is what the web-platform-tests expect from browsers. `ex`, `ch`, `cap`, `ic` and `lh` use
143
+ fixed ratios of the font size, because the real values depend on the font. Blocks nested
144
+ more than 32 deep make their entry invalid.
145
+ - **Media conditions.** `not`, `and`, `or`, nesting, the `min-` and `max-` forms and range
146
+ syntax such as `(400px <= width < 800px)`, for `width`, `height`, `aspect-ratio`,
147
+ `orientation` and `resolution` (including `infinite`). Other features, and media types such as `screen`, never
148
+ match: the first are unknown under the three-valued logic of Media Queries 4, the second
149
+ are not allowed in `sizes`. A height-based condition is unknown while
150
+ `Environment.height` is `None`.
151
+ - **`auto`.** When the value is `auto` or starts with `auto,` (any ASCII case), `auto`
152
+ stands for `auto_width` if one is given: an image that allows auto-sizes, rendered at
153
+ that width. Otherwise it is skipped and the next entry applies.
154
+ - **Selection.** The standard leaves the final pick to the browser. `select` takes the
155
+ lowest density that covers `environment.density`, or the highest density when none
156
+ does; this is the usual policy and it reproduces every web-platform-tests selection
157
+ case. Width candidates with a zero size get an infinite density.
158
+ - **Issue codes.** `empty`, `extra-comma`, `invalid-descriptor`, `duplicate-width`,
159
+ `duplicate-density`, `zero-density`, `height-descriptor`, `mixed-descriptors`,
160
+ `sizes-without-width`, `missing-sizes` and `invalid-sizes`.
161
+
162
+ ## Why
163
+
164
+ The `srcset` syntax looks like a comma-separated list, yet a URL may contain commas, so a
165
+ naive `split(",")` corrupts it. And reading the attribute is only half the job: knowing
166
+ which file a phone downloads takes the `sizes` attribute, which is CSS (lengths, `calc`,
167
+ media conditions), and the density arithmetic that ties the two together. This library
168
+ implements the WHATWG algorithms for all three steps, typed and without dependencies, and
169
+ checks itself against the web-platform-tests cases that browsers run.
170
+
171
+ ## Standards
172
+
173
+ - WHATWG HTML: parsing a srcset attribute, parsing a sizes attribute, creating and
174
+ normalizing a source set, and the srcset and sizes authoring requirements
175
+ (https://html.spec.whatwg.org/multipage/images.html).
176
+ - CSS Syntax 3 (https://drafts.csswg.org/css-syntax-3/) and Media Queries 4
177
+ (https://drafts.csswg.org/mediaqueries-4/).
178
+
179
+ ## Development
180
+
181
+ ```
182
+ pip install -r requirements-dev.txt
183
+ python scripts/fetch_upstream.py # optional: the web-platform-tests files
184
+ pwsh scripts/check.ps1
185
+ ```
186
+
187
+ The web-platform-tests files are not part of the repository; `tests/upstream/MANIFEST.json`
188
+ records where they come from, and their tests skip until the script has fetched them.
189
+
190
+ ## License
191
+
192
+ MIT. See [LICENSE](LICENSE).
193
+
194
+ ## Links
195
+
196
+ - Website: https://lianes8studio.com
197
+ - GitHub: https://github.com/JaviLianes8
198
+ - LinkedIn: https://www.linkedin.com/in/jlianes/
srcset-0.2.0/README.md ADDED
@@ -0,0 +1,161 @@
1
+ # srcset
2
+
3
+ Parse, build, check and resolve the HTML `srcset` and `sizes` attributes with the WHATWG
4
+ algorithms, checked against the web-platform-tests cases browsers run: which candidates
5
+ survive, what layout width `sizes` gives, and which image a browser fetches for a viewport
6
+ and a device pixel ratio.
7
+
8
+ ## Install
9
+
10
+ ```
11
+ pip install srcset
12
+ ```
13
+
14
+ Python 3.10 or newer, no dependencies.
15
+
16
+ ## Usage
17
+
18
+ Parse a `srcset` value into typed candidates. Invalid candidates are dropped, as browsers
19
+ drop them, and a comma inside a URL (a data URI, for example) does not split the list:
20
+
21
+ ```python
22
+ from srcset import Candidate, build, parse
23
+
24
+ candidates = parse("small.png 1x, large.png 2x, data:image/png;base64,iVBO 3x")
25
+ print([c.url for c in candidates])
26
+ # ['small.png', 'large.png', 'data:image/png;base64,iVBO']
27
+ print(parse("hero.jpg 800w, bad.jpg 1.x"))
28
+ # [Candidate(url='hero.jpg', width=800, density=None, height=None)]
29
+ print(build([Candidate("a.png", 320), ("b.png", "2x")]))
30
+ # a.png 320w, b.png 2x
31
+ ```
32
+
33
+ Resolve `sizes` and pick the image a browser would load:
34
+
35
+ ```python
36
+ from srcset import Environment, parse_sizes, select
37
+
38
+ phone = Environment(width=390, height=844, density=3)
39
+ sizes = "(min-width: 1024px) 33vw, calc(100vw - 2rem)"
40
+ print(parse_sizes(sizes, phone))
41
+ # 358.0
42
+ srcset = "s.jpg 480w, m.jpg 960w, l.jpg 1440w"
43
+ print(select(srcset, phone, sizes=sizes))
44
+ # ImageSource(url='l.jpg', density=4.022346368715084)
45
+ print(select(srcset, Environment(width=1440), sizes=sizes).url)
46
+ # s.jpg
47
+ ```
48
+
49
+ Check what authors wrote:
50
+
51
+ ```python
52
+ from srcset import validate
53
+
54
+ for issue in validate("a.jpg 400w, b.jpg 400w, c.jpg 2x", sizes="100vw"):
55
+ print(issue.code)
56
+ # duplicate-width
57
+ # mixed-descriptors
58
+ # sizes-without-width
59
+ ```
60
+
61
+ ## Command line
62
+
63
+ ```
64
+ $ srcset parse "a.png 100w 50h, b.png 2x"
65
+ [{"url": "a.png", "width": 100, "density": null, "height": 50}, {"url": "b.png", "width": null, "density": 2.0, "height": null}]
66
+ $ srcset select "s.jpg 480w, l.jpg 1440w" --sizes "50vw" --width 1280 --dpr 2
67
+ l.jpg
68
+ $ srcset check "a.png 1x,, b.png 1x"
69
+ extra-comma: a comma with no image candidate before it
70
+ duplicate-density: 2 candidates share the density 1
71
+ ```
72
+
73
+ `select` takes `--sizes`, `--src`, `--width` (1280 by default), `--height`, `--dpr` and
74
+ `--json`. `check` exits with status 1 when it finds an issue. `python -m srcset` works too.
75
+
76
+ ## API
77
+
78
+ | Name | What it does |
79
+ | --- | --- |
80
+ | `parse(value)` | The candidates a browser keeps, as `Candidate` values. Never raises for malformed input. |
81
+ | `build(candidates)` | Serializes `Candidate` values or `(url, descriptor)` pairs; raises `SrcsetError` for anything that would not read back the same. |
82
+ | `parse_sizes(value, environment, *, auto_width=None)` | The layout width in CSS pixels, `100vw` when no entry applies. |
83
+ | `source_set(srcset, environment, *, sizes="", src="", auto_width=None)` | Every candidate as an `ImageSource` with the density it stands for, later duplicates removed. |
84
+ | `select(srcset, environment, *, sizes="", src="", auto_width=None)` | The `ImageSource` a browser would fetch, or `None`. |
85
+ | `validate(srcset, sizes=None)` | Authoring errors as `Issue` values; `sizes=None` means the attribute is absent. |
86
+ | `Candidate(url, width=None, density=None, height=None)` | A frozen candidate; `descriptor` gives its text, such as `320w` or `1.5x`. |
87
+ | `Environment(width, height=None, density=1.0, font_size=16.0)` | Viewport size in CSS pixels, device pixel ratio and root font size. |
88
+ | `ImageSource(url, density)` | A named tuple from a normalized source set. |
89
+ | `Issue(code, message)` | A named tuple with a stable code. |
90
+ | `SrcsetError` | A `ValueError` for values that cannot be built or are out of range. Wrong types raise `TypeError`. |
91
+
92
+ ## Behaviour
93
+
94
+ - **Descriptors.** A width is a valid non-negative integer above zero followed by `w`; a
95
+ density is a valid HTML floating-point number followed by `x` (`.5x` and `1e1x` are fine,
96
+ `1.x`, `+1x` and `1X` are not), with only ASCII digits. `0x` is kept, as browsers keep it.
97
+ The `h` descriptor is accepted only next to a width. Two descriptors of one kind, or a
98
+ width with a density, drop the candidate.
99
+ - **Sizes.** Entries are read with a CSS tokenizer (comments, escapes, unclosed blocks).
100
+ Lengths cover the absolute units, `em`, `rem`, and the viewport units with their `s`, `l`
101
+ and `d` forms. Math functions: `calc`, `min`, `max`, `clamp`, `abs`, `sign`, `round`,
102
+ `mod`, `rem`, `hypot`, `sqrt`, `pow`, `exp` and `log`, with the constants `e` and `pi`.
103
+ A negative literal is invalid and a negative math result becomes 0. A result that is
104
+ infinite or not a number (division by zero, for example) makes the entry invalid, which
105
+ is what the web-platform-tests expect from browsers. `ex`, `ch`, `cap`, `ic` and `lh` use
106
+ fixed ratios of the font size, because the real values depend on the font. Blocks nested
107
+ more than 32 deep make their entry invalid.
108
+ - **Media conditions.** `not`, `and`, `or`, nesting, the `min-` and `max-` forms and range
109
+ syntax such as `(400px <= width < 800px)`, for `width`, `height`, `aspect-ratio`,
110
+ `orientation` and `resolution` (including `infinite`). Other features, and media types such as `screen`, never
111
+ match: the first are unknown under the three-valued logic of Media Queries 4, the second
112
+ are not allowed in `sizes`. A height-based condition is unknown while
113
+ `Environment.height` is `None`.
114
+ - **`auto`.** When the value is `auto` or starts with `auto,` (any ASCII case), `auto`
115
+ stands for `auto_width` if one is given: an image that allows auto-sizes, rendered at
116
+ that width. Otherwise it is skipped and the next entry applies.
117
+ - **Selection.** The standard leaves the final pick to the browser. `select` takes the
118
+ lowest density that covers `environment.density`, or the highest density when none
119
+ does; this is the usual policy and it reproduces every web-platform-tests selection
120
+ case. Width candidates with a zero size get an infinite density.
121
+ - **Issue codes.** `empty`, `extra-comma`, `invalid-descriptor`, `duplicate-width`,
122
+ `duplicate-density`, `zero-density`, `height-descriptor`, `mixed-descriptors`,
123
+ `sizes-without-width`, `missing-sizes` and `invalid-sizes`.
124
+
125
+ ## Why
126
+
127
+ The `srcset` syntax looks like a comma-separated list, yet a URL may contain commas, so a
128
+ naive `split(",")` corrupts it. And reading the attribute is only half the job: knowing
129
+ which file a phone downloads takes the `sizes` attribute, which is CSS (lengths, `calc`,
130
+ media conditions), and the density arithmetic that ties the two together. This library
131
+ implements the WHATWG algorithms for all three steps, typed and without dependencies, and
132
+ checks itself against the web-platform-tests cases that browsers run.
133
+
134
+ ## Standards
135
+
136
+ - WHATWG HTML: parsing a srcset attribute, parsing a sizes attribute, creating and
137
+ normalizing a source set, and the srcset and sizes authoring requirements
138
+ (https://html.spec.whatwg.org/multipage/images.html).
139
+ - CSS Syntax 3 (https://drafts.csswg.org/css-syntax-3/) and Media Queries 4
140
+ (https://drafts.csswg.org/mediaqueries-4/).
141
+
142
+ ## Development
143
+
144
+ ```
145
+ pip install -r requirements-dev.txt
146
+ python scripts/fetch_upstream.py # optional: the web-platform-tests files
147
+ pwsh scripts/check.ps1
148
+ ```
149
+
150
+ The web-platform-tests files are not part of the repository; `tests/upstream/MANIFEST.json`
151
+ records where they come from, and their tests skip until the script has fetched them.
152
+
153
+ ## License
154
+
155
+ MIT. See [LICENSE](LICENSE).
156
+
157
+ ## Links
158
+
159
+ - Website: https://lianes8studio.com
160
+ - GitHub: https://github.com/JaviLianes8
161
+ - LinkedIn: https://www.linkedin.com/in/jlianes/
@@ -0,0 +1,70 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "srcset"
7
+ version = "0.2.0"
8
+ description = "Parse, build, check and resolve the HTML srcset and sizes attributes like a browser"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Javier Lianes", email = "javier@lianes8studio.com" }]
14
+ keywords = [
15
+ "srcset", "sizes", "html", "responsive-images", "whatwg", "media-queries", "picture",
16
+ "image", "parser",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Environment :: Console",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3 :: Only",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Programming Language :: Python :: 3.13",
29
+ "Programming Language :: Python :: 3.14",
30
+ "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
31
+ "Topic :: Text Processing :: Markup :: HTML",
32
+ "Typing :: Typed",
33
+ ]
34
+ dependencies = []
35
+
36
+ [project.optional-dependencies]
37
+ dev = ["ruff", "mypy", "pytest", "build", "twine"]
38
+
39
+ [project.scripts]
40
+ srcset = "srcset._cli:main"
41
+
42
+ [project.urls]
43
+ Homepage = "https://lianes8studio.com"
44
+ Repository = "https://github.com/JaviLianes8/srcset"
45
+ Issues = "https://github.com/JaviLianes8/srcset/issues"
46
+ Changelog = "https://github.com/JaviLianes8/srcset/blob/main/CHANGELOG.md"
47
+ LinkedIn = "https://www.linkedin.com/in/jlianes/"
48
+ Funding = "https://buymeacoffee.com/jlianesglrs"
49
+
50
+ [tool.hatch.build.targets.wheel]
51
+ packages = ["src/srcset"]
52
+
53
+ [tool.hatch.build.targets.sdist]
54
+ exclude = ["IMPROVEMENTS-round*.md", "tests/upstream/*.html", ".github"]
55
+
56
+ [tool.ruff]
57
+ line-length = 100
58
+ target-version = "py310"
59
+
60
+ [tool.ruff.lint]
61
+ select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
62
+
63
+ [tool.mypy]
64
+ python_version = "3.10"
65
+ strict = true
66
+
67
+ [tool.pytest.ini_options]
68
+ testpaths = ["tests"]
69
+ pythonpath = ["src"]
70
+ addopts = "-q"
@@ -0,0 +1,3 @@
1
+ # Development dependencies: the package in editable mode plus its dev extras
2
+ # (ruff, mypy, pytest, build, twine). Install with: pip install -r requirements-dev.txt
3
+ -e .[dev]
@@ -0,0 +1,16 @@
1
+ # Local quality gate. Run before every commit. No CI runs in the cloud.
2
+ # $ErrorActionPreference does NOT stop on a native command's non-zero exit, so each tool's
3
+ # exit code is checked explicitly: a red gate must fail, never pass silently.
4
+ $ErrorActionPreference = "Stop"
5
+
6
+ function Invoke-Step($label, [scriptblock]$cmd) {
7
+ Write-Host "== $label =="
8
+ & $cmd
9
+ if ($LASTEXITCODE -ne 0) { Write-Host "FAILED: $label (exit $LASTEXITCODE)"; exit $LASTEXITCODE }
10
+ }
11
+
12
+ Invoke-Step "ruff format" { ruff format --check . }
13
+ Invoke-Step "ruff lint" { ruff check . }
14
+ Invoke-Step "mypy" { mypy --strict src tests }
15
+ Invoke-Step "pytest" { pytest }
16
+ Write-Host "gate green"
@@ -0,0 +1,37 @@
1
+ """Fetch the third-party test files listed in tests/upstream/MANIFEST.json.
2
+
3
+ The files are not part of the repository. Their tests skip until this script has fetched
4
+ them; each download is checked against the size and sha256 in the manifest.
5
+
6
+ python scripts/fetch_upstream.py
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import sys
14
+ import urllib.request
15
+ from pathlib import Path
16
+
17
+ FOLDER = Path(__file__).resolve().parents[1] / "tests" / "upstream"
18
+
19
+
20
+ def main() -> int:
21
+ manifest = json.loads((FOLDER / "MANIFEST.json").read_text(encoding="utf-8"))
22
+ failed = 0
23
+ for name, entry in manifest.items():
24
+ with urllib.request.urlopen(entry["url"], timeout=60) as response:
25
+ body = response.read()
26
+ digest = hashlib.sha256(body).hexdigest()
27
+ if len(body) != entry["size"] or digest != entry["sha256"]:
28
+ print(f"{name}: got {len(body)} bytes, sha256 {digest}; manifest differs")
29
+ failed += 1
30
+ continue
31
+ (FOLDER / name).write_bytes(body)
32
+ print(f"{name}: ok")
33
+ return 1 if failed else 0
34
+
35
+
36
+ if __name__ == "__main__":
37
+ sys.exit(main())
@@ -0,0 +1,28 @@
1
+ # Build and upload to PyPI. Run scripts/check.ps1 first.
2
+ # The name must not already exist on PyPI; the token is read from a secret store, never git.
3
+ $ErrorActionPreference = "Stop"
4
+
5
+ # Works on both Windows PowerShell 5.1 and pwsh 7 (generic catch, no PS7-only types).
6
+ $taken = $true
7
+ try {
8
+ Invoke-WebRequest -UseBasicParsing "https://pypi.org/pypi/srcset/json" | Out-Null
9
+ } catch {
10
+ if ($_.Exception.Response.StatusCode.value__ -eq 404) { $taken = $false } else { throw }
11
+ }
12
+ if ($taken) { throw "The name 'srcset' already exists on PyPI. Choose another before publishing." }
13
+
14
+ $token = $env:PYPI_TOKEN
15
+ if (-not $token -and (Test-Path "C:\secrets\pypi-token.txt")) {
16
+ $token = (Get-Content "C:\secrets\pypi-token.txt" -Raw).Trim()
17
+ }
18
+ if (-not $token) {
19
+ throw "No PyPI token. Set `$env:PYPI_TOKEN or save it to C:\secrets\pypi-token.txt (never commit it)."
20
+ }
21
+
22
+ Remove-Item -Recurse -Force dist -ErrorAction SilentlyContinue
23
+ python -m build
24
+ python -m twine check dist/*
25
+
26
+ $env:TWINE_USERNAME = "__token__"
27
+ $env:TWINE_PASSWORD = $token
28
+ try { python -m twine upload dist/* } finally { Remove-Item Env:\TWINE_PASSWORD -ErrorAction SilentlyContinue }
@@ -0,0 +1,26 @@
1
+ """Parse, build, check and resolve the HTML srcset and sizes attributes like a browser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._build import build
6
+ from ._model import Candidate, Environment, ImageSource, Issue, SrcsetError
7
+ from ._parse import parse
8
+ from ._select import select, source_set
9
+ from ._sizes import parse_sizes
10
+ from ._validate import validate
11
+
12
+ __version__ = "0.2.0"
13
+
14
+ __all__ = [
15
+ "Candidate",
16
+ "Environment",
17
+ "ImageSource",
18
+ "Issue",
19
+ "SrcsetError",
20
+ "build",
21
+ "parse",
22
+ "parse_sizes",
23
+ "select",
24
+ "source_set",
25
+ "validate",
26
+ ]
@@ -0,0 +1,10 @@
1
+ """Allow ``python -m srcset``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from ._cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())