vercel-headers-bundle 0.7.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vercel, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: vercel-headers-bundle
3
+ Version: 0.7.1
4
+ Summary: Request header helpers for Vercel Python applications
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+
10
+ # vercel-headers-bundle
11
+
12
+ This is a version of `vercel-headers` with third-party dependencies bundled. For normal use, install the unbundled `vercel-headers` package instead: https://pypi.org/project/vercel-headers/
13
+
14
+ # Headers
15
+
16
+ `vercel.headers` stores request headers for Vercel Function helpers and exposes
17
+ IP address and geolocation helpers.
18
+
19
+ Register request headers once per request:
20
+
21
+ ```python
22
+ from vercel.headers import set_headers
23
+
24
+ set_headers(request.headers)
25
+ ```
26
+
27
+ OIDC and cache helpers read the same registered header context.
@@ -0,0 +1,18 @@
1
+ # vercel-headers-bundle
2
+
3
+ This is a version of `vercel-headers` with third-party dependencies bundled. For normal use, install the unbundled `vercel-headers` package instead: https://pypi.org/project/vercel-headers/
4
+
5
+ # Headers
6
+
7
+ `vercel.headers` stores request headers for Vercel Function helpers and exposes
8
+ IP address and geolocation helpers.
9
+
10
+ Register request headers once per request:
11
+
12
+ ```python
13
+ from vercel.headers import set_headers
14
+
15
+ set_headers(request.headers)
16
+ ```
17
+
18
+ OIDC and cache helpers read the same registered header context.
@@ -0,0 +1,116 @@
1
+ """Hatch metadata hook for publish-time workspace dependency bounds."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
10
+ from packaging.requirements import Requirement
11
+
12
+ try:
13
+ import tomllib
14
+ except ModuleNotFoundError: # pragma: no cover - Python < 3.11
15
+ import tomli as tomllib # type: ignore[no-redef]
16
+
17
+
18
+ class WorkspaceDependenciesMetadataHook(MetadataHookInterface):
19
+ """Generate package dependencies from the repo-owned dependency table."""
20
+
21
+ def update(self, metadata: dict[str, Any]) -> None:
22
+ """Populate dynamic dependencies for Hatchling metadata generation."""
23
+ pyproject = _load_pyproject(Path(self.root))
24
+ release = pyproject.get("tool", {}).get("vercel", {}).get("release", {})
25
+ dependency_table = release.get("dependencies", {})
26
+ workspace_sources = pyproject.get("tool", {}).get("uv", {}).get("sources", {})
27
+ workspace_names = {
28
+ name for name, source in workspace_sources.items() if source.get("workspace") is True
29
+ }
30
+ workspace_root = _find_workspace_root(Path(self.root))
31
+
32
+ metadata["dependencies"] = [
33
+ _rewrite_dependency(requirement, workspace_names, workspace_root)
34
+ for requirement in dependency_table.get("dependencies", [])
35
+ ]
36
+
37
+
38
+ def _load_pyproject(path: Path) -> dict[str, Any]:
39
+ with (path / "pyproject.toml").open("rb") as fp:
40
+ return tomllib.load(fp)
41
+
42
+
43
+ def _find_workspace_root(start: Path) -> Path | None:
44
+ for path in [start, *start.parents]:
45
+ pyproject = path / "pyproject.toml"
46
+ if not pyproject.exists():
47
+ continue
48
+ data = _load_pyproject(path)
49
+ if "workspace" in data.get("tool", {}).get("uv", {}):
50
+ return path
51
+ return None
52
+
53
+
54
+ def _rewrite_dependency(
55
+ requirement: str,
56
+ workspace_names: set[str],
57
+ workspace_root: Path | None,
58
+ ) -> str:
59
+ parsed = Requirement(requirement)
60
+ normalized = parsed.name.lower().replace("_", "-")
61
+ if normalized not in workspace_names or workspace_root is None:
62
+ return requirement
63
+ return _with_lower_bound(parsed, _read_workspace_version(workspace_root, normalized))
64
+
65
+
66
+ def _with_lower_bound(requirement: Requirement, version: str) -> str:
67
+ extras = f"[{','.join(sorted(requirement.extras))}]" if requirement.extras else ""
68
+ specifiers = [
69
+ str(specifier) for specifier in requirement.specifier if specifier.operator != ">="
70
+ ]
71
+ specifier_text = ",".join([f">={version}", *specifiers])
72
+ marker = f" ; {requirement.marker}" if requirement.marker else ""
73
+ return f"{requirement.name}{extras}{specifier_text}{marker}"
74
+
75
+
76
+ def _read_workspace_version(workspace_root: Path, package_name: str) -> str:
77
+ for pattern in ("src/*/pyproject.toml", "integrations/*/pyproject.toml"):
78
+ for pyproject_path in workspace_root.glob(pattern):
79
+ version = _version_from_pyproject(pyproject_path, package_name)
80
+ if version is not None:
81
+ return version
82
+ raise RuntimeError(f"unknown workspace dependency {package_name!r}")
83
+
84
+
85
+ def _version_from_pyproject(pyproject_path: Path, package_name: str) -> str | None:
86
+ data = _load_pyproject(pyproject_path.parent)
87
+ if data.get("project", {}).get("name") != package_name:
88
+ return None
89
+ version_path = pyproject_path.parent / data["tool"]["hatch"]["version"]["path"]
90
+ module = ast.parse(version_path.read_text(encoding="utf-8"), filename=str(version_path))
91
+ for node in module.body:
92
+ value = _version_value(node)
93
+ if value is None:
94
+ continue
95
+ if isinstance(value, ast.Constant) and isinstance(value.value, str):
96
+ return value.value
97
+ raise RuntimeError(f"could not find __version__ in {version_path}")
98
+
99
+
100
+ def _version_value(node: ast.stmt) -> ast.expr | None:
101
+ if isinstance(node, ast.Assign) and any(
102
+ isinstance(target, ast.Name) and target.id == "__version__" for target in node.targets
103
+ ):
104
+ return node.value
105
+ if (
106
+ isinstance(node, ast.AnnAssign)
107
+ and isinstance(node.target, ast.Name)
108
+ and node.target.id == "__version__"
109
+ ):
110
+ return node.value
111
+ return None
112
+
113
+
114
+ def get_metadata_hook() -> type[MetadataHookInterface]:
115
+ """Return the hook class used by Hatchling's custom hook loader."""
116
+ return WorkspaceDependenciesMetadataHook
@@ -0,0 +1,29 @@
1
+ """Load the shared Vercel Hatch metadata hook."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.util import module_from_spec, spec_from_file_location
6
+ from pathlib import Path
7
+ from types import ModuleType
8
+
9
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
10
+
11
+
12
+ def get_metadata_hook() -> type[MetadataHookInterface]:
13
+ """Return the shared workspace dependency metadata hook."""
14
+ return _load_shared_hook().get_metadata_hook()
15
+
16
+
17
+ def _load_shared_hook() -> ModuleType:
18
+ root = Path(__file__).resolve().parent
19
+ candidates = [root / "../../scripts/hatch_build.py", root / "_vercel_hatch_build.py"]
20
+ for candidate in candidates:
21
+ path = candidate.resolve()
22
+ if path.exists():
23
+ spec = spec_from_file_location("_vercel_hatch_build", path)
24
+ if spec is None or spec.loader is None:
25
+ raise RuntimeError(f"could not load Hatch hook from {path}")
26
+ module = module_from_spec(spec)
27
+ spec.loader.exec_module(module)
28
+ return module
29
+ raise RuntimeError("could not find shared Vercel Hatch metadata hook")
@@ -0,0 +1,75 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27.0,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "vercel-headers-bundle"
7
+ dynamic = ["version", "dependencies"]
8
+ description = "Request header helpers for Vercel Python applications"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = [
13
+ "LICENSE",
14
+ "LICENSE.*",
15
+ "vercel/headers/_vendor/LICEN[CS]E*",
16
+ ]
17
+
18
+ [tool.hatch.metadata.hooks.custom]
19
+ path = "hatch_build.py"
20
+
21
+ [tool.vercel.release.dependencies]
22
+ dependencies = []
23
+
24
+ [tool.hatch.version]
25
+ path = "vercel/headers/version.py"
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ force-include = { "_vercel_hatch_build.py" = "/_vercel_hatch_build.py" }
29
+ include = [
30
+ "/vercel/headers/**/*.py",
31
+ "/vercel/headers/py.typed",
32
+ "/README.md",
33
+ "/pyproject.toml",
34
+ "/hatch_build.py",
35
+ "/LICENSE",
36
+ "/vercel/headers/_vendor/LICEN[CS]E*",
37
+ ]
38
+ exclude = [
39
+ "/**/__pycache__",
40
+ ]
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ dev-mode-dirs = ["."]
44
+ only-include = [
45
+ "/vercel/headers",
46
+ ]
47
+ exclude = [
48
+ "/**/__pycache__",
49
+ ]
50
+
51
+ [tool.poe]
52
+ include = "../../scripts/poe/poe.toml"
53
+ verbosity = -1
54
+
55
+ [tool.poe.tasks.typecheck]
56
+ cmd = "$MYPY"
57
+
58
+ [tool.poe.tasks.test]
59
+ cmd = "python -c \"pass\""
60
+
61
+ [tool.vendoring]
62
+ destination = "vercel/headers/_vendor/"
63
+ requirements = "vercel/headers/_vendor/vendor.txt"
64
+ namespace = "vercel.headers._vendor"
65
+ protected-files = [
66
+ "__init__.py",
67
+ "vendor.txt",
68
+ ]
69
+
70
+ [tool.vendoring.transformations]
71
+ drop = [
72
+ "*.so",
73
+ "*/tests/",
74
+ "*/__pycache__/",
75
+ ]
@@ -0,0 +1,144 @@
1
+ from __future__ import annotations
2
+
3
+ import urllib.parse
4
+ from collections.abc import Callable, Iterator, Mapping
5
+ from contextlib import contextmanager
6
+ from contextvars import ContextVar
7
+ from dataclasses import dataclass
8
+ from typing import Any, ParamSpec, Protocol, TypedDict, TypeVar
9
+
10
+ __all__ = [
11
+ "ip_address",
12
+ "geolocation",
13
+ "Geo",
14
+ "HeadersContext",
15
+ "set_headers",
16
+ "get_headers",
17
+ "headers_from_asgi_scope",
18
+ "headers_from_wsgi_environ",
19
+ ]
20
+
21
+
22
+ _cv_headers: ContextVar[Mapping[str, str] | None] = ContextVar("vercel_headers", default=None)
23
+ P = ParamSpec("P")
24
+ R = TypeVar("R")
25
+
26
+ # Header constants (same as TS names)
27
+ CITY_HEADER_NAME = "x-vercel-ip-city"
28
+ COUNTRY_HEADER_NAME = "x-vercel-ip-country"
29
+ IP_HEADER_NAME = "x-real-ip"
30
+ LATITUDE_HEADER_NAME = "x-vercel-ip-latitude"
31
+ LONGITUDE_HEADER_NAME = "x-vercel-ip-longitude"
32
+ REGION_HEADER_NAME = "x-vercel-ip-country-region"
33
+ POSTAL_CODE_HEADER_NAME = "x-vercel-ip-postal-code"
34
+ REQUEST_ID_HEADER_NAME = "x-vercel-id"
35
+
36
+ EMOJI_FLAG_UNICODE_STARTING_POSITION = 127397
37
+
38
+
39
+ def set_headers(headers: Mapping[str, str] | None) -> None:
40
+ _cv_headers.set(headers)
41
+
42
+
43
+ def get_headers() -> Mapping[str, str] | None:
44
+ return _cv_headers.get()
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class HeadersContext:
49
+ """Immutable snapshot of the current Vercel request headers."""
50
+
51
+ headers: Mapping[str, str] | None
52
+
53
+ @contextmanager
54
+ def use(self) -> Iterator[None]:
55
+ token = _cv_headers.set(self.headers)
56
+ try:
57
+ yield
58
+ finally:
59
+ _cv_headers.reset(token)
60
+
61
+ def run(self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:
62
+ with self.use():
63
+ return func(*args, **kwargs)
64
+
65
+
66
+ class _HeadersLike(Protocol):
67
+ def get(self, name: str) -> str | None: ...
68
+
69
+
70
+ class _RequestLike(Protocol):
71
+ headers: _HeadersLike
72
+
73
+
74
+ class Geo(TypedDict, total=False):
75
+ city: str | None
76
+ country: str | None
77
+ flag: str | None
78
+ region: str | None
79
+ countryRegion: str | None
80
+ latitude: str | None
81
+ longitude: str | None
82
+ postalCode: str | None
83
+
84
+
85
+ def _get_header(headers: _HeadersLike, key: str) -> str | None:
86
+ return headers.get(key)
87
+
88
+
89
+ def _get_header_decode(req: _RequestLike, key: str) -> str | None:
90
+ raw = _get_header(req.headers, key)
91
+ return urllib.parse.unquote(raw) if raw is not None else None
92
+
93
+
94
+ def _get_flag(country_code: str | None) -> str | None:
95
+ if not country_code or len(country_code) != 2 or not country_code.isalpha():
96
+ return None
97
+ return "".join(chr(EMOJI_FLAG_UNICODE_STARTING_POSITION + ord(c)) for c in country_code.upper())
98
+
99
+
100
+ def headers_from_asgi_scope(scope: Mapping[str, Any]) -> dict[str, str]:
101
+ """Return request headers decoded from an ASGI scope."""
102
+ return {
103
+ name.decode("latin-1"): value.decode("latin-1") for name, value in scope.get("headers", [])
104
+ }
105
+
106
+
107
+ def headers_from_wsgi_environ(environ: Mapping[str, Any]) -> dict[str, str]:
108
+ """Return request headers decoded from a WSGI environ mapping."""
109
+ headers: dict[str, str] = {}
110
+ if "CONTENT_TYPE" in environ:
111
+ headers["Content-Type"] = str(environ["CONTENT_TYPE"])
112
+ if "CONTENT_LENGTH" in environ:
113
+ headers["Content-Length"] = str(environ["CONTENT_LENGTH"])
114
+ for name, value in environ.items():
115
+ if not name.startswith("HTTP_"):
116
+ continue
117
+ header_name = name[5:].replace("_", "-").title()
118
+ headers[header_name] = str(value)
119
+ return headers
120
+
121
+
122
+ def ip_address(input: _RequestLike | _HeadersLike) -> str | None:
123
+ headers = input.headers if hasattr(input, "headers") else input
124
+ return _get_header(headers, IP_HEADER_NAME)
125
+
126
+
127
+ def _region_from_request_id(request_id: str | None) -> str | None:
128
+ if request_id is None:
129
+ return "dev1"
130
+ return request_id.split(":")[0]
131
+
132
+
133
+ def geolocation(request: _RequestLike) -> Geo:
134
+ headers = request.headers
135
+ return {
136
+ "city": _get_header_decode(request, CITY_HEADER_NAME),
137
+ "country": _get_header(headers, COUNTRY_HEADER_NAME),
138
+ "flag": _get_flag(_get_header(headers, COUNTRY_HEADER_NAME)),
139
+ "countryRegion": _get_header(headers, REGION_HEADER_NAME),
140
+ "region": _region_from_request_id(_get_header(headers, REQUEST_ID_HEADER_NAME)),
141
+ "latitude": _get_header(headers, LATITUDE_HEADER_NAME),
142
+ "longitude": _get_header(headers, LONGITUDE_HEADER_NAME),
143
+ "postalCode": _get_header(headers, POSTAL_CODE_HEADER_NAME),
144
+ }
@@ -0,0 +1 @@
1
+ """Generated vendored dependencies for vercel-headers-bundle."""
File without changes
@@ -0,0 +1 @@
1
+ __version__ = "0.7.1"