srcset 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
srcset/_descriptors.py ADDED
@@ -0,0 +1,57 @@
1
+ """The descriptor parser step of "parse a srcset attribute" (WHATWG HTML 4.8.4.3.10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import NamedTuple
7
+
8
+ from ._numbers import is_floating_point, is_non_negative_integer, parse_floating_point, to_int
9
+
10
+
11
+ class Descriptors(NamedTuple):
12
+ width: int | None
13
+ density: float | None
14
+ height: int | None
15
+
16
+
17
+ def parse_descriptors(tokens: Sequence[str]) -> Descriptors | None:
18
+ """Read descriptor tokens into values, or ``None`` when the candidate is an error.
19
+
20
+ Every token is visited even after an error, exactly as the standard reads them; the
21
+ only thing that matters is whether an error was raised at all.
22
+ """
23
+ error = False
24
+ width: int | None = None
25
+ density: float | None = None
26
+ height: int | None = None
27
+ for token in tokens:
28
+ body, suffix = token[:-1], token[-1:]
29
+ if suffix == "w" and is_non_negative_integer(body):
30
+ if width is not None or density is not None:
31
+ error = True
32
+ value = to_int(body)
33
+ if value == 0:
34
+ error = True
35
+ else:
36
+ width = value
37
+ elif suffix == "x" and is_floating_point(body):
38
+ if width is not None or density is not None or height is not None:
39
+ error = True
40
+ number = parse_floating_point(body)
41
+ if number is None or number < 0:
42
+ error = True
43
+ else:
44
+ density = number
45
+ elif suffix == "h" and is_non_negative_integer(body):
46
+ if height is not None or density is not None:
47
+ error = True
48
+ value = to_int(body)
49
+ if value == 0:
50
+ error = True
51
+ else:
52
+ height = value
53
+ else:
54
+ error = True
55
+ if height is not None and width is None:
56
+ error = True
57
+ return None if error else Descriptors(width, density, height)
@@ -0,0 +1,81 @@
1
+ """The CSS math functions applied to already evaluated arguments (CSS Values 4, 10).
2
+
3
+ A quantity is ``(value, is_length)``. Each function checks the argument types the way the
4
+ grammar does and returns ``None`` for a mismatch; a non-finite result is rejected later.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from collections.abc import Callable
11
+
12
+ Quantity = tuple[float, bool]
13
+
14
+ STRATEGIES = ("nearest", "up", "down", "to-zero")
15
+ CONSTANTS = {"e": math.e, "pi": math.pi, "infinity": math.inf, "-infinity": -math.inf}
16
+ CONSTANTS["nan"] = math.nan
17
+
18
+
19
+ def _same(args: list[Quantity]) -> bool:
20
+ return bool(args) and len({kind for _, kind in args}) == 1
21
+
22
+
23
+ def _numbers(args: list[Quantity]) -> bool:
24
+ return bool(args) and not any(kind for _, kind in args)
25
+
26
+
27
+ def _round(strategy: str, a: float, b: float) -> float:
28
+ # A zero step divides by zero; apply() turns that into NaN, which is invalid.
29
+ ratio = a / b
30
+ if strategy == "up":
31
+ steps = math.ceil(ratio)
32
+ elif strategy == "down":
33
+ steps = math.floor(ratio)
34
+ elif strategy == "to-zero":
35
+ steps = math.trunc(ratio)
36
+ else:
37
+ # Halfway values round up (towards positive infinity), as CSS specifies.
38
+ steps = math.floor(ratio + 0.5)
39
+ return steps * b
40
+
41
+
42
+ def _modulo(a: float, b: float, truncate: bool) -> float:
43
+ steps = math.trunc(a / b) if truncate else math.floor(a / b)
44
+ return a - b * steps
45
+
46
+
47
+ _UNARY_NUMBER: dict[str, Callable[[float], float]] = {"sqrt": math.sqrt, "exp": math.exp}
48
+
49
+
50
+ def apply(name: str, args: list[Quantity], strategy: str = "nearest") -> Quantity | None:
51
+ """Result of math function ``name``, or ``None`` when the arguments do not fit."""
52
+ values = [value for value, _ in args]
53
+ kind = args[0][1] if args else False
54
+ try:
55
+ if name in ("min", "max", "hypot") and _same(args):
56
+ if name == "hypot":
57
+ return (math.hypot(*values), kind)
58
+ return ((min if name == "min" else max)(values), kind)
59
+ if name == "clamp" and len(args) == 3 and _same(args):
60
+ return (max(values[0], min(values[1], values[2])), kind)
61
+ if name in ("abs", "sign") and len(args) == 1:
62
+ if name == "abs":
63
+ return (abs(values[0]), kind)
64
+ return (float((values[0] > 0) - (values[0] < 0)), False)
65
+ if name == "round" and len(args) in (1, 2) and _same(args):
66
+ if len(args) == 1 and kind:
67
+ return None
68
+ step = values[1] if len(args) == 2 else 1.0
69
+ return (_round(strategy, values[0], step), kind)
70
+ if name in ("mod", "rem") and len(args) == 2 and _same(args):
71
+ return (_modulo(values[0], values[1], name == "rem"), kind)
72
+ if name in _UNARY_NUMBER and len(args) == 1 and _numbers(args):
73
+ return (_UNARY_NUMBER[name](values[0]), False)
74
+ if name == "pow" and len(args) == 2 and _numbers(args):
75
+ return (math.pow(values[0], values[1]), False)
76
+ if name == "log" and len(args) in (1, 2) and _numbers(args):
77
+ base = values[1] if len(args) == 2 else math.e
78
+ return (math.log(values[0]) / math.log(base), False)
79
+ except (ValueError, OverflowError, ZeroDivisionError):
80
+ return (math.nan, kind)
81
+ return None
srcset/_media.py ADDED
@@ -0,0 +1,130 @@
1
+ """Media conditions (Media Queries 4) with Kleene three-valued logic.
2
+
3
+ ``True`` and ``False`` are the usual results and ``None`` is unknown: an unknown feature,
4
+ a value of the wrong type or ``<general-enclosed>`` syntax kept for future extensions.
5
+ A condition that does not match the grammar at all raises ``Invalid``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._css_reader import Token
11
+ from ._css_values import Block, Value, ident, is_any_value, is_ws, strip
12
+ from ._media_features import evaluate_feature
13
+ from ._model import Environment
14
+
15
+ Truth = bool | None
16
+
17
+
18
+ class Invalid(Exception):
19
+ """The values do not form a ``<media-condition>``."""
20
+
21
+
22
+ def evaluate(values: list[Value], env: Environment, *, strict: bool = False) -> Truth:
23
+ """Evaluate a ``<media-condition>``; raises ``Invalid`` on a grammar mismatch.
24
+
25
+ ``strict`` also refuses ``<general-enclosed>``, which authors must not write.
26
+ """
27
+ items = [value for value in values if not is_ws(value)]
28
+ if not items:
29
+ raise Invalid
30
+ if ident(items[0], "not") is not None:
31
+ if len(items) != 2:
32
+ raise Invalid
33
+ inner = _in_parens(items[1], env, strict)
34
+ return None if inner is None else not inner
35
+ results = [_in_parens(items[0], env, strict)]
36
+ joiner = ident(items[1], "and", "or") if len(items) > 1 else "and"
37
+ if len(items) % 2 == 0 or joiner is None:
38
+ raise Invalid
39
+ for word, item in zip(items[1::2], items[2::2], strict=True):
40
+ if ident(word) != joiner:
41
+ raise Invalid
42
+ results.append(_in_parens(item, env, strict))
43
+ if joiner == "and":
44
+ return False if False in results else (None if None in results else True)
45
+ return True if True in results else (None if None in results else False)
46
+
47
+
48
+ def _in_parens(value: Value, env: Environment, strict: bool) -> Truth:
49
+ """``<media-in-parens>``: a nested condition, a feature, or general-enclosed."""
50
+ if not isinstance(value, Block):
51
+ raise Invalid
52
+ if value.name is None and value.opener == "(":
53
+ try:
54
+ return evaluate(value.items, env, strict=strict)
55
+ except Invalid:
56
+ pass
57
+ feature = _feature(strip(value.items))
58
+ if feature is not None:
59
+ return evaluate_feature(*feature, env)
60
+ general = value.name is not None or value.opener == "("
61
+ if general and not strict and is_any_value(value.items):
62
+ return None
63
+ raise Invalid
64
+
65
+
66
+ Feature = tuple[str, list[tuple[str, list[Value]]]]
67
+ _FLIP = {"<": ">", "<=": ">=", ">": "<", ">=": "<=", "=": "="}
68
+
69
+
70
+ def _feature(items: list[Value]) -> Feature | None:
71
+ """Split ``<media-feature>`` into its name and ``(operator, value)`` comparisons.
72
+
73
+ The operator is ``:`` for the plain form; the boolean form has no comparison. Range
74
+ forms are turned around so the name comes first: ``10px < width`` is ``width > 10px``.
75
+ """
76
+ split = _split_operators(items)
77
+ if split is None:
78
+ return None
79
+ operands, ops = split
80
+ names = [_name(operand) for operand in operands]
81
+ if not ops:
82
+ # A min- or max- prefix is only valid in the plain form.
83
+ prefixed = names[0] is not None and names[0].startswith(("min-", "max-"))
84
+ return None if names[0] is None or prefixed else (names[0], [])
85
+ if ops == [":"]:
86
+ return None if names[0] is None else (names[0], [(":", operands[1])])
87
+ if ":" in ops or any(name and name.startswith(("min-", "max-")) for name in names):
88
+ return None
89
+ if len(ops) == 1:
90
+ if names[0] is not None:
91
+ return (names[0], [(ops[0], operands[1])])
92
+ return None if names[1] is None else (names[1], [(_FLIP[ops[0]], operands[0])])
93
+ if len(ops) == 2 and ops[0][0] == ops[1][0] != "=" and names[1] is not None:
94
+ return (names[1], [(_FLIP[ops[0]], operands[0]), (ops[1], operands[2])])
95
+ return None
96
+
97
+
98
+ def _name(operand: list[Value]) -> str | None:
99
+ return ident(operand[0]) if len(operand) == 1 else None
100
+
101
+
102
+ def _split_operators(items: list[Value]) -> tuple[list[list[Value]], list[str]] | None:
103
+ """Operands and the operators between them; ``None`` when an operand is empty."""
104
+ operands: list[list[Value]] = [[]]
105
+ ops: list[str] = []
106
+ i = 0
107
+ while i < len(items):
108
+ symbol = _symbol(items[i])
109
+ if symbol is None:
110
+ operands[-1].append(items[i])
111
+ else:
112
+ # "<=" must be written without whitespace between its two characters.
113
+ if symbol in "<>" and i + 1 < len(items) and _symbol(items[i + 1]) == "=":
114
+ symbol += "="
115
+ i += 1
116
+ ops.append(symbol)
117
+ operands.append([])
118
+ i += 1
119
+ operands = [strip(operand) for operand in operands]
120
+ if not all(operands) or len(ops) > 2:
121
+ return None
122
+ return operands, ops
123
+
124
+
125
+ def _symbol(item: Value) -> str | None:
126
+ if isinstance(item, Token) and item.kind == "colon":
127
+ return ":"
128
+ if isinstance(item, Token) and item.kind == "delim" and item.value in "<>=":
129
+ return item.value
130
+ return None
@@ -0,0 +1,115 @@
1
+ """Evaluate one media feature against an environment.
2
+
3
+ Known features: ``width``, ``height``, ``aspect-ratio``, ``orientation`` and
4
+ ``resolution``, with ``min-``/``max-`` prefixes and the range syntax. Any other name, or a
5
+ value of the wrong type, is unknown, so the condition around it does not match.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from collections.abc import Callable
12
+
13
+ from ._calc import quantity
14
+ from ._css_reader import Token
15
+ from ._css_values import Value, ident, is_ws
16
+ from ._model import Environment
17
+
18
+ _RESOLUTION = {"dppx": 1.0, "x": 1.0, "dpi": 1 / 96, "dpcm": 2.54 / 96}
19
+ _RANGE = ("width", "height", "aspect-ratio", "resolution")
20
+ _COMPARE: dict[str, Callable[[float, float], bool]] = {
21
+ ":": lambda a, b: a == b,
22
+ "=": lambda a, b: a == b,
23
+ "<": lambda a, b: a < b,
24
+ "<=": lambda a, b: a <= b,
25
+ ">": lambda a, b: a > b,
26
+ ">=": lambda a, b: a >= b,
27
+ }
28
+
29
+
30
+ def evaluate_feature(
31
+ name: str, tests: list[tuple[str, list[Value]]], env: Environment
32
+ ) -> bool | None:
33
+ """Result of ``(name)``, ``(name: value)`` or a range form; ``None`` when unknown."""
34
+ if name.startswith(("min-", "max-")):
35
+ if len(tests) != 1 or tests[0][0] != ":" or name[4:] not in _RANGE:
36
+ return None
37
+ name, tests = name[4:], [(">=" if name[:3] == "min" else "<=", tests[0][1])]
38
+ actual = _actual(name, env)
39
+ if name == "orientation":
40
+ if any(op != ":" for op, _ in tests):
41
+ return None
42
+ if not tests:
43
+ return True if actual is not None else None
44
+ wanted = ident(tests[0][1][0]) if len(tests[0][1]) == 1 else None
45
+ if wanted not in ("portrait", "landscape") or actual is None:
46
+ return None
47
+ return (wanted == "portrait") == (actual == 1.0)
48
+ if name not in _RANGE:
49
+ return None
50
+ if actual is None:
51
+ return None
52
+ if not tests:
53
+ return actual != 0
54
+ results = []
55
+ for op, values in tests:
56
+ expected = _value(name, values, env)
57
+ if expected is None:
58
+ return None
59
+ results.append(_COMPARE[op](actual, expected))
60
+ return all(results)
61
+
62
+
63
+ def _actual(name: str, env: Environment) -> float | None:
64
+ height = env.height
65
+ if name == "width":
66
+ return env.width
67
+ if name == "resolution":
68
+ return env.density
69
+ if height is None:
70
+ return None
71
+ if name == "height":
72
+ return height
73
+ if name == "orientation":
74
+ return 1.0 if height >= env.width else 0.0
75
+ if name == "aspect-ratio":
76
+ return None if height == 0 else env.width / height
77
+ return None
78
+
79
+
80
+ def _value(name: str, values: list[Value], env: Environment) -> float | None:
81
+ values = [value for value in values if not is_ws(value)]
82
+ if name == "aspect-ratio":
83
+ return _ratio(values, env)
84
+ if len(values) != 1:
85
+ return None
86
+ value = values[0]
87
+ if name == "resolution":
88
+ if isinstance(value, Token) and value.kind == "dimension":
89
+ scale = _RESOLUTION.get(value.unit.lower())
90
+ return None if scale is None else value.number * scale
91
+ return math.inf if ident(value, "infinite") else None
92
+ found = quantity(value, env)
93
+ if found is None or (not found[1] and found[0] != 0):
94
+ return None
95
+ return found[0]
96
+
97
+
98
+ def _ratio(values: list[Value], env: Environment) -> float | None:
99
+ """``<ratio>``: a non-negative number, optionally ``/`` another one."""
100
+ parts = [values] if len(values) == 1 else [values[:1], values[2:]]
101
+ if len(values) not in (1, 3):
102
+ return None
103
+ if len(values) == 3:
104
+ slash = values[1]
105
+ if not (isinstance(slash, Token) and slash.kind == "delim" and slash.value == "/"):
106
+ return None
107
+ numbers = []
108
+ for part in parts:
109
+ found = quantity(part[0], env) if len(part) == 1 else None
110
+ if found is None or found[1] or found[0] < 0:
111
+ return None
112
+ numbers.append(found[0])
113
+ if len(numbers) == 1:
114
+ return numbers[0]
115
+ return None if numbers[1] == 0 else numbers[0] / numbers[1]
srcset/_model.py ADDED
@@ -0,0 +1,111 @@
1
+ """Public data types shared by the parser, the builder and the selector."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import dataclass
7
+ from typing import NamedTuple
8
+
9
+ from ._numbers import format_density, int_text
10
+
11
+
12
+ class SrcsetError(ValueError):
13
+ """Raised when a value cannot be expressed as, or read from, a srcset attribute."""
14
+
15
+
16
+ def _positive_int(name: str, value: object) -> None:
17
+ if isinstance(value, bool) or not isinstance(value, int):
18
+ raise TypeError(f"{name} must be an int, got {type(value).__name__}")
19
+ if value <= 0:
20
+ raise SrcsetError(f"{name} must be greater than zero")
21
+
22
+
23
+ def _number(name: str, value: object) -> float:
24
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
25
+ raise TypeError(f"{name} must be a number, got {type(value).__name__}")
26
+ try:
27
+ number = float(value)
28
+ except OverflowError:
29
+ raise SrcsetError(f"{name} is too large") from None
30
+ if not math.isfinite(number):
31
+ raise SrcsetError(f"{name} must be finite, got {number}")
32
+ return number
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Candidate:
37
+ """One image candidate: a URL with at most a width or a density descriptor.
38
+
39
+ ``height`` is the future-compatible ``h`` descriptor, which browsers accept only next
40
+ to a width. A candidate with no descriptor stands for ``1x``.
41
+ """
42
+
43
+ url: str
44
+ width: int | None = None
45
+ density: float | None = None
46
+ height: int | None = None
47
+
48
+ def __post_init__(self) -> None:
49
+ if not isinstance(self.url, str):
50
+ raise TypeError(f"url must be a str, got {type(self.url).__name__}")
51
+ if self.width is not None:
52
+ _positive_int("width", self.width)
53
+ if self.height is not None:
54
+ _positive_int("height", self.height)
55
+ if self.density is not None:
56
+ density = _number("density", self.density)
57
+ if density < 0:
58
+ raise SrcsetError(f"density must not be negative, got {density}")
59
+ object.__setattr__(self, "density", density + 0.0)
60
+ if self.width is not None or self.height is not None:
61
+ raise SrcsetError("a candidate has either a density or a width, not both")
62
+ if self.height is not None and self.width is None:
63
+ raise SrcsetError("a height descriptor needs a width descriptor")
64
+
65
+ @property
66
+ def descriptor(self) -> str:
67
+ """The descriptors as written in a srcset value, ``""`` when there are none."""
68
+ if self.density is not None:
69
+ return format_density(self.density)
70
+ parts = [int_text(self.width) + "w"] if self.width is not None else []
71
+ if self.height is not None:
72
+ parts.append(int_text(self.height) + "h")
73
+ return " ".join(parts)
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Environment:
78
+ """What a browser knows when it picks an image: viewport, pixel ratio and font size.
79
+
80
+ Lengths are CSS pixels. ``height`` may be ``None`` when it is not known; media
81
+ conditions that need it then evaluate to unknown and do not match.
82
+ """
83
+
84
+ width: float
85
+ height: float | None = None
86
+ density: float = 1.0
87
+ font_size: float = 16.0
88
+
89
+ def __post_init__(self) -> None:
90
+ for name in ("width", "height", "density", "font_size"):
91
+ value = getattr(self, name)
92
+ if value is None and name == "height":
93
+ continue
94
+ number = _number(name, value)
95
+ if number < 0 or (number == 0 and name in ("density", "font_size")):
96
+ raise SrcsetError(f"{name} is out of range: {number}")
97
+ object.__setattr__(self, name, number + 0.0)
98
+
99
+
100
+ class ImageSource(NamedTuple):
101
+ """A URL from a normalized source set and the pixel density it stands for."""
102
+
103
+ url: str
104
+ density: float
105
+
106
+
107
+ class Issue(NamedTuple):
108
+ """An authoring error: a stable ``code`` and a readable ``message``."""
109
+
110
+ code: str
111
+ message: str
srcset/_numbers.py ADDED
@@ -0,0 +1,62 @@
1
+ """HTML number microsyntaxes, restricted to ASCII digits as the standard requires."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+
8
+ _NON_NEGATIVE_INTEGER = re.compile(r"[0-9]+")
9
+ _FLOATING_POINT = re.compile(r"-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?")
10
+
11
+
12
+ # Python refuses to convert very long digit strings in one go (the limit can be as low as
13
+ # 640 digits); converting in chunks keeps the HTML rule, which sets no length limit.
14
+ _CHUNK = 512
15
+
16
+
17
+ def to_int(digits: str) -> int:
18
+ """Exact value of a string of ASCII digits of any length."""
19
+ value = 0
20
+ for start in range(0, len(digits), _CHUNK):
21
+ chunk = digits[start : start + _CHUNK]
22
+ value = value * 10 ** len(chunk) + int(chunk)
23
+ return value
24
+
25
+
26
+ def int_text(value: int) -> str:
27
+ """Decimal text of a non-negative int of any size."""
28
+ parts: list[str] = []
29
+ while value >= 10**_CHUNK:
30
+ value, low = divmod(value, 10**_CHUNK)
31
+ parts.append(str(low).rjust(_CHUNK, "0"))
32
+ return str(value) + "".join(reversed(parts))
33
+
34
+
35
+ def is_non_negative_integer(text: str) -> bool:
36
+ """True for a valid non-negative integer: one or more ASCII digits."""
37
+ return _NON_NEGATIVE_INTEGER.fullmatch(text) is not None
38
+
39
+
40
+ def is_floating_point(text: str) -> bool:
41
+ """True for a valid floating-point number (no ``+``, no bare ``.``, no ``1.``)."""
42
+ return _FLOATING_POINT.fullmatch(text) is not None
43
+
44
+
45
+ def parse_floating_point(text: str) -> float | None:
46
+ """Value of a valid floating-point number; ``None`` when it rounds past the doubles.
47
+
48
+ Python rounds to the nearest double with ties to even, as the HTML rules do. The
49
+ rules have no negative zero; ``Candidate`` turns ``-0.0`` into ``0.0``.
50
+ """
51
+ value = float(text)
52
+ if math.isinf(value):
53
+ return None
54
+ return value
55
+
56
+
57
+ def format_density(density: float) -> str:
58
+ """Shortest text for a density that reads back as the same float, with its ``x``."""
59
+ text = repr(density)
60
+ if text.endswith(".0"):
61
+ text = text[:-2]
62
+ return text + "x"
srcset/_parse.py ADDED
@@ -0,0 +1,32 @@
1
+ """Parse a srcset attribute exactly as browsers do (WHATWG HTML 4.8.4.3.10)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._descriptors import parse_descriptors
6
+ from ._model import Candidate
7
+ from ._scan import RawCandidate, scan
8
+
9
+
10
+ def parse(value: str) -> list[Candidate]:
11
+ """Return the image candidates a browser keeps from a srcset attribute value.
12
+
13
+ Candidates whose descriptors are invalid, repeated or contradictory are dropped, as
14
+ browsers drop them; nothing raises for a malformed value.
15
+ """
16
+ if not isinstance(value, str):
17
+ raise TypeError(f"srcset value must be a str, got {type(value).__name__}")
18
+ candidates: list[Candidate] = []
19
+ for raw in scan(value):
20
+ if isinstance(raw, RawCandidate):
21
+ candidate = to_candidate(raw)
22
+ if candidate is not None:
23
+ candidates.append(candidate)
24
+ return candidates
25
+
26
+
27
+ def to_candidate(raw: RawCandidate) -> Candidate | None:
28
+ """The candidate for a raw entry, or ``None`` when the browser drops it."""
29
+ found = parse_descriptors(raw.tokens)
30
+ if not raw.url or found is None:
31
+ return None
32
+ return Candidate(raw.url, found.width, found.density, found.height)
srcset/_scan.py ADDED
@@ -0,0 +1,85 @@
1
+ """Split a srcset value into raw entries: the splitting loop and descriptor tokenizer.
2
+
3
+ A URL is a maximal run of non-whitespace, so a comma inside it (a data URI) never splits
4
+ the list. Only a comma that ends the URL, or one met while reading descriptors, separates
5
+ candidates. The raw entries keep what an authoring check needs to know about the text.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterator
11
+ from typing import NamedTuple
12
+
13
+ # ASCII whitespace in the HTML sense: no vertical tab, no non-ASCII spaces.
14
+ WHITESPACE = "\t\n\x0c\r "
15
+ _SEPARATORS = WHITESPACE + ","
16
+
17
+
18
+ class RawCandidate(NamedTuple):
19
+ url: str
20
+ tokens: list[str]
21
+ stray_commas: int # commas eaten by the splitting loop before this URL
22
+ trailing_commas: int # commas removed from the end of the URL
23
+
24
+
25
+ def scan(value: str) -> Iterator[RawCandidate | int]:
26
+ """Yield each raw candidate, then the number of stray commas left at the end."""
27
+ pos, end = 0, len(value)
28
+ while True:
29
+ start = pos
30
+ while pos < end and value[pos] in _SEPARATORS:
31
+ pos += 1
32
+ commas = value.count(",", start, pos)
33
+ if pos >= end:
34
+ yield commas
35
+ return
36
+ start = pos
37
+ while pos < end and value[pos] not in WHITESPACE:
38
+ pos += 1
39
+ url = value[start:pos]
40
+ stripped = url.rstrip(",")
41
+ if stripped != url:
42
+ yield RawCandidate(stripped, [], commas, len(url) - len(stripped))
43
+ continue
44
+ pos, tokens = _tokenize(value, pos)
45
+ yield RawCandidate(url, tokens, commas, 0)
46
+
47
+
48
+ def _tokenize(value: str, pos: int) -> tuple[int, list[str]]:
49
+ """Collect descriptor tokens up to a separating comma or the end of the input."""
50
+ end = len(value)
51
+ while pos < end and value[pos] in WHITESPACE:
52
+ pos += 1
53
+ tokens: list[str] = []
54
+ current: list[str] = []
55
+ state = "in descriptor"
56
+ while True:
57
+ c = value[pos] if pos < end else ""
58
+ if state == "in descriptor":
59
+ if c in WHITESPACE and c:
60
+ if current:
61
+ tokens.append("".join(current))
62
+ current = []
63
+ state = "after descriptor"
64
+ elif c in (",", ""):
65
+ if current:
66
+ tokens.append("".join(current))
67
+ return (pos + 1 if c else pos), tokens
68
+ else:
69
+ current.append(c)
70
+ if c == "(":
71
+ state = "in parens"
72
+ elif state == "in parens":
73
+ if not c:
74
+ tokens.append("".join(current))
75
+ return pos, tokens
76
+ current.append(c)
77
+ if c == ")":
78
+ state = "in descriptor"
79
+ else:
80
+ if not c:
81
+ return pos, tokens
82
+ if c not in WHITESPACE:
83
+ state = "in descriptor"
84
+ continue
85
+ pos += 1