errdown 0.1.0a0__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.
errdown/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """errdown: Cloudflare-compatible structured errors (RFC 9457) for every HTTP error an agent hits.
2
+
3
+ Pre-release (alpha). Zero dependencies. `normalize()` never raises.
4
+ """
5
+ from ._decide import agent_accept_header, backoff, decide
6
+ from ._normalize import normalize, sanitize
7
+ from ._render import ordered, to_json, to_markdown
8
+
9
+ __all__ = ["normalize", "to_markdown", "to_json", "ordered", "decide", "backoff", "agent_accept_header", "sanitize"]
10
+ __version__ = "0.1.0a0"
errdown/_decide.py ADDED
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import random as _random
4
+ from typing import Any, Callable, Dict, Optional
5
+
6
+ _ESCALATE = {"challenge", "access_denied", "legal", "auth_required"}
7
+
8
+
9
+ def decide(p: Dict[str, Any]) -> Dict[str, Any]:
10
+ """Cloudflare's recommended control flow: retryable -> wait; owner action -> escalate; else fail fast."""
11
+ cat = p.get("error_category")
12
+ if cat == "challenge":
13
+ return {"action": "escalate", "reason": "challenge"}
14
+ if p.get("retryable"):
15
+ ra = p.get("retry_after")
16
+ return {"action": "retry", "after_seconds": 5 if ra is None else ra}
17
+ if p.get("owner_action_required"):
18
+ return {"action": "escalate", "reason": "owner_action_required"}
19
+ if cat in _ESCALATE:
20
+ return {"action": "escalate", "reason": cat}
21
+ return {"action": "fail", "reason": p.get("error_name")}
22
+
23
+
24
+ def backoff(attempt: int, *, base: float = 1, max: float = 60, min: float = 0,
25
+ random: Optional[Callable[[], float]] = None) -> float:
26
+ """Exponential backoff with full jitter. attempt starts at 0. Honors a server-given minimum."""
27
+ rand = random or _random.random
28
+ ceiling = _min(max, base * 2 ** _max(0, attempt))
29
+ return _max(min, rand() * ceiling)
30
+
31
+
32
+ _min, _max = min, max # keyword args above shadow the builtins inside backoff()
33
+
34
+
35
+ def agent_accept_header(mode: str = "markdown") -> str:
36
+ """The Accept header Cloudflare recommends for agents."""
37
+ return "application/json, */*" if mode == "json" else "text/markdown, */*"
@@ -0,0 +1,130 @@
1
+ """Port of packages/js/src/fingerprints.ts. Keep in the same order; JS `$` is written `\\Z`."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ I = re.I
8
+
9
+
10
+ def _fp(id: str, source: str, confidence: float, *, status: Optional[List[int]] = None,
11
+ header: Optional[tuple] = None, body: Optional[List[Any]] = None, **over: Any) -> Dict[str, Any]:
12
+ return {"id": id, "source": source, "confidence": confidence, "status": status,
13
+ "header": (header[0], re.compile(header[1], header[2] if len(header) > 2 else 0)) if header else None,
14
+ "body": [re.compile(b) if isinstance(b, str) else re.compile(*b) for b in body] if body else None,
15
+ **over}
16
+
17
+
18
+ CHALLENGES: List[Dict[str, Any]] = [
19
+ _fp("cloudflare_challenge", "cloudflare", 0.95, header=("cf-mitigated", r"challenge", I),
20
+ error_name="cloudflare_challenge", title="Bot verification required"),
21
+ _fp("cloudflare_challenge_page", "cloudflare", 0.9,
22
+ body=[(r"<title>Just a moment\.\.\.</title>|challenges\.cloudflare\.com|cf-chl-|_cf_chl_opt", I)],
23
+ error_name="cloudflare_challenge", title="Bot verification required"),
24
+ _fp("recaptcha", "unknown", 0.85,
25
+ body=[(r"google\.com/recaptcha|g-recaptcha", I), (r"captcha|verify you are human|unusual traffic", I)],
26
+ error_name="recaptcha_challenge", title="CAPTCHA required"),
27
+ _fp("hcaptcha", "unknown", 0.85, body=[(r"hcaptcha\.com|h-captcha", I)],
28
+ error_name="hcaptcha_challenge", title="CAPTCHA required"),
29
+ _fp("aws_waf_captcha", "aws-cloudfront", 0.9, header=("x-amzn-waf-action", r"captcha|challenge", I),
30
+ error_name="aws_waf_challenge", title="Bot verification required"),
31
+ _fp("datadome", "unknown", 0.85, header=("x-datadome", r"."),
32
+ body=[(r"captcha-delivery\.com|datadome", I)],
33
+ error_name="datadome_challenge", title="Bot verification required"),
34
+ _fp("perimeterx", "unknown", 0.85, body=[(r"px-captcha|perimeterx|_pxCaptcha", I)],
35
+ error_name="perimeterx_challenge", title="Bot verification required"),
36
+ _fp("indeed_bot_detection", "unknown", 0.85, body=[(r"from=bot-detection", I)],
37
+ error_name="bot_detection_redirect", title="Bot verification required"),
38
+ _fp("linkedin_999", "linkedin", 0.85, status=[999], header=("x-li-fabric", r"."),
39
+ error_name="linkedin_bot_block", title="Blocked as automated traffic"),
40
+ _fp("network_security_block", "unknown", 0.85, status=[403], body=[(r"blocked by network security", I)],
41
+ category="access_denied", error_name="network_security_block", title="Blocked by network security"),
42
+ _fp("akamai_bot", "akamai", 0.8, status=[403],
43
+ body=[(r"<title>Access Denied</title>", I), (r"Reference #[0-9]+\.[0-9a-f]+", I)],
44
+ category="access_denied", error_name="akamai_access_denied", title="Access denied"),
45
+ ]
46
+
47
+ PAGES: List[Dict[str, Any]] = [
48
+ _fp("cloudflare_blocked", "cloudflare", 0.9,
49
+ body=[(r"cf-error-details", I), (r"Sorry, you have been blocked", I)],
50
+ category="access_denied", error_name="cloudflare_blocked", title="Blocked by the site's firewall",
51
+ retryable=False, owner_action_required=False,
52
+ detail="The site's Cloudflare firewall blocked this request."),
53
+ _fp("cloudflare_legacy", "cloudflare", 0.9, body=[(r"cf-error-details|cf-wrapper|Cloudflare Ray ID", I)]),
54
+ _fp("nginx_default", "nginx", 0.9, body=[(r"<center>nginx(/[0-9.]+)?</center>", I)]),
55
+ _fp("apache_default", "apache", 0.9, body=[(r"<address>Apache(/[0-9.]+)?[^<]*Server at", I)]),
56
+ _fp("apache_header", "apache", 0.7, header=("server", r"^Apache", I),
57
+ body=[(r"<title>[0-9]{3} [^<]+</title>", I)]),
58
+ _fp("caddy", "caddy", 0.75, header=("server", r"^Caddy", I)),
59
+ _fp("envoy_upstream", "envoy", 0.9,
60
+ body=[(r"upstream connect error or disconnect/reset before headers|no healthy upstream", I)],
61
+ category="upstream_unavailable", error_name="envoy_upstream_unavailable",
62
+ title="Upstream unavailable", retryable=True),
63
+ _fp("envoy_timeout", "envoy", 0.9, body=[r"^upstream request timeout\s*\Z"],
64
+ category="upstream_unavailable", error_name="envoy_upstream_timeout",
65
+ title="Upstream timeout", retryable=True),
66
+ _fp("envoy_empty", "envoy", 0.75, header=("server", r"^envoy\Z", I), body=[r"^\s*\Z"]),
67
+ _fp("traefik_404", "traefik", 0.8, body=[r"^404 page not found\s*\Z"]),
68
+ _fp("traefik", "traefik", 0.65,
69
+ body=[r"^(Bad Gateway|Gateway Timeout|Service Unavailable|Too Many Requests|Request Entity Too Large)\s*\Z"]),
70
+ _fp("aws_alb", "aws-alb", 0.9, header=("server", r"^awselb", I)),
71
+ _fp("aws_apigateway", "aws-apigateway", 0.85, header=("x-amzn-errortype", r".")),
72
+ _fp("aws_cloudfront", "aws-cloudfront", 0.9, body=[(r"Generated by cloudfront \(CloudFront\)", I)]),
73
+ _fp("vercel", "vercel", 0.85, header=("x-vercel-error", r".")),
74
+ _fp("vercel_hosted", "vercel", 0.6, header=("x-vercel-id", r".")),
75
+ _fp("github_pages", "github-pages", 0.85, status=[404], header=("server", r"^GitHub\.com\Z", I),
76
+ body=[(r"GitHub Pages|There isn't a GitHub Pages site here|Site not found", I)]),
77
+ _fp("netlify", "netlify", 0.8, header=("server", r"^Netlify", I)),
78
+ _fp("heroku_no_such_app", "heroku", 0.95, body=[(r"<title>No such app</title>", I)],
79
+ category="not_found", error_name="heroku_no_such_app", title="No such app",
80
+ retryable=False, detail="There is no Heroku app at this address."),
81
+ _fp("heroku_app_error", "heroku", 0.9,
82
+ body=[(r"herokucdn\.com/error-pages|Application error", I), (r"heroku", I)],
83
+ category="server_error", error_name="heroku_application_error",
84
+ title="Application error", retryable=True),
85
+ _fp("render_no_server", "render", 0.9, header=("x-render-routing", r"no-server", I),
86
+ category="not_found", error_name="render_no_server", title="No service at this address",
87
+ detail="There is no Render service at this address."),
88
+ _fp("render", "render", 0.75, header=("x-render-origin-server", r".")),
89
+ _fp("gfe_default", "google-frontend", 0.8,
90
+ body=[(r"<h1>Error: (Page )?Not Found</h1>", I), (r"The requested URL was not found on this server", I)]),
91
+ _fp("google_404", "google-frontend", 0.8, body=[r"<title>Error 404 \(Not Found\)!!1</title>"]),
92
+ _fp("gfe", "google-frontend", 0.8, header=("server", r"^(Google Frontend|GFE|gws)", I)),
93
+ _fp("express_default", "express", 0.85, header=("x-powered-by", r"^Express\Z", I),
94
+ body=[(r"<title>Error</title>", I), (r"<pre>", I)]),
95
+ _fp("werkzeug_default", "werkzeug", 0.85,
96
+ body=[(r"<title>[0-9]{3} [^<]+</title>\s*<h1>[^<]+</h1>\s*<p>", I),
97
+ (r"(If you entered the URL manually please check your spelling|The server encountered an internal error and was unable to complete your request|You don't have the permission to access the requested resource)", I)]),
98
+ _fp("django_default", "django", 0.85,
99
+ body=[(r"(<title>Server Error \(500\)</title>|The requested resource was not found on this server\.|<title>403 Forbidden</title>[\s\S]{0,200}<h1>403 Forbidden</h1>)", I)]),
100
+ _fp("tomcat_default", "tomcat", 0.9, body=[r"<title>HTTP Status [0-9]{3} – [^<]+</title>"]),
101
+ _fp("jetty_default", "jetty", 0.9, body=[r"<h2>HTTP ERROR [0-9]{3}"]),
102
+ _fp("python_http_server", "python-http-server", 0.8,
103
+ body=[r"<title>Error response</title>", r"Error code explanation:"]),
104
+ _fp("uvicorn_plain", "uvicorn", 0.7, header=("server", r"^uvicorn\Z", I),
105
+ body=[r"^(Internal Server Error|Not Found|Method Not Allowed)\s*\Z"]),
106
+ _fp("envoy_plain", "envoy", 0.75, header=("server", r"^envoy\Z", I), body=[r"^[A-Z][A-Za-z -]{2,40}\Z"]),
107
+ _fp("fastly", "fastly", 0.8, body=[(r"Varnish cache server|Fastly error", I)]),
108
+ ]
109
+
110
+
111
+ def matches(fp: Dict[str, Any], status: int, h: Dict[str, str], body: str) -> bool:
112
+ if fp["status"] and status not in fp["status"]:
113
+ return False
114
+ if fp["header"]:
115
+ name, pat = fp["header"]
116
+ v = h.get(name)
117
+ if v is None or not pat.search(v):
118
+ return False
119
+ if fp["body"]:
120
+ for rx in fp["body"]:
121
+ if not rx.search(body):
122
+ return False
123
+ return bool(fp["header"] or fp["body"])
124
+
125
+
126
+ def find_fingerprint(lst: List[Dict[str, Any]], status: int, h: Dict[str, str], body: str) -> Optional[Dict[str, Any]]:
127
+ for fp in lst:
128
+ if matches(fp, status, h, body):
129
+ return fp
130
+ return None
errdown/_headers.py ADDED
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from datetime import datetime, timezone
5
+ from email.utils import parsedate_to_datetime
6
+ from typing import Any, Dict, Optional
7
+
8
+ from ._util import js_round
9
+
10
+ HeaderMap = Dict[str, str]
11
+
12
+
13
+ def to_header_map(h: Any) -> HeaderMap:
14
+ """Accepts dict, list of pairs, or anything with .items() (httpx/requests/aiohttp headers)."""
15
+ m: HeaderMap = {}
16
+ if not h:
17
+ return m
18
+
19
+ def put(k: Any, v: Any) -> None:
20
+ if not isinstance(k, str) or v is None:
21
+ return
22
+ m[k.lower()] = ", ".join(str(x) for x in v) if isinstance(v, (list, tuple)) else str(v)
23
+
24
+ try:
25
+ if hasattr(h, "multi_items"): # httpx: keep repeated headers
26
+ seen: Dict[str, list] = {}
27
+ for k, v in h.multi_items():
28
+ seen.setdefault(k.lower(), []).append(v)
29
+ for k, vs in seen.items():
30
+ put(k, vs if len(vs) > 1 else vs[0])
31
+ elif hasattr(h, "items"):
32
+ for k, v in h.items():
33
+ put(k, v)
34
+ else:
35
+ for pair in h:
36
+ if isinstance(pair, (list, tuple)) and len(pair) >= 2:
37
+ put(pair[0], pair[1])
38
+ except Exception:
39
+ pass
40
+ return m
41
+
42
+
43
+ _MAX_RETRY = 86400
44
+ _DIGITS = re.compile(r"[0-9]+\Z")
45
+ _NUM = re.compile(r"[0-9]+(\.[0-9]+)?\Z")
46
+
47
+
48
+ def _clamp(n: float) -> int:
49
+ return max(0, min(_MAX_RETRY, js_round(n)))
50
+
51
+
52
+ def _parse_date_ms(s: str) -> Optional[float]:
53
+ try:
54
+ dt = parsedate_to_datetime(s)
55
+ except Exception:
56
+ dt = None
57
+ if dt is None:
58
+ try:
59
+ dt = datetime.fromisoformat(s.replace("Z", "+00:00"))
60
+ except Exception:
61
+ return None
62
+ if dt.tzinfo is None:
63
+ dt = dt.replace(tzinfo=timezone.utc)
64
+ return dt.timestamp() * 1000
65
+
66
+
67
+ def retry_after_from_headers(h: HeaderMap, now_ms: float) -> Optional[int]:
68
+ ra = (h.get("retry-after") or "").strip()
69
+ if ra:
70
+ if _DIGITS.match(ra):
71
+ return _clamp(int(ra))
72
+ t = _parse_date_ms(ra)
73
+ if t is not None:
74
+ return _clamp((t - now_ms) / 1000)
75
+ for name in ("ratelimit-reset", "x-ratelimit-reset", "x-rate-limit-reset"):
76
+ v = (h.get(name) or "").strip()
77
+ if v and _NUM.match(v):
78
+ n = float(v)
79
+ return _clamp(n - now_ms / 1000 if n > 1e9 else n)
80
+ return None
errdown/_normalize.py ADDED
@@ -0,0 +1,476 @@
1
+ """Port of packages/js/src/normalize.ts. Must produce identical output on every fixture."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import time
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Dict, Optional, Tuple
8
+ from urllib.parse import urlsplit
9
+
10
+ from ._fingerprints import CHALLENGES, PAGES, find_fingerprint
11
+ from ._headers import HeaderMap, retry_after_from_headers, to_header_map
12
+ from ._status import classify_status, default_retry_after, guidance
13
+ from ._util import is_num, js_parse, js_str, js_trim
14
+
15
+ Problem = Dict[str, Any]
16
+
17
+ MAX_BODY = 256 * 1024
18
+ TYPE_BASE = "https://errdown.com/errors/"
19
+ CF_DOCS = "https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/"
20
+
21
+ _BODY_PAGES = [f for f in PAGES if f["body"]]
22
+ _HEADER_PAGES = [f for f in PAGES if not f["body"]]
23
+
24
+
25
+ def _body_to_str(body: Any) -> str:
26
+ try:
27
+ if body is None:
28
+ return ""
29
+ if isinstance(body, str):
30
+ return body[:MAX_BODY]
31
+ if isinstance(body, (bytes, bytearray, memoryview)):
32
+ return bytes(body[:MAX_BODY]).decode("utf-8-sig", errors="replace")
33
+ return ""
34
+ except Exception:
35
+ return ""
36
+
37
+
38
+ def _iso(dt: datetime) -> str:
39
+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z"
40
+
41
+
42
+ def _parse_now(now: Any) -> Tuple[str, float]:
43
+ """Returns (timestamp string, now in ms). A string `now` is kept verbatim, as in TS."""
44
+ try:
45
+ if isinstance(now, datetime):
46
+ d = now if now.tzinfo else now.replace(tzinfo=timezone.utc)
47
+ return _iso(d), d.timestamp() * 1000
48
+ if isinstance(now, str) and now:
49
+ d = datetime.fromisoformat(now.replace("Z", "+00:00"))
50
+ if d.tzinfo is None:
51
+ d = d.replace(tzinfo=timezone.utc)
52
+ return now, d.timestamp() * 1000
53
+ except Exception:
54
+ pass
55
+ ms = time.time() * 1000
56
+ return _iso(datetime.fromtimestamp(ms / 1000, tz=timezone.utc)), ms
57
+
58
+
59
+ def _host_of(url: Optional[str]) -> Optional[str]:
60
+ if not url:
61
+ return None
62
+ try:
63
+ u = urlsplit(url)
64
+ if not u.scheme or not u.hostname:
65
+ return None
66
+ host = u.hostname
67
+ if ":" in host:
68
+ host = f"[{host}]"
69
+ port = u.port
70
+ default = {"http": 80, "https": 443, "ws": 80, "wss": 443}.get(u.scheme.lower())
71
+ return f"{host}:{port}" if port is not None and port != default else host
72
+ except Exception:
73
+ return None
74
+
75
+
76
+ _CTRL = re.compile("[\u0000-\u001f\u007f-\u009f

]+")
77
+ _WS = re.compile(r"\s+")
78
+
79
+
80
+ def sanitize(text: str, max_len: int = 200) -> str:
81
+ """Strip control chars/newlines and truncate, for quoting untrusted text (SPEC §7)."""
82
+ clean = js_trim(_WS.sub(" ", _CTRL.sub(" ", text)))
83
+ return clean[: max_len - 1] + "…" if len(clean) > max_len else clean
84
+
85
+
86
+ def _try_json(body: str) -> Any:
87
+ t = body.lstrip()
88
+ if not t or t[0] not in "{[":
89
+ return _MISSING
90
+ try:
91
+ return js_parse(body)
92
+ except Exception:
93
+ return _MISSING
94
+
95
+
96
+ _MISSING = object()
97
+
98
+ # [category, error_name, title, owner_action_required?, retryable?]
99
+ CF_CODES: Dict[int, tuple] = {
100
+ 1000: ("dns", "dns_loop", "DNS points to prohibited IP", True, False),
101
+ 1001: ("dns", "dns_resolution_error", "DNS resolution error", True),
102
+ 1003: ("config", "direct_ip_access_not_allowed", "Direct IP access not allowed"),
103
+ 1006: ("access_denied", "access_denied_ip_banned", "Access denied"),
104
+ 1007: ("access_denied", "access_denied_ip_banned", "Access denied"),
105
+ 1008: ("access_denied", "access_denied_ip_banned", "Access denied"),
106
+ 1009: ("access_denied", "access_denied_country", "Access denied (country or region banned)"),
107
+ 1010: ("access_denied", "access_denied_browser_signature", "Access denied (browser signature)"),
108
+ 1012: ("access_denied", "access_denied", "Access denied"),
109
+ 1014: ("config", "cname_cross_user_banned", "CNAME cross-user banned", True),
110
+ 1015: ("rate_limit", "rate_limited", "You are being rate limited"),
111
+ 1016: ("dns", "origin_dns_error", "Origin DNS error", True, False),
112
+ 1020: ("access_denied", "access_denied", "Access denied (firewall rule)"),
113
+ 1034: ("config", "edge_ip_restricted", "Edge IP restricted"),
114
+ 520: ("upstream_unavailable", "origin_unknown_error", "Web server returned an unknown error", False, True),
115
+ 521: ("upstream_unavailable", "origin_down", "Web server is down", False, True),
116
+ 522: ("upstream_unavailable", "origin_connection_timed_out", "Connection timed out", False, True),
117
+ 523: ("upstream_unavailable", "origin_unreachable", "Origin is unreachable", False, True),
118
+ 524: ("upstream_unavailable", "origin_timeout", "A timeout occurred", False, True),
119
+ 525: ("tls", "ssl_handshake_failed", "SSL handshake failed", True, False),
120
+ 526: ("tls", "invalid_ssl_certificate", "Invalid SSL certificate", True, False),
121
+ 1101: ("worker", "worker_threw_exception", "Worker threw exception", True, False),
122
+ 1102: ("worker", "worker_exceeded_resource_limits", "Worker exceeded resource limits", True),
123
+ }
124
+
125
+ # ---------- Cloudflare Markdown ----------
126
+
127
+ _FM = re.compile(r"^?---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)\Z")
128
+ _KV = re.compile(r"^([A-Za-z_][A-Za-z0-9_-]*):\s?(.*)\Z", re.S)
129
+ _NUMERIC = re.compile(r"-?[0-9]+(\.[0-9]+)?\Z")
130
+ _TITLE = re.compile(r"^#\s+(.+)$", re.M)
131
+ _FOOTER = re.compile(r"\n---[ \t]*\r?\n([\s\S]*?)\s*\Z")
132
+
133
+
134
+ def _parse_scalar(v: str) -> Any:
135
+ s = js_trim(v)
136
+ if s == "true":
137
+ return True
138
+ if s == "false":
139
+ return False
140
+ if s in ("null", "~", ""):
141
+ return _MISSING
142
+ if _NUMERIC.match(s):
143
+ return float(s) if "." in s else int(s)
144
+ if len(s) >= 2 and ((s[0] == '"' and s[-1] == '"') or (s[0] == "'" and s[-1] == "'")):
145
+ return s[1:-1]
146
+ if s in ('"', "'"):
147
+ return s
148
+ return s
149
+
150
+
151
+ def _section(rest: str, name: str) -> Optional[str]:
152
+ rx = re.compile(r"^##\s+" + name + r"\s*$([\s\S]*?)(?=^##\s|^---\s*$|\Z)", re.M | re.I)
153
+ m = rx.search(rest)
154
+ return js_trim(m.group(1)) if m else None
155
+
156
+
157
+ def _parse_cf_markdown(body: str) -> Optional[Dict[str, Any]]:
158
+ m = _FM.match(body)
159
+ if not m:
160
+ return None
161
+ fm: Dict[str, Any] = {}
162
+ for line in re.split(r"\r?\n", m.group(1)):
163
+ kv = _KV.match(line)
164
+ if kv:
165
+ v = _parse_scalar(kv.group(2))
166
+ if v is not _MISSING:
167
+ fm[kv.group(1)] = v
168
+ if "error_code" not in fm:
169
+ return None
170
+ rest = m.group(2)
171
+ t = _TITLE.search(rest)
172
+ title = js_trim(t.group(1)) if t else None
173
+ if title:
174
+ fm["title"] = title
175
+ detail = _section(rest, "What Happened")
176
+ if detail:
177
+ fm["detail"] = detail
178
+ todo = _section(rest, "What You Should Do")
179
+ if todo:
180
+ fm["what_you_should_do"] = todo
181
+ f = _FOOTER.search(rest)
182
+ footer = js_trim(f.group(1)) if f else None
183
+ if footer:
184
+ fm["footer"] = footer
185
+ return fm
186
+
187
+
188
+ # ---------- Assembly ----------
189
+
190
+ class _Ctx:
191
+ __slots__ = ("status", "h", "url", "timestamp", "now_ms")
192
+
193
+ def __init__(self, status: int, h: HeaderMap, url: Optional[str], timestamp: str, now_ms: float):
194
+ self.status, self.h, self.url, self.timestamp, self.now_ms = status, h, url, timestamp, now_ms
195
+
196
+
197
+ def _nn(v: Any, d: Any) -> Any:
198
+ """JS `v ?? d`."""
199
+ return d if v is None else v
200
+
201
+
202
+ def _finish(p: Dict[str, Any], ctx: _Ctx) -> Problem:
203
+ status = p["status"]
204
+ base = classify_status(status)
205
+ category = _nn(p.get("error_category"), base["category"])
206
+ retryable = _nn(p.get("retryable"), base["retryable"])
207
+ owner = _nn(p.get("owner_action_required"), base["owner_action_required"])
208
+ retry_after = p.get("retry_after")
209
+ if retry_after is None and retryable:
210
+ retry_after = _nn(retry_after_from_headers(ctx.h, ctx.now_ms), default_retry_after(status))
211
+ error_name = _nn(p.get("error_name"), base["error_name"])
212
+
213
+ out: Dict[str, Any] = {
214
+ "type": _nn(p.get("type"), TYPE_BASE + js_str(error_name)),
215
+ "title": _nn(p.get("title"), base["title"]),
216
+ "status": status,
217
+ "detail": _nn(p.get("detail"), f"The server returned HTTP {status}."),
218
+ "instance": _nn(p.get("instance"), ctx.url),
219
+ "error_code": _nn(p.get("error_code"), status),
220
+ "error_name": error_name,
221
+ "error_category": category,
222
+ "retryable": retryable,
223
+ "retry_after": retry_after,
224
+ "owner_action_required": owner,
225
+ "what_you_should_do": _nn(p.get("what_you_should_do"), guidance(category, bool(retryable), bool(owner), retry_after)),
226
+ "timestamp": _nn(p.get("timestamp"), ctx.timestamp),
227
+ "zone": _nn(p.get("zone"), _host_of(ctx.url)),
228
+ "footer": p.get("footer"),
229
+ "ray_id": p.get("ray_id"),
230
+ "cloudflare_error": p.get("cloudflare_error"),
231
+ "errdown_synthesized": _nn(p.get("errdown_synthesized"), True),
232
+ "errdown_source": _nn(p.get("errdown_source"), "unknown"),
233
+ "errdown_confidence": _nn(p.get("errdown_confidence"), 0.5),
234
+ }
235
+ for k, v in p.items():
236
+ if k not in out:
237
+ out[k] = v
238
+ # TS deletes `undefined` core members; extension members are kept as-is (ordered() drops nulls).
239
+ return {k: v for k, v in out.items() if not (k in _CORE and v is None)}
240
+
241
+
242
+ _CORE = {"type", "title", "status", "detail", "instance", "error_code", "error_name", "error_category",
243
+ "retryable", "retry_after", "owner_action_required", "what_you_should_do", "timestamp", "zone",
244
+ "footer", "ray_id", "cloudflare_error", "errdown_synthesized", "errdown_source", "errdown_confidence"}
245
+
246
+ _RAY_HDR = re.compile(r"[0-9a-f]{8,32}\Z", re.I)
247
+ _RAY_BODY = re.compile(r"Ray ID:?\s*(?:<[^>]{0,80}>\s*)?([0-9a-f]{16})", re.I)
248
+
249
+
250
+ def _ray_id(ctx: _Ctx, body: str = "") -> Optional[str]:
251
+ hdr = ctx.h.get("cf-ray")
252
+ if hdr is not None:
253
+ first = js_trim(hdr).split("-")[0]
254
+ if first and _RAY_HDR.match(first):
255
+ return first.lower()
256
+ m = _RAY_BODY.search(body)
257
+ return m.group(1) if m else None
258
+
259
+
260
+ def _cf_meta(ctx: _Ctx, body: str = "") -> Dict[str, Any]:
261
+ ray = _ray_id(ctx, body)
262
+ meta: Dict[str, Any] = {"errdown_source": "cloudflare", "cloudflare_error": True}
263
+ if ray:
264
+ meta["ray_id"] = ray
265
+ return meta
266
+
267
+
268
+ def _from_fp(fp: Dict[str, Any], ctx: _Ctx, challenge: bool, body: str = "") -> Problem:
269
+ base = classify_status(ctx.status)
270
+ category = "challenge" if challenge else _nn(fp.get("category"), base["category"])
271
+ label = "" if fp["source"] == "unknown" else fp["source"].replace("-", "_") + "_"
272
+ error_name = _nn(fp.get("error_name"), label + base["error_name"])
273
+ if challenge:
274
+ what = "a bot-verification challenge page"
275
+ elif fp["source"] == "unknown":
276
+ what = "a block page"
277
+ else:
278
+ what = f"an error page from {fp['source']}"
279
+ p: Dict[str, Any] = {
280
+ "status": ctx.status,
281
+ "title": _nn(fp.get("title"), base["title"]),
282
+ "detail": _nn(fp.get("detail"), f"The server returned HTTP {ctx.status} with {what}."),
283
+ "error_name": error_name,
284
+ "error_category": category,
285
+ "retryable": False if challenge else _nn(fp.get("retryable"), base["retryable"]),
286
+ "owner_action_required": _nn(fp.get("owner_action_required"), base["owner_action_required"]),
287
+ "errdown_source": fp["source"],
288
+ "errdown_confidence": fp["confidence"],
289
+ }
290
+ if fp["source"] == "cloudflare":
291
+ p.update(_cf_meta(ctx, body))
292
+ return _finish(p, ctx)
293
+
294
+
295
+ def _str(v: Any) -> Optional[str]:
296
+ if isinstance(v, str) and js_trim(v):
297
+ return v
298
+ if is_num(v):
299
+ return js_str(v)
300
+ return None
301
+
302
+
303
+ def _first(*vals: Optional[str]) -> Optional[str]:
304
+ for v in vals:
305
+ if v is not None:
306
+ return v
307
+ return None
308
+
309
+
310
+ def _message_from_json(j: Any) -> Optional[Dict[str, Optional[str]]]:
311
+ if not isinstance(j, dict):
312
+ return None
313
+ j = {str(k).lower(): v for k, v in j.items()}
314
+ errors = j.get("errors")
315
+ if isinstance(errors, list) and errors:
316
+ e = errors[0]
317
+ if isinstance(e, dict):
318
+ ext = e.get("extensions") if isinstance(e.get("extensions"), dict) else {}
319
+ return {"message": _str(e.get("message")), "code": _first(_str(ext.get("code")), _str(e.get("code")))}
320
+ if isinstance(e, str):
321
+ return {"message": e, "code": None}
322
+ if isinstance(errors, str):
323
+ return {"message": errors, "code": None}
324
+ detail = j.get("detail")
325
+ if isinstance(detail, list) and detail and isinstance(detail[0], dict):
326
+ d0 = detail[0]
327
+ return {"message": _first(_str(d0.get("msg")), _str(d0.get("message"))), "code": _str(d0.get("type"))}
328
+ err = j.get("error")
329
+ if isinstance(err, str) and isinstance(j.get("error_description"), str):
330
+ return {"message": j["error_description"], "code": err}
331
+ if isinstance(err, dict):
332
+ return {"message": _first(_str(err.get("message")), _str(err.get("detail"))),
333
+ "code": _first(_str(err.get("code")), _str(err.get("type")))}
334
+ if isinstance(err, str):
335
+ return {"message": _first(_str(j.get("message")), err), "code": _str(j.get("code"))}
336
+ if _str(j.get("message")) or _str(detail):
337
+ return {"message": _first(_str(j.get("message")), _str(detail)), "code": _str(j.get("code"))}
338
+ return None
339
+
340
+
341
+ _XML_HEAD = re.compile(r"^\s*(<\?xml[^>]{0,200}\?>\s*)?<(Error|ErrorResponse)[\s>]")
342
+
343
+
344
+ def _message_from_xml(body: str) -> Optional[Dict[str, Optional[str]]]:
345
+ if not _XML_HEAD.search(body):
346
+ return None
347
+
348
+ def tag(t: str) -> Optional[str]:
349
+ m = re.search("<" + t + ">([^<]{1,500})</" + t + ">", body)
350
+ return js_trim(m.group(1)) if m else None
351
+
352
+ code, message = tag("Code"), tag("Message")
353
+ return {"code": code, "message": message} if (code or message) else None
354
+
355
+
356
+ _XML_SOURCES = [
357
+ ("server", re.compile(r"^AmazonS3\Z", re.I), "aws-s3"),
358
+ ("server", re.compile(r"^UploadServer\Z", re.I), "google-cloud-storage"),
359
+ ("x-amzn-requestid", re.compile(r"."), "aws"),
360
+ ("x-ms-request-id", re.compile(r"."), "azure"),
361
+ ]
362
+ _PLAIN_CF = re.compile(r"^\s*error code: (1[0-9]{3}|5[0-9]{2})\s*\Z")
363
+
364
+
365
+ def normalize(status: int, headers: Any = None, body: Any = None, *, url: Optional[str] = None,
366
+ now: Any = None) -> Optional[Problem]:
367
+ """Convert an HTTP response into a Cloudflare-compatible Problem, or None if not an error.
368
+
369
+ Never raises. `body` may be str or bytes; `headers` a dict, list of pairs, or any object
370
+ with .items() (httpx, requests, aiohttp). `now` (datetime or ISO string) pins the timestamp.
371
+ """
372
+ try:
373
+ timestamp, now_ms = _parse_now(now)
374
+ st = status if isinstance(status, int) and not isinstance(status, bool) else 0
375
+ ctx = _Ctx(st, to_header_map(headers), url, timestamp, now_ms)
376
+ except Exception:
377
+ return None
378
+ try:
379
+ return _run(ctx, _body_to_str(body))
380
+ except Exception:
381
+ if ctx.status < 400:
382
+ return None
383
+ try:
384
+ return _finish({"status": ctx.status, "errdown_confidence": 0.3}, ctx)
385
+ except Exception:
386
+ return None
387
+
388
+
389
+ def scan_window(body: str) -> str:
390
+ """Fingerprints only look at the head and tail of large bodies (SPEC §5)."""
391
+ return body[:32768] + "\n" + body[-8192:] if len(body) > 40960 else body
392
+
393
+
394
+ def _run(ctx: _Ctx, full_body: str) -> Optional[Problem]:
395
+ status, h = ctx.status, ctx.h
396
+ body = scan_window(full_body)
397
+ is_error = 400 <= status <= 999
398
+
399
+ challenge = find_fingerprint(CHALLENGES, status, h, body)
400
+ if challenge and (is_error or challenge.get("category") != "access_denied"):
401
+ return _from_fp(challenge, ctx, challenge.get("category") != "access_denied", body)
402
+ if not is_error:
403
+ return None
404
+
405
+ ctype = h.get("content-type", "")
406
+ j = _try_json(full_body)
407
+
408
+ # 1. Structured pass-through.
409
+ if isinstance(j, dict) and ("problem+json" in ctype or ("type" in j and "status" in j) or "error_code" in j):
410
+ cf = is_num(j.get("error_code")) and ("ray_id" in j or "cf-error-type" in h)
411
+ p: Dict[str, Any] = {"errdown_synthesized": False, "errdown_source": "cloudflare" if cf else "origin",
412
+ "errdown_confidence": 1}
413
+ if cf:
414
+ p["cloudflare_error"] = True
415
+ p.update(j)
416
+ p["status"] = j["status"] if is_num(j.get("status")) else status
417
+ return _finish(p, ctx)
418
+ md = _parse_cf_markdown(full_body) if ("markdown" in ctype or body.lstrip().startswith("---")) else None
419
+ if md:
420
+ cf = "ray_id" in md or "cf-error-type" in h
421
+ p = {"errdown_synthesized": False, "errdown_source": "cloudflare" if cf else "origin", "errdown_confidence": 1}
422
+ if cf:
423
+ p["cloudflare_error"] = True
424
+ p.update(md)
425
+ p["status"] = md["status"] if is_num(md.get("status")) else status
426
+ return _finish(p, ctx)
427
+
428
+ if "cf-error-type" in h:
429
+ p = {"status": status, **_cf_meta(ctx), "errdown_confidence": 0.85,
430
+ "detail": f"Cloudflare returned HTTP {status} ({sanitize(h.get('cf-error-type') or '', 40)})."}
431
+ return _finish(p, ctx)
432
+
433
+ plain = _PLAIN_CF.match(body)
434
+ if plain and re.search("cloudflare", h.get("server", ""), re.I):
435
+ code = int(plain.group(1))
436
+ known = CF_CODES.get(code)
437
+ p = {"status": status, **_cf_meta(ctx), "type": CF_DOCS, "error_code": code,
438
+ "error_name": known[1] if known else f"cloudflare_{code}"}
439
+ if known:
440
+ p["error_category"] = known[0]
441
+ p["title"] = f"Error {code}: {known[2]}"
442
+ else:
443
+ p["title"] = f"Cloudflare error {code}"
444
+ if known and len(known) > 3:
445
+ p["owner_action_required"] = known[3]
446
+ if known and len(known) > 4:
447
+ p["retryable"] = known[4]
448
+ if code < 1000 and not known:
449
+ p["error_category"] = classify_status(code)["category"]
450
+ p["detail"] = f"Cloudflare returned error {code}{f' ({known[2]})' if known else ''} with HTTP {status}."
451
+ p["errdown_confidence"] = 0.9 if known else 0.75
452
+ return _finish(p, ctx)
453
+
454
+ fp = find_fingerprint(_BODY_PAGES, status, h, body)
455
+ if fp:
456
+ return _from_fp(fp, ctx, False, body)
457
+ hfp = find_fingerprint(_HEADER_PAGES, status, h, body)
458
+
459
+ m = _message_from_json(j) if j is not _MISSING else _message_from_xml(full_body)
460
+ xml_source = None
461
+ if j is _MISSING:
462
+ for name, rx, src in _XML_SOURCES:
463
+ if rx.search(h.get(name, "")):
464
+ xml_source = src
465
+ break
466
+ if m and (m.get("message") or m.get("code")):
467
+ said = (f" The server's message (untrusted, quoted): \"{sanitize(m['message']).replace(chr(34), chr(39))}\""
468
+ if m.get("message") else "")
469
+ code_s = f" (code: {sanitize(m['code'], 60)})" if m.get("code") else ""
470
+ return _finish({"status": status, "detail": f"The server returned HTTP {status}{code_s}.{said}",
471
+ "errdown_source": xml_source or (hfp["source"] if hfp else "origin"),
472
+ "errdown_confidence": 0.7}, ctx)
473
+ if hfp:
474
+ return _from_fp(hfp, ctx, False, body)
475
+
476
+ return _finish({"status": status, "errdown_confidence": 0.3 if status >= 600 else 0.5}, ctx)
errdown/_render.py ADDED
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ from typing import Any, Dict
6
+
7
+ from ._util import is_num, js_str, js_stringify
8
+
9
+ _ORDER = [
10
+ "type", "title", "status", "detail", "instance", "error_code", "error_name", "error_category",
11
+ "ray_id", "timestamp", "zone", "cloudflare_error", "retryable", "retry_after", "owner_action_required",
12
+ "what_you_should_do", "footer", "errdown_synthesized", "errdown_source", "errdown_confidence",
13
+ ]
14
+ _FM_KEYS = [
15
+ "error_code", "error_name", "error_category", "status", "ray_id", "timestamp", "zone",
16
+ "cloudflare_error", "retryable", "retry_after", "owner_action_required",
17
+ "errdown_synthesized", "errdown_source", "errdown_confidence",
18
+ ]
19
+
20
+
21
+ def ordered(p: Dict[str, Any]) -> Dict[str, Any]:
22
+ """Ordered copy (Cloudflare's member order) with None members removed."""
23
+ out = {k: p[k] for k in _ORDER if p.get(k) is not None}
24
+ for k, v in p.items():
25
+ if k not in out and v is not None:
26
+ out[k] = v
27
+ return out
28
+
29
+
30
+ def to_json(p: Dict[str, Any], indent: Any = None) -> str:
31
+ return js_stringify(ordered(p), indent)
32
+
33
+
34
+ _SAFE = re.compile(r"[A-Za-z0-9_.:/+@-][A-Za-z0-9_ .:/+@-]*\Z")
35
+ _RESERVED = re.compile(r"(true|false|null|~|-?[0-9]+(\.[0-9]+)?)\Z")
36
+
37
+
38
+ def _yaml_scalar(v: Any) -> str:
39
+ if is_num(v) or isinstance(v, bool):
40
+ return js_str(v)
41
+ s = re.sub(r"[\r\n]+", " ", js_str(v))
42
+ if _SAFE.match(s) and not _RESERVED.match(s) and not re.search(r":\s", s):
43
+ return s
44
+ return json.dumps(s, ensure_ascii=False)
45
+
46
+
47
+ def to_markdown(p: Dict[str, Any]) -> str:
48
+ fm = [f"{k}: {_yaml_scalar(p[k])}" for k in _FM_KEYS if p.get(k) is not None]
49
+ md = (f"---\n" + "\n".join(fm) + f"\n---\n\n# {js_str(p.get('title'))}\n\n## What Happened\n\n"
50
+ f"{js_str(p.get('detail'))}\n\n## What You Should Do\n\n{js_str(p.get('what_you_should_do'))}\n")
51
+ if p.get("footer"):
52
+ md += f"\n---\n\n{js_str(p['footer'])}\n"
53
+ return md
errdown/_status.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+
6
+ def _c(category: str, error_name: str, title: str, retryable: bool = False, owner: bool = False) -> Dict[str, Any]:
7
+ return {"category": category, "error_name": error_name, "title": title,
8
+ "retryable": retryable, "owner_action_required": owner}
9
+
10
+
11
+ _TABLE: Dict[int, Dict[str, Any]] = {
12
+ 400: _c("bad_request", "bad_request", "Bad request"),
13
+ 401: _c("auth_required", "auth_required", "Authentication required"),
14
+ 403: _c("access_denied", "forbidden", "Access denied"),
15
+ 404: _c("not_found", "not_found", "Not found"),
16
+ 405: _c("bad_request", "method_not_allowed", "Method not allowed"),
17
+ 406: _c("bad_request", "not_acceptable", "Not acceptable"),
18
+ 407: _c("auth_required", "proxy_auth_required", "Proxy authentication required"),
19
+ 408: _c("upstream_unavailable", "request_timeout", "Request timeout", True),
20
+ 409: _c("bad_request", "conflict", "Conflict"),
21
+ 410: _c("not_found", "gone", "Gone"),
22
+ 411: _c("bad_request", "length_required", "Length required"),
23
+ 412: _c("bad_request", "precondition_failed", "Precondition failed"),
24
+ 413: _c("bad_request", "payload_too_large", "Payload too large"),
25
+ 414: _c("bad_request", "uri_too_long", "URI too long"),
26
+ 415: _c("bad_request", "unsupported_media_type", "Unsupported media type"),
27
+ 422: _c("bad_request", "unprocessable_content", "Unprocessable content"),
28
+ 429: _c("rate_limit", "rate_limited", "Rate limited", True),
29
+ 431: _c("bad_request", "request_header_fields_too_large", "Request header fields too large"),
30
+ 451: _c("legal", "unavailable_for_legal_reasons", "Unavailable for legal reasons"),
31
+ 500: _c("server_error", "internal_server_error", "Internal server error", True),
32
+ 501: _c("unsupported", "not_implemented", "Not implemented"),
33
+ 502: _c("upstream_unavailable", "bad_gateway", "Bad gateway", True),
34
+ 503: _c("upstream_unavailable", "service_unavailable", "Service unavailable", True),
35
+ 504: _c("upstream_unavailable", "gateway_timeout", "Gateway timeout", True),
36
+ }
37
+
38
+
39
+ def classify_status(status: int) -> Dict[str, Any]:
40
+ hit = _TABLE.get(status)
41
+ if hit:
42
+ return dict(hit)
43
+ if status >= 600:
44
+ return _c("bad_request", "nonstandard_status", "Nonstandard error status")
45
+ if status >= 500:
46
+ return _c("server_error", "server_error", "Server error", True)
47
+ return _c("bad_request", "client_error", "Client error")
48
+
49
+
50
+ def default_retry_after(status: int) -> int:
51
+ return 60 if status == 429 else 5
52
+
53
+
54
+ def guidance(category: str, retryable: bool, owner: bool, retry_after: Optional[Any]) -> str:
55
+ if category == "challenge":
56
+ return ("Stop. This site requires a human to complete a check (CAPTCHA or bot verification). "
57
+ "Do not retry automatically and do not attempt to bypass it. Ask the user to open the page in a browser.")
58
+ if owner:
59
+ return "This needs the site owner to fix. Do not retry. Report the error to the user or the site operator."
60
+ if retryable:
61
+ n = retry_after if retry_after is not None else 5
62
+ from ._util import js_str
63
+ return (f"Wait {js_str(n)} seconds, then retry with exponential backoff. "
64
+ "Stop after a few attempts and report the error if it persists.")
65
+ return {
66
+ "access_denied": "Do not retry. Access was intentionally blocked. Tell the user; they may need to request access from the site owner.",
67
+ "legal": "Do not retry. This content is unavailable in this location for legal reasons.",
68
+ "auth_required": "Do not retry without credentials. Ask the user to authenticate or provide credentials.",
69
+ "not_found": "Do not retry. Check the URL for mistakes, or search for the resource elsewhere.",
70
+ "bad_request": "Do not retry the same request. Check the URL, method, headers and body, then fix the request.",
71
+ "unsupported": "Do not retry. The server does not support this request.",
72
+ }.get(category, "Do not retry the same request. Report the error to the user.")
errdown/_util.py ADDED
@@ -0,0 +1,64 @@
1
+ """Helpers that reproduce JavaScript semantics so output matches the TypeScript reference exactly."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import math
6
+ from typing import Any
7
+
8
+
9
+ def is_num(v: Any) -> bool:
10
+ """JS `typeof v === "number"` (bool is not a number)."""
11
+ return isinstance(v, (int, float)) and not isinstance(v, bool)
12
+
13
+
14
+ def js_num(v: Any) -> Any:
15
+ """Integral floats become ints (JS has one number type: 1.0 prints as 1)."""
16
+ if isinstance(v, float) and v.is_integer() and math.isfinite(v):
17
+ return int(v)
18
+ return v
19
+
20
+
21
+ def js_str(v: Any) -> str:
22
+ """JS String(v) for numbers, booleans and strings."""
23
+ if isinstance(v, bool):
24
+ return "true" if v else "false"
25
+ if isinstance(v, float):
26
+ if v.is_integer() and math.isfinite(v):
27
+ return str(int(v))
28
+ r = repr(v)
29
+ return r
30
+ return str(v)
31
+
32
+
33
+ def js_round(x: float) -> int:
34
+ """JS Math.round: halves round toward +infinity."""
35
+ return int(math.floor(x + 0.5))
36
+
37
+
38
+ def _plain(v: Any) -> Any:
39
+ if isinstance(v, dict):
40
+ return {k: _plain(x) for k, x in v.items()}
41
+ if isinstance(v, list):
42
+ return [_plain(x) for x in v]
43
+ return js_num(v)
44
+
45
+
46
+ def js_stringify(v: Any, indent: Any = None) -> str:
47
+ """JSON.stringify: compact separators, no ASCII escaping, integral floats as ints."""
48
+ if indent:
49
+ return json.dumps(_plain(v), ensure_ascii=False, indent=indent)
50
+ return json.dumps(_plain(v), ensure_ascii=False, separators=(",", ":"))
51
+
52
+
53
+ def _reject_constant(name: str) -> Any:
54
+ raise ValueError(name)
55
+
56
+
57
+ def js_parse(s: str) -> Any:
58
+ """JSON.parse: rejects NaN/Infinity, which Python's json accepts."""
59
+ return json.loads(s, parse_constant=_reject_constant)
60
+
61
+
62
+ def js_trim(s: str) -> str:
63
+ # JS trim() strips whitespace + line terminators incl. U+FEFF; Python strip() lacks U+FEFF.
64
+ return s.strip().strip("").strip()
errdown/py.typed ADDED
File without changes
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.5
2
+ Name: errdown
3
+ Version: 0.1.0a0
4
+ Summary: Cloudflare-compatible structured errors (RFC 9457) for every HTTP error your agent hits.
5
+ Project-URL: Homepage, https://errdown.com
6
+ Project-URL: Repository, https://github.com/ArtZab0/errdown
7
+ Author: Artem Zabarov
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ License-File: NOTICE
11
+ Keywords: ai-agents,cloudflare,errors,http,llm,mcp,problem-details,rfc9457
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+
18
+ # errdown
19
+
20
+ > **Pre-release (alpha).** API and output may change.
21
+
22
+ Cloudflare-compatible structured errors (RFC 9457 Problem Details) for every HTTP error your
23
+ agent hits: nginx, AWS, Vercel, framework defaults, JSON/XML API errors, bot challenges.
24
+ Zero dependencies, pure function, never throws. Independent project, not affiliated with Cloudflare.
25
+
26
+ ```python
27
+ import httpx
28
+ from errdown import normalize, to_markdown, decide, agent_accept_header
29
+
30
+ res = httpx.get(url, headers={"accept": agent_accept_header()})
31
+ if res.is_error:
32
+ problem = normalize(res.status_code, res.headers, res.content, url=url)
33
+ if problem:
34
+ to_markdown(problem) # Cloudflare-format Markdown for the model
35
+ decide(problem) # {"action": "retry", "after_seconds": 5} | escalate | fail
36
+ ```
37
+
38
+ Spec and conformance fixtures: https://github.com/ArtZab0/errdown
39
+
40
+ License: Apache-2.0. Spec and fixtures: CC0 (captured third-party responses excepted).
@@ -0,0 +1,14 @@
1
+ errdown/__init__.py,sha256=etZd_UyhaGoDNjs68e8yz8DfahLI3kFwxtbOhBMNpQg,467
2
+ errdown/_decide.py,sha256=NVtxg-V7nOiDk_h-QZw4_8nNGpC7NmT7uZOBJyfGs9I,1512
3
+ errdown/_fingerprints.py,sha256=1bjf9ljg7qus5qA26_CkFW_ft8-MpBQq7WqDiX2hXZo,8485
4
+ errdown/_headers.py,sha256=VVXB_VzW_syctLSNakNCkzZih_sw5BmNTZ2_5GfYG68,2353
5
+ errdown/_normalize.py,sha256=9w5O3iUoHPAk3oLDWrjM42izQaMXN3WLFbgtg7pqLAE,19311
6
+ errdown/_render.py,sha256=j3Zvuntuti1r6TfrO2FZXDUFJNAAX-8ckWS3rcQ4q5w,1952
7
+ errdown/_status.py,sha256=i3ojcm_runtzEjslWp3IDmd-ubvLtugHD4fqOK2BNEg,4077
8
+ errdown/_util.py,sha256=wTuzAWuLGrAX48a7rPgo8DdI_aG4DTGsLHxKGX5YtL0,1903
9
+ errdown/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ errdown-0.1.0a0.dist-info/METADATA,sha256=RGLfBemC5nOe1FgvRw3OJ3wZB3kBbbe9OVfWDZObu3U,1551
11
+ errdown-0.1.0a0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ errdown-0.1.0a0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ errdown-0.1.0a0.dist-info/licenses/NOTICE,sha256=_DDDFjHvuxj1Z9rYTR3wCAoDlWx-Xg1EFKPjBSBMqxY,274
14
+ errdown-0.1.0a0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ errdown
2
+ Copyright 2026 Artem Zabarov
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ errdown is an independent project and is not affiliated with or endorsed by Cloudflare, Inc.
7
+ It follows Cloudflare's published structured error format for interoperability.