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/__init__.py ADDED
@@ -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
+ ]
srcset/__main__.py ADDED
@@ -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())
srcset/_build.py ADDED
@@ -0,0 +1,57 @@
1
+ """Serialize image candidates into a srcset value that parses back to the same list."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Iterable
7
+
8
+ from ._descriptors import parse_descriptors
9
+ from ._model import Candidate, SrcsetError
10
+ from ._scan import WHITESPACE
11
+
12
+
13
+ def build(candidates: Iterable[Candidate | tuple[str, str]]) -> str:
14
+ """Join candidates into a srcset value, refusing anything that would not round-trip.
15
+
16
+ Items are ``Candidate`` values or ``(url, descriptor)`` pairs such as
17
+ ``("a.png", "320w")``. Raises ``SrcsetError`` for an empty URL, a URL holding ASCII
18
+ whitespace or starting or ending with a comma, and descriptors a browser would drop.
19
+ """
20
+ if isinstance(candidates, (str, bytes)):
21
+ raise TypeError("build takes an iterable of candidates, not a string")
22
+ parts: list[str] = []
23
+ for item in candidates:
24
+ candidate = _candidate(item)
25
+ _check_url(candidate.url)
26
+ descriptor = candidate.descriptor
27
+ parts.append(f"{candidate.url} {descriptor}" if descriptor else candidate.url)
28
+ return ", ".join(parts)
29
+
30
+
31
+ def _candidate(item: object) -> Candidate:
32
+ if isinstance(item, Candidate):
33
+ return item
34
+ if not isinstance(item, tuple) or len(item) != 2:
35
+ raise TypeError(f"expected a Candidate or a (url, descriptor) pair, got {item!r:.80}")
36
+ url, descriptor = item
37
+ if not isinstance(url, str) or not isinstance(descriptor, str):
38
+ raise TypeError("url and descriptor must both be str")
39
+ found = parse_descriptors(_split(descriptor))
40
+ if found is None:
41
+ raise SrcsetError(f"invalid descriptor: {descriptor!r:.80}")
42
+ return Candidate(url, found.width, found.density, found.height)
43
+
44
+
45
+ def _split(descriptor: str) -> list[str]:
46
+ # Commas and parentheses never survive the descriptor parser, so splitting on ASCII
47
+ # whitespace reads the text exactly as the parser's tokenizer would.
48
+ return [token for token in re.split(r"[\t\n\x0c\r ]+", descriptor) if token]
49
+
50
+
51
+ def _check_url(url: str) -> None:
52
+ if not url:
53
+ raise SrcsetError("candidate URL must not be empty")
54
+ if any(ch in WHITESPACE for ch in url):
55
+ raise SrcsetError(f"candidate URL must not contain ASCII whitespace: {url!r:.80}")
56
+ if url.startswith(",") or url.endswith(","):
57
+ raise SrcsetError(f"candidate URL must not start or end with a comma: {url!r:.80}")
srcset/_calc.py ADDED
@@ -0,0 +1,142 @@
1
+ """Lengths and math functions (``calc``, ``min``, ``clamp``, ``round``...), resolved to px.
2
+
3
+ A quantity is ``(value, is_length)``: a plain number or a length in CSS pixels. Font
4
+ relative units other than ``em`` and ``rem`` use fixed ratios, because the real values
5
+ depend on font metrics a library cannot know.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+
12
+ from ._css_reader import Token
13
+ from ._css_values import Block, Value, ident, is_ws, strip
14
+ from ._math_functions import CONSTANTS, STRATEGIES, Quantity, apply
15
+ from ._model import Environment
16
+
17
+ _ABSOLUTE = {"px": 1.0, "in": 96.0, "cm": 96 / 2.54, "mm": 96 / 25.4, "q": 96 / 101.6}
18
+ _ABSOLUTE.update({"pt": 96 / 72, "pc": 16.0})
19
+ _FONT = {"em": 1.0, "ex": 0.5, "ch": 0.5, "cap": 0.7, "ic": 1.0, "lh": 1.2}
20
+ _MATH = frozenset((
21
+ "calc", "min", "max", "clamp", "abs", "sign", "round", "mod", "rem", "hypot", "sqrt",
22
+ "pow", "exp", "log",
23
+ )) # fmt: skip
24
+
25
+
26
+ def unit_px(unit: str, env: Environment) -> float | None:
27
+ """Pixels in one ``unit`` (ASCII case-insensitive), or ``None`` if not a length unit."""
28
+ unit = unit.lower() if unit.isascii() else unit
29
+ if unit in _ABSOLUTE:
30
+ return _ABSOLUTE[unit]
31
+ font = unit[1:] if unit.startswith("r") and unit[1:] in _FONT else unit
32
+ if font in _FONT:
33
+ return _FONT[font] * env.font_size
34
+ axis = unit[1:] if unit[:1] in ("s", "l", "d") and len(unit) > 2 else unit
35
+ width, height = env.width, env.height
36
+ sizes = {"vw": width, "vi": width, "vh": height, "vb": height}
37
+ if axis in sizes:
38
+ value = sizes[axis]
39
+ return None if value is None else value / 100
40
+ if axis in ("vmin", "vmax"):
41
+ if height is None:
42
+ return None
43
+ return (min if axis == "vmin" else max)(width, height) / 100
44
+ return None
45
+
46
+
47
+ def quantity(value: Value, env: Environment) -> Quantity | None:
48
+ """A number, a length or a math function as a quantity; ``None`` when invalid."""
49
+ if isinstance(value, Block):
50
+ if value.name is None or value.name.lower() not in _MATH:
51
+ return None
52
+ result = _function(value.name.lower(), value.items, env)
53
+ elif value.kind == "number":
54
+ result = (value.number, False)
55
+ elif value.kind == "dimension":
56
+ scale = unit_px(value.unit, env)
57
+ result = None if scale is None else (value.number * scale, True)
58
+ else:
59
+ return None
60
+ if result is None or not math.isfinite(result[0]):
61
+ return None
62
+ return result
63
+
64
+
65
+ def _function(name: str, items: list[Value], env: Environment) -> Quantity | None:
66
+ args = _split_args(items)
67
+ if name == "calc":
68
+ return _sum(args[0], env) if len(args) == 1 else None
69
+ strategy = "nearest"
70
+ if name == "round" and len(args) > 1 and len(args[0]) == 1:
71
+ word = ident(args[0][0], *STRATEGIES)
72
+ if word is not None:
73
+ strategy, args = word, args[1:]
74
+ values = [_sum(arg, env) for arg in args]
75
+ found = [value for value in values if value is not None]
76
+ if len(found) != len(values):
77
+ return None
78
+ return apply(name, found, strategy)
79
+
80
+
81
+ def _split_args(items: list[Value]) -> list[list[Value]]:
82
+ args: list[list[Value]] = [[]]
83
+ for item in items:
84
+ if isinstance(item, Token) and item.kind == "comma":
85
+ args.append([])
86
+ else:
87
+ args[-1].append(item)
88
+ return [strip(arg) for arg in args]
89
+
90
+
91
+ def _sum(items: list[Value], env: Environment) -> Quantity | None:
92
+ """``<calc-sum>``: products joined by ``+`` or ``-`` with whitespace on both sides."""
93
+ items = strip(items)
94
+ terms: list[list[Value]] = [[]]
95
+ signs = [1.0]
96
+ for i, item in enumerate(items):
97
+ op = item.value if isinstance(item, Token) and item.kind == "delim" else ""
98
+ if op in ("+", "-") and 0 < i < len(items) - 1:
99
+ if not (is_ws(items[i - 1]) and is_ws(items[i + 1])):
100
+ return None
101
+ terms.append([])
102
+ signs.append(1.0 if op == "+" else -1.0)
103
+ else:
104
+ terms[-1].append(item)
105
+ total: Quantity | None = None
106
+ for sign, term in zip(signs, terms, strict=True):
107
+ value = _product(strip(term), env)
108
+ if value is None or (total is not None and total[1] != value[1]):
109
+ return None
110
+ total = (sign * value[0] + (total[0] if total else 0.0), value[1])
111
+ return total
112
+
113
+
114
+ def _product(items: list[Value], env: Environment) -> Quantity | None:
115
+ """``<calc-product>``: values joined by ``*`` or ``/``; a divisor must be a number."""
116
+ operands = [item for item in items if not is_ws(item)]
117
+ if len(operands) % 2 == 0:
118
+ return None
119
+ result = _operand(operands[0], env)
120
+ for op, item in zip(operands[1::2], operands[2::2], strict=True):
121
+ right = _operand(item, env)
122
+ symbol = op.value if isinstance(op, Token) and op.kind == "delim" else ""
123
+ if result is None or right is None or symbol not in ("*", "/"):
124
+ return None
125
+ if symbol == "/":
126
+ if right[1] or right[0] == 0:
127
+ return None
128
+ result = (result[0] / right[0], result[1])
129
+ elif result[1] and right[1]:
130
+ return None
131
+ else:
132
+ result = (result[0] * right[0], result[1] or right[1])
133
+ return result
134
+
135
+
136
+ def _operand(value: Value, env: Environment) -> Quantity | None:
137
+ if isinstance(value, Block) and value.name is None and value.opener == "(":
138
+ return _sum(value.items, env)
139
+ word = ident(value)
140
+ if word is not None:
141
+ return (CONSTANTS[word], False) if word in CONSTANTS else None
142
+ return quantity(value, env)
srcset/_cli.py ADDED
@@ -0,0 +1,78 @@
1
+ """Command line: ``srcset parse``, ``srcset select`` and ``srcset check``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Sequence
9
+
10
+ from ._model import Environment, SrcsetError
11
+ from ._numbers import int_text
12
+ from ._parse import parse
13
+ from ._select import select
14
+ from ._validate import validate
15
+
16
+
17
+ def _parser() -> argparse.ArgumentParser:
18
+ parser = argparse.ArgumentParser(prog="srcset", description="Read HTML srcset and sizes.")
19
+ commands = parser.add_subparsers(dest="command", required=True)
20
+ read = commands.add_parser("parse", help="print the candidates as JSON")
21
+ read.add_argument("srcset")
22
+ pick = commands.add_parser("select", help="print the URL a browser would fetch")
23
+ pick.add_argument("srcset")
24
+ pick.add_argument("--sizes", default="", help="the sizes attribute")
25
+ pick.add_argument("--src", default="", help="the src attribute, used as 1x")
26
+ pick.add_argument("--width", type=float, default=1280.0, help="viewport width in px")
27
+ pick.add_argument("--height", type=float, default=None, help="viewport height in px")
28
+ pick.add_argument("--dpr", type=float, default=1.0, help="device pixel ratio")
29
+ pick.add_argument("--json", action="store_true", help="print URL and density as JSON")
30
+ check = commands.add_parser("check", help="list authoring errors; exit 1 if any")
31
+ check.add_argument("srcset")
32
+ check.add_argument("--sizes", default=None, help="the sizes attribute, if present")
33
+ return parser
34
+
35
+
36
+ def main(argv: Sequence[str] | None = None) -> int:
37
+ """Run the command line; returns the exit status."""
38
+ args = _parser().parse_args(argv)
39
+ if args.command == "parse":
40
+ rows = [
41
+ {"url": c.url, "width": _int(c.width), "density": c.density, "height": _int(c.height)}
42
+ for c in parse(args.srcset)
43
+ ]
44
+ _say(json.dumps(rows))
45
+ return 0
46
+ if args.command == "select":
47
+ try:
48
+ env = Environment(args.width, args.height, args.dpr)
49
+ except SrcsetError as error:
50
+ print(f"srcset: {error}", file=sys.stderr)
51
+ return 2
52
+ chosen = select(args.srcset, env, sizes=args.sizes, src=args.src)
53
+ if chosen is None:
54
+ print("srcset: no image candidate", file=sys.stderr)
55
+ return 1
56
+ if args.json:
57
+ _say(json.dumps({"url": chosen.url, "density": chosen.density}))
58
+ else:
59
+ _say(chosen.url)
60
+ return 0
61
+ issues = validate(args.srcset, args.sizes)
62
+ for issue in issues:
63
+ _say(f"{issue.code}: {issue.message}")
64
+ return 1 if issues else 0
65
+
66
+
67
+ def _int(value: int | None) -> int | str | None:
68
+ # json cannot write an int past the interpreter's digit limit; such a width is text.
69
+ return int_text(value) if value is not None and value >= 10**400 else value
70
+
71
+
72
+ def _say(text: str) -> None:
73
+ """Print a line that the console encoding may not cover, escaping what it cannot hold.
74
+
75
+ A URL can hold any character, and a Windows pipe defaults to a legacy code page.
76
+ """
77
+ encoding = sys.stdout.encoding or "utf-8"
78
+ print(text.encode(encoding, "backslashreplace").decode(encoding))
srcset/_css_reader.py ADDED
@@ -0,0 +1,98 @@
1
+ """Character-level helpers for the CSS tokenizer: the token type and an input cursor."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import NamedTuple
6
+
7
+
8
+ class Token(NamedTuple):
9
+ kind: str # ident, function, number, dimension, percentage, delim, ws, (, ), ...
10
+ value: str = "" # name, unit-less text or the delim character
11
+ number: float = 0.0
12
+ unit: str = ""
13
+
14
+
15
+ def preprocess(text: str) -> str:
16
+ text = text.replace("\r\n", "\n").replace("\r", "\n").replace("\x0c", "\n")
17
+ return "".join("\ufffd" if c == "\0" or 0xD800 <= ord(c) <= 0xDFFF else c for c in text)
18
+
19
+
20
+ # Non-ASCII ident code points (CSS Syntax 3, 4.2), as inclusive ranges.
21
+ _NON_ASCII_IDENT = (
22
+ (0xB7, 0xB7), (0xC0, 0xD6), (0xD8, 0xF6), (0xF8, 0x37D), (0x37F, 0x1FFF),
23
+ (0x200C, 0x200D), (0x203F, 0x2040), (0x2070, 0x218F), (0x2C00, 0x2FEF),
24
+ (0x3001, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFFD), (0x10000, 0x10FFFF),
25
+ ) # fmt: skip
26
+
27
+
28
+ def ident_start(c: str) -> bool:
29
+ if c.isascii():
30
+ return c.isalpha() or c == "_"
31
+ code = ord(c)
32
+ return any(low <= code <= high for low, high in _NON_ASCII_IDENT)
33
+
34
+
35
+ def ident_char(c: str) -> bool:
36
+ return ident_start(c) or (c.isascii() and c.isdigit()) or c == "-"
37
+
38
+
39
+ def digit(c: str) -> bool:
40
+ return c != "" and c in "0123456789"
41
+
42
+
43
+ def is_escape(a: str, b: str) -> bool:
44
+ return a == "\\" and b != "\n"
45
+
46
+
47
+ class Reader:
48
+ def __init__(self, text: str) -> None:
49
+ self.text = text
50
+ self.pos = 0
51
+
52
+ def peek(self, n: int = 0) -> str:
53
+ i = self.pos + n
54
+ return self.text[i] if i < len(self.text) else ""
55
+
56
+ def starts_ident(self, n: int = 0) -> bool:
57
+ a, b, c = self.peek(n), self.peek(n + 1), self.peek(n + 2)
58
+ if a == "-":
59
+ return ident_start(b) or b == "-" or is_escape(b, c)
60
+ return ident_start(a) or is_escape(a, b)
61
+
62
+ def starts_number(self) -> bool:
63
+ a, b, c = self.peek(), self.peek(1), self.peek(2)
64
+ if a in ("+", "-") and a:
65
+ return digit(b) or (b == "." and digit(c))
66
+ return digit(a) or (a == "." and digit(b))
67
+
68
+ def escape(self) -> str:
69
+ """Consume an escape whose backslash is already consumed."""
70
+ c = self.peek()
71
+ if not c:
72
+ return "\ufffd"
73
+ self.pos += 1
74
+ if c not in "0123456789abcdefABCDEF":
75
+ return c
76
+ digits = c
77
+ while len(digits) < 6 and self.peek() and self.peek() in "0123456789abcdefABCDEF":
78
+ digits += self.peek()
79
+ self.pos += 1
80
+ if self.peek() and self.peek() in " \t\n":
81
+ self.pos += 1
82
+ code = int(digits, 16)
83
+ if code == 0 or 0xD800 <= code <= 0xDFFF or code > 0x10FFFF:
84
+ return "\ufffd"
85
+ return chr(code)
86
+
87
+ def name(self) -> str:
88
+ out: list[str] = []
89
+ while True:
90
+ c = self.peek()
91
+ if ident_char(c):
92
+ out.append(c)
93
+ self.pos += 1
94
+ elif is_escape(c, self.peek(1)):
95
+ self.pos += 1
96
+ out.append(self.escape())
97
+ else:
98
+ return "".join(out)
srcset/_css_tokens.py ADDED
@@ -0,0 +1,152 @@
1
+ """A CSS Syntax 3 tokenizer, complete enough to read a sizes attribute like a browser.
2
+
3
+ Comments vanish, escapes are decoded (``1\\p\\x`` is ``1px``) and every bracket becomes
4
+ its own token so the component value step can match blocks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from ._css_reader import Reader, Token, digit, ident_char, is_escape, preprocess
10
+
11
+ _SIMPLE = {"(": "(", ")": ")", "[": "[", "]": "]", "{": "{", "}": "}"}
12
+ _WS = " \t\n"
13
+ _SIMPLE.update({",": "comma", ":": "colon", ";": "semicolon"})
14
+
15
+
16
+ def tokenize(text: str) -> list[Token]:
17
+ """Split CSS text into tokens; comments are dropped."""
18
+ reader = Reader(preprocess(text))
19
+ tokens: list[Token] = []
20
+ while True:
21
+ while reader.peek() == "/" and reader.peek(1) == "*":
22
+ end = reader.text.find("*/", reader.pos + 2)
23
+ reader.pos = len(reader.text) if end < 0 else end + 2
24
+ c = reader.peek()
25
+ if not c:
26
+ return tokens
27
+ tokens.append(_next(reader, c))
28
+
29
+
30
+ def _next(reader: Reader, c: str) -> Token:
31
+ if c in " \t\n":
32
+ while reader.peek() and reader.peek() in " \t\n":
33
+ reader.pos += 1
34
+ return Token("ws")
35
+ if c in "\"'":
36
+ reader.pos += 1
37
+ return _string(reader, c)
38
+ if c in _SIMPLE:
39
+ reader.pos += 1
40
+ return Token(_SIMPLE[c], c)
41
+ if reader.starts_number():
42
+ return _numeric(reader)
43
+ if c == "-" and reader.peek(1) == "-" and reader.peek(2) == ">":
44
+ reader.pos += 3
45
+ return Token("cdc", "-->")
46
+ if reader.starts_ident():
47
+ return _ident_like(reader)
48
+ if c == "#" and (ident_char(reader.peek(1)) or is_escape(reader.peek(1), reader.peek(2))):
49
+ reader.pos += 1
50
+ return Token("hash", reader.name())
51
+ if c == "@" and reader.starts_ident(1):
52
+ reader.pos += 1
53
+ return Token("at-keyword", reader.name())
54
+ if reader.text.startswith("<!--", reader.pos):
55
+ reader.pos += 4
56
+ return Token("cdo", "<!--")
57
+ reader.pos += 1
58
+ return Token("delim", c)
59
+
60
+
61
+ def _string(reader: Reader, quote: str) -> Token:
62
+ out: list[str] = []
63
+ while True:
64
+ c = reader.peek()
65
+ if not c or c == quote:
66
+ reader.pos += 1 if c else 0
67
+ return Token("string", "".join(out))
68
+ if c == "\n":
69
+ return Token("bad-string")
70
+ reader.pos += 1
71
+ if c != "\\":
72
+ out.append(c)
73
+ elif reader.peek() == "\n":
74
+ reader.pos += 1
75
+ elif reader.peek():
76
+ out.append(reader.escape())
77
+
78
+
79
+ def _numeric(reader: Reader) -> Token:
80
+ start = reader.pos
81
+ if reader.peek() in ("+", "-"):
82
+ reader.pos += 1
83
+ while digit(reader.peek()):
84
+ reader.pos += 1
85
+ if reader.peek() == "." and digit(reader.peek(1)):
86
+ reader.pos += 1
87
+ while digit(reader.peek()):
88
+ reader.pos += 1
89
+ e, sign, third = reader.peek(), reader.peek(1), reader.peek(2)
90
+ if e in ("e", "E") and e and (digit(sign) or (sign in ("+", "-") and sign and digit(third))):
91
+ reader.pos += 2
92
+ while digit(reader.peek()):
93
+ reader.pos += 1
94
+ text = reader.text[start : reader.pos]
95
+ number = float(text)
96
+ if reader.starts_ident():
97
+ return Token("dimension", text, number, reader.name())
98
+ if reader.peek() == "%":
99
+ reader.pos += 1
100
+ return Token("percentage", text, number)
101
+ return Token("number", text, number)
102
+
103
+
104
+ def _ident_like(reader: Reader) -> Token:
105
+ name = reader.name()
106
+ if reader.peek() != "(":
107
+ return Token("ident", name)
108
+ reader.pos += 1
109
+ if name.lower() != "url":
110
+ return Token("function", name)
111
+ while reader.peek() in _WS and reader.peek() and reader.peek(1) in _WS and reader.peek(1):
112
+ reader.pos += 1
113
+ after = reader.peek(1) if reader.peek() in _WS and reader.peek() else reader.peek()
114
+ if after and after in "\"'":
115
+ return Token("function", name)
116
+ return _url(reader)
117
+
118
+
119
+ def _url(reader: Reader) -> Token:
120
+ while reader.peek() and reader.peek() in _WS:
121
+ reader.pos += 1
122
+ out: list[str] = []
123
+ while True:
124
+ c = reader.peek()
125
+ reader.pos += 1 if c else 0
126
+ if not c or c == ")":
127
+ return Token("url", "".join(out))
128
+ if c in _WS:
129
+ while reader.peek() and reader.peek() in _WS:
130
+ reader.pos += 1
131
+ if reader.peek() in (")", ""):
132
+ reader.pos += 1 if reader.peek() else 0
133
+ return Token("url", "".join(out))
134
+ elif c == "\\" and is_escape(c, reader.peek()):
135
+ out.append(reader.escape())
136
+ continue
137
+ elif c not in "\"'(\\" and not _non_printable(c):
138
+ out.append(c)
139
+ continue
140
+ while reader.peek() not in (")", ""):
141
+ if is_escape(reader.peek(), reader.peek(1)):
142
+ reader.pos += 1
143
+ reader.escape()
144
+ else:
145
+ reader.pos += 1
146
+ reader.pos += 1 if reader.peek() else 0
147
+ return Token("bad-url")
148
+
149
+
150
+ def _non_printable(c: str) -> bool:
151
+ code = ord(c)
152
+ return code <= 8 or code == 0x0B or 0x0E <= code <= 0x1F or code == 0x7F
srcset/_css_values.py ADDED
@@ -0,0 +1,113 @@
1
+ """CSS component values: tokens grouped into matched blocks and functions (CSS Syntax 3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import TypeAlias
7
+
8
+ from ._css_reader import Token
9
+ from ._css_tokens import tokenize
10
+
11
+ _CLOSE = {"(": ")", "[": "]", "{": "}"}
12
+ MAX_DEPTH = 32
13
+
14
+
15
+ @dataclass
16
+ class Block:
17
+ """A ``(``, ``[`` or ``{`` block, or a function when ``name`` is set."""
18
+
19
+ opener: str
20
+ name: str | None = None
21
+ items: list[Value] = field(default_factory=list)
22
+
23
+
24
+ Value: TypeAlias = "Token | Block"
25
+
26
+
27
+ def comma_separated(text: str) -> list[list[Value]]:
28
+ """Parse a comma-separated list of component values; commas in blocks do not split."""
29
+ tokens = tokenize(text)
30
+ tokens.reverse()
31
+ groups: list[list[Value]] = [[]]
32
+ while tokens:
33
+ token = tokens.pop()
34
+ if token.kind == "comma":
35
+ groups.append([])
36
+ else:
37
+ groups[-1].append(_component(token, tokens))
38
+ return groups
39
+
40
+
41
+ def _component(token: Token, stack: list[Token], depth: int = 0) -> Value:
42
+ if token.kind == "function":
43
+ return _block(Block("(", token.value), stack, depth + 1)
44
+ if token.kind in _CLOSE:
45
+ return _block(Block(token.kind), stack, depth + 1)
46
+ return token
47
+
48
+
49
+ def _block(block: Block, stack: list[Token], depth: int) -> Value:
50
+ """Fill a block up to its closing token or the end of input (unclosed is fine).
51
+
52
+ Past ``MAX_DEPTH`` levels the block is skipped and replaced by a ``too-deep`` token
53
+ that no grammar accepts, so hostile nesting cannot exhaust the call stack.
54
+ """
55
+ if depth > MAX_DEPTH:
56
+ return _skip(_CLOSE[block.opener], stack)
57
+ close = _CLOSE[block.opener]
58
+ while stack:
59
+ token = stack.pop()
60
+ if token.kind == close:
61
+ return block
62
+ block.items.append(_component(token, stack, depth))
63
+ return block
64
+
65
+
66
+ def _skip(close: str, stack: list[Token]) -> Token:
67
+ closers = [close]
68
+ while stack and closers:
69
+ token = stack.pop()
70
+ if token.kind == closers[-1]:
71
+ closers.pop()
72
+ elif token.kind == "function":
73
+ closers.append(")")
74
+ elif token.kind in _CLOSE:
75
+ closers.append(_CLOSE[token.kind])
76
+ return Token("too-deep")
77
+
78
+
79
+ def is_ws(value: Value) -> bool:
80
+ return isinstance(value, Token) and value.kind == "ws"
81
+
82
+
83
+ def strip(values: list[Value]) -> list[Value]:
84
+ """Drop whitespace tokens at both ends."""
85
+ start, end = 0, len(values)
86
+ while start < end and is_ws(values[start]):
87
+ start += 1
88
+ while end > start and is_ws(values[end - 1]):
89
+ end -= 1
90
+ return values[start:end]
91
+
92
+
93
+ def ident(value: Value, *names: str) -> str | None:
94
+ """The lower-cased name of an identifier, if it is one (and one of ``names``)."""
95
+ if isinstance(value, Token) and value.kind == "ident":
96
+ name = _ascii_lower(value.value)
97
+ return name if not names or name in names else None
98
+ return None
99
+
100
+
101
+ def _ascii_lower(text: str) -> str:
102
+ return "".join(c.lower() if c.isascii() else c for c in text)
103
+
104
+
105
+ def is_any_value(values: list[Value]) -> bool:
106
+ """True when the values match ``<any-value>``: no stray closers, no bad tokens."""
107
+ for value in values:
108
+ if isinstance(value, Block):
109
+ if not is_any_value(value.items):
110
+ return False
111
+ elif value.kind in (")", "]", "}", "bad-string", "bad-url", "too-deep"):
112
+ return False
113
+ return True