cavlyn 1.0.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.
cavlyn/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ from cavlyn._version import __version__
2
+ from cavlyn.builder import DynamicLink
3
+ from cavlyn.client import CavlynClient
4
+ from cavlyn.exceptions import (
5
+ CavlynApiError,
6
+ CavlynError,
7
+ CavlynNetworkError,
8
+ )
9
+ from cavlyn.models import (
10
+ CampaignResponse,
11
+ DynamicLinkResponse,
12
+ LinkMetadata,
13
+ ParsedLink,
14
+ )
15
+
16
+ __all__ = [
17
+ "__version__",
18
+ "CavlynClient",
19
+ "DynamicLink",
20
+ "LinkMetadata",
21
+ "DynamicLinkResponse",
22
+ "ParsedLink",
23
+ "CampaignResponse",
24
+ "CavlynError",
25
+ "CavlynApiError",
26
+ "CavlynNetworkError",
27
+ ]
cavlyn/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
cavlyn/builder.py ADDED
@@ -0,0 +1,150 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from typing import Any
5
+ from urllib.parse import urlencode
6
+
7
+ from cavlyn.models import LinkMetadata
8
+
9
+
10
+ class DynamicLink:
11
+ """Fluent builder for constructing Cavlyn dynamic link payloads."""
12
+
13
+ def __init__(self) -> None:
14
+ self._project_id: str | None = None
15
+ self._custom_alias: str | None = None
16
+ self._deep_path: str = "/"
17
+ self._query_params: dict[str, str] = {}
18
+ self._expires_at: str | None = None
19
+ self._campaign_id: str | None = None
20
+ self._metadata: LinkMetadata | None = None
21
+
22
+ @classmethod
23
+ def builder(cls) -> DynamicLink:
24
+ """Entrypoint for chaining methods to build a dynamic link."""
25
+ return cls()
26
+
27
+ def app_id(self, app_id: str) -> DynamicLink:
28
+ """Sets the app UUID for this dynamic link."""
29
+ self._project_id = str(app_id)
30
+ return self
31
+
32
+ def project_id(self, project_id: str) -> DynamicLink:
33
+ """Deprecated alias of app_id()."""
34
+ return self.app_id(project_id)
35
+
36
+ def custom_alias(self, alias: str) -> DynamicLink:
37
+ """Sets a branded custom alias/slug (e.g., 'summer-drop-2026')."""
38
+ self._custom_alias = alias.strip() if alias else None
39
+ return self
40
+
41
+ def deep_path(self, path: str) -> DynamicLink:
42
+ """
43
+ Sets the target in-app mobile deep path.
44
+ Automatically ensures a leading forward slash (e.g. '/products/123').
45
+ """
46
+ clean = path.strip() if path else "/"
47
+ self._deep_path = clean if clean.startswith("/") else f"/{clean}"
48
+ return self
49
+
50
+ def utm(
51
+ self,
52
+ source: str,
53
+ medium: str,
54
+ campaign: str,
55
+ term: str | None = None,
56
+ content: str | None = None,
57
+ ) -> DynamicLink:
58
+ """Attaches standard marketing attribution parameters."""
59
+ if source:
60
+ self._query_params["utm_source"] = source
61
+ if medium:
62
+ self._query_params["utm_medium"] = medium
63
+ if campaign:
64
+ self._query_params["utm_campaign"] = campaign
65
+ if term:
66
+ self._query_params["utm_term"] = term
67
+ if content:
68
+ self._query_params["utm_content"] = content
69
+ return self
70
+
71
+ def query_param(self, key: str, value: Any) -> DynamicLink:
72
+ """Adds an individual key-value parameter to the in-app route query."""
73
+ if key and value is not None:
74
+ self._query_params[str(key)] = str(value)
75
+ return self
76
+
77
+ def query_params(self, params: dict[str, Any]) -> DynamicLink:
78
+ """Adds multiple query parameters."""
79
+ for k, v in params.items():
80
+ self.query_param(k, v)
81
+ return self
82
+
83
+ def expires_at(self, expiry: datetime | str) -> DynamicLink:
84
+ """Sets an expiration date for the dynamic link."""
85
+ if isinstance(expiry, datetime):
86
+ self._expires_at = expiry.isoformat()
87
+ else:
88
+ self._expires_at = str(expiry)
89
+ return self
90
+
91
+ def campaign_id(self, campaign_id: str) -> DynamicLink:
92
+ """Assigns the dynamic link to an internal campaign."""
93
+ self._campaign_id = str(campaign_id)
94
+ return self
95
+
96
+ def metadata(self, meta: LinkMetadata | dict[str, Any]) -> DynamicLink:
97
+ """Attaches Open Graph and Twitter Card social preview metadata."""
98
+ if isinstance(meta, LinkMetadata):
99
+ self._metadata = meta
100
+ elif isinstance(meta, dict):
101
+ self._metadata = LinkMetadata.from_dict(meta)
102
+ return self
103
+
104
+ def social_preview(
105
+ self,
106
+ title: str,
107
+ description: str,
108
+ image_url: str | None = None,
109
+ ) -> DynamicLink:
110
+ """Convenience method to set social card title, description, and image."""
111
+ self._metadata = LinkMetadata(
112
+ title=title,
113
+ description=description,
114
+ og_title=title,
115
+ og_description=description,
116
+ og_image=image_url,
117
+ twitter_title=title,
118
+ twitter_description=description,
119
+ twitter_image=image_url,
120
+ )
121
+ return self
122
+
123
+ def build_payload(self, default_project_id: str | None = None, default_app_id: str | None = None) -> dict[str, Any]:
124
+ """Compiles the configured parameters into a REST API request dictionary."""
125
+ effective_app_id = self._project_id or default_app_id or default_project_id
126
+
127
+ compiled_query: str | None = None
128
+ if self._query_params:
129
+ compiled_query = urlencode(self._query_params)
130
+
131
+ payload: dict[str, Any] = {
132
+ "deepPath": self._deep_path,
133
+ }
134
+
135
+ if effective_app_id:
136
+ payload["appId"] = effective_app_id
137
+ if self._custom_alias:
138
+ payload["customAlias"] = self._custom_alias
139
+ if compiled_query:
140
+ payload["deepQuery"] = compiled_query
141
+ if self._expires_at:
142
+ payload["expiresAt"] = self._expires_at
143
+ if self._campaign_id:
144
+ payload["campaignId"] = self._campaign_id
145
+ if self._metadata:
146
+ meta_dict = self._metadata.to_dict()
147
+ if meta_dict:
148
+ payload["metadata"] = meta_dict
149
+
150
+ return payload
cavlyn/client.py ADDED
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from datetime import datetime
5
+ from typing import Any
6
+ from urllib.error import HTTPError, URLError
7
+ from urllib.parse import quote, urlparse
8
+ from urllib.request import Request, urlopen
9
+
10
+ from cavlyn._version import __version__
11
+ from cavlyn.builder import DynamicLink
12
+ from cavlyn.exceptions import (
13
+ CavlynApiError,
14
+ CavlynError,
15
+ CavlynNetworkError,
16
+ )
17
+ from cavlyn.models import CampaignResponse, DynamicLinkResponse, ParsedLink
18
+
19
+
20
+ class CavlynClient:
21
+ """
22
+ Client for the Cavlyn API.
23
+ Supports creating/managing dynamic deep links, UTM campaigns, and server events via X-API-Key.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ api_key: str,
29
+ base_url: str = "https://api.cavlyn.com",
30
+ default_app_id: str | None = None,
31
+ default_project_id: str | None = None,
32
+ link_domain: str | None = None,
33
+ timeout: float = 30.0,
34
+ ) -> None:
35
+ if not api_key:
36
+ raise ValueError("Cavlyn: api_key is required")
37
+
38
+ self.api_key = api_key.strip()
39
+ self.base_url = base_url.rstrip("/")
40
+ effective_app = default_app_id or default_project_id
41
+ self.default_app_id = str(effective_app) if effective_app else None
42
+ self.default_project_id = self.default_app_id
43
+ self.link_domain = (link_domain or self.base_url).rstrip("/")
44
+ self.timeout = timeout
45
+
46
+ def new_link(self) -> DynamicLink:
47
+ """Starts a new fluent DynamicLink builder with the default app ID attached."""
48
+ builder = DynamicLink.builder()
49
+ if self.default_app_id:
50
+ builder.app_id(self.default_app_id)
51
+ return builder
52
+
53
+ def create_dynamic_link(self, link: DynamicLink | dict[str, Any]) -> DynamicLinkResponse:
54
+ """Creates an intelligent dynamic link via POST /api/v1/links."""
55
+ if isinstance(link, DynamicLink):
56
+ payload = link.build_payload(default_app_id=self.default_app_id)
57
+ elif isinstance(link, dict):
58
+ payload = dict(link)
59
+ if "appId" not in payload and "projectId" not in payload and self.default_app_id:
60
+ payload["appId"] = self.default_app_id
61
+ else:
62
+ raise TypeError("link must be an instance of DynamicLink or a dict")
63
+
64
+ response_data = self._request("POST", "/api/v1/links", payload=payload)
65
+ return DynamicLinkResponse.from_dict(response_data, link_domain=self.link_domain)
66
+
67
+ def list_dynamic_links(self, app_id: str | None = None) -> list[DynamicLinkResponse]:
68
+ """Lists all dynamic links for the API key's app via GET /api/v1/links."""
69
+ effective_app = app_id or self.default_app_id
70
+ qs = f"?appId={quote(str(effective_app))}" if effective_app else ""
71
+ items = self._request("GET", f"/api/v1/links{qs}")
72
+ return [DynamicLinkResponse.from_dict(item, link_domain=self.link_domain) for item in items]
73
+
74
+ def get_dynamic_link(self, link_id: str) -> DynamicLinkResponse:
75
+ """Gets a single dynamic link by ID via GET /api/v1/links/{id}."""
76
+ data = self._request("GET", f"/api/v1/links/{quote(str(link_id))}")
77
+ return DynamicLinkResponse.from_dict(data, link_domain=self.link_domain)
78
+
79
+ def update_dynamic_link(self, link_id: str, updates: dict[str, Any]) -> DynamicLinkResponse:
80
+ """Partially updates a dynamic link via PATCH /api/v1/links/{id}."""
81
+ data = self._request("PATCH", f"/api/v1/links/{quote(str(link_id))}", payload=updates)
82
+ return DynamicLinkResponse.from_dict(data, link_domain=self.link_domain)
83
+
84
+ def delete_dynamic_link(self, link_id: str) -> None:
85
+ """Deletes a dynamic link via DELETE /api/v1/links/{id}."""
86
+ self._request("DELETE", f"/api/v1/links/{quote(str(link_id))}")
87
+
88
+ def create_campaign(
89
+ self,
90
+ name: str,
91
+ source: str | None = None,
92
+ medium: str | None = None,
93
+ campaign: str | None = None,
94
+ term: str | None = None,
95
+ content: str | None = None,
96
+ starts_at: datetime | str | None = None,
97
+ ends_at: datetime | str | None = None,
98
+ app_id: str | None = None,
99
+ ) -> CampaignResponse:
100
+ """Creates a UTM attribution campaign via POST /api/v1/campaigns."""
101
+ payload: dict[str, Any] = {"name": name}
102
+ effective_app = app_id or self.default_app_id
103
+ if effective_app:
104
+ payload["appId"] = str(effective_app)
105
+ if source is not None:
106
+ payload["source"] = source
107
+ if medium is not None:
108
+ payload["medium"] = medium
109
+ if campaign is not None:
110
+ payload["campaign"] = campaign
111
+ if term is not None:
112
+ payload["term"] = term
113
+ if content is not None:
114
+ payload["content"] = content
115
+ if starts_at is not None:
116
+ payload["startsAt"] = starts_at.isoformat() if isinstance(starts_at, datetime) else str(starts_at)
117
+ if ends_at is not None:
118
+ payload["endsAt"] = ends_at.isoformat() if isinstance(ends_at, datetime) else str(ends_at)
119
+
120
+ data = self._request("POST", "/api/v1/campaigns", payload=payload)
121
+ return CampaignResponse.from_dict(data)
122
+
123
+ def list_campaigns(self, app_id: str | None = None) -> list[CampaignResponse]:
124
+ """Lists all campaigns for the API key's app via GET /api/v1/campaigns."""
125
+ effective_app = app_id or self.default_app_id
126
+ qs = f"?appId={quote(str(effective_app))}" if effective_app else ""
127
+ items = self._request("GET", f"/api/v1/campaigns{qs}")
128
+ return [CampaignResponse.from_dict(item) for item in items]
129
+
130
+ def get_campaign(self, campaign_id: str) -> CampaignResponse:
131
+ """Gets a campaign by ID via GET /api/v1/campaigns/{id}."""
132
+ data = self._request("GET", f"/api/v1/campaigns/{quote(str(campaign_id))}")
133
+ return CampaignResponse.from_dict(data)
134
+
135
+ def parse_dynamic_link(self, code_or_url: str) -> ParsedLink:
136
+ """Parses and resolves a dynamic link by short code, custom alias, or full URL."""
137
+ if not code_or_url or not code_or_url.strip():
138
+ raise ValueError("code_or_url is required to parse dynamic link")
139
+
140
+ target = code_or_url.strip()
141
+ if "/" in target:
142
+ parsed = urlparse(target)
143
+ target = parsed.path.rstrip("/").split("/")[-1]
144
+
145
+ endpoint = f"/api/v1/links/resolve?code={quote(target)}"
146
+ response_data = self._request("GET", endpoint)
147
+ return ParsedLink.from_dict(response_data)
148
+
149
+ def track_event(
150
+ self,
151
+ event_type: str,
152
+ click_id: str | None = None,
153
+ revenue: float | None = None,
154
+ currency: str = "USD",
155
+ metadata: dict[str, Any] | None = None,
156
+ link_id: str | None = None,
157
+ installation_id: str | None = None,
158
+ idempotency_key: str | None = None,
159
+ ) -> None:
160
+ """
161
+ Ingests a server-side conversion or installation event tied to an attribution
162
+ link_id or click_id. Pass idempotency_key to make retries safe.
163
+ """
164
+ payload: dict[str, Any] = {
165
+ "eventType": event_type,
166
+ }
167
+ if link_id:
168
+ payload["linkId"] = link_id
169
+ if click_id:
170
+ payload["clickId"] = click_id
171
+ if installation_id:
172
+ payload["installationId"] = installation_id
173
+ if revenue is not None:
174
+ payload["revenue"] = revenue
175
+ payload["currency"] = currency
176
+ if metadata:
177
+ payload["metadata"] = metadata
178
+
179
+ extra = {"Idempotency-Key": idempotency_key} if idempotency_key else None
180
+ self._request("POST", "/api/v1/events", payload=payload, extra_headers=extra)
181
+
182
+ def _request(
183
+ self,
184
+ method: str,
185
+ path: str,
186
+ payload: dict[str, Any] | None = None,
187
+ extra_headers: dict[str, str] | None = None,
188
+ ) -> Any:
189
+ url = f"{self.base_url}{path}"
190
+ headers = {
191
+ "Content-Type": "application/json",
192
+ "X-API-Key": self.api_key,
193
+ "User-Agent": f"Cavlyn-Python-SDK/{__version__}",
194
+ **(extra_headers or {}),
195
+ }
196
+
197
+ data_bytes = None
198
+ if payload is not None:
199
+ data_bytes = json.dumps(payload).encode("utf-8")
200
+
201
+ req = Request(url, data=data_bytes, headers=headers, method=method)
202
+
203
+ try:
204
+ with urlopen(req, timeout=self.timeout) as resp:
205
+ status = resp.status
206
+ body = resp.read().decode("utf-8")
207
+ if status == 204 or not body.strip():
208
+ return {}
209
+ return json.loads(body)
210
+ except HTTPError as e:
211
+ raw_err = e.read().decode("utf-8")
212
+ err_json: dict[str, Any] = {}
213
+ msg = e.reason
214
+ try:
215
+ err_json = json.loads(raw_err)
216
+ msg = err_json.get("message", msg)
217
+ except Exception:
218
+ pass
219
+ raise CavlynApiError(status_code=e.code, message=msg, payload=err_json) from e
220
+ except URLError as e:
221
+ raise CavlynNetworkError(f"Network error connecting to {url}: {e.reason}") from e
222
+ except OSError as e: # includes socket timeouts raised while reading the response
223
+ raise CavlynNetworkError(f"Network error connecting to {url}: {e}") from e
224
+ except ValueError as e:
225
+ raise CavlynError(f"Invalid JSON in response from {url}: {e}") from e
cavlyn/exceptions.py ADDED
@@ -0,0 +1,18 @@
1
+ class CavlynError(Exception):
2
+ """Base exception for all Cavlyn SDK errors."""
3
+ pass
4
+
5
+
6
+ class CavlynApiError(CavlynError):
7
+ """Raised when the Cavlyn API returns a non-2xx status code."""
8
+
9
+ def __init__(self, status_code: int, message: str, payload: dict | None = None):
10
+ super().__init__(f"API Error ({status_code}): {message}")
11
+ self.status_code = status_code
12
+ self.message = message
13
+ self.payload = payload or {}
14
+
15
+
16
+ class CavlynNetworkError(CavlynError):
17
+ """Raised when network connectivity fails during API communication."""
18
+ pass
cavlyn/models.py ADDED
@@ -0,0 +1,167 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+ from urllib.parse import parse_qs
6
+
7
+
8
+ @dataclass
9
+ class LinkMetadata:
10
+ title: str | None = None
11
+ description: str | None = None
12
+ og_title: str | None = None
13
+ og_description: str | None = None
14
+ og_image: str | None = None
15
+ twitter_title: str | None = None
16
+ twitter_description: str | None = None
17
+ twitter_image: str | None = None
18
+
19
+ def to_dict(self) -> dict[str, Any]:
20
+ result: dict[str, Any] = {}
21
+ if self.title is not None:
22
+ result["title"] = self.title
23
+ if self.description is not None:
24
+ result["description"] = self.description
25
+ if self.og_title is not None:
26
+ result["ogTitle"] = self.og_title
27
+ if self.og_description is not None:
28
+ result["ogDescription"] = self.og_description
29
+ if self.og_image is not None:
30
+ result["ogImage"] = self.og_image
31
+ if self.twitter_title is not None:
32
+ result["twitterTitle"] = self.twitter_title
33
+ if self.twitter_description is not None:
34
+ result["twitterDescription"] = self.twitter_description
35
+ if self.twitter_image is not None:
36
+ result["twitterImage"] = self.twitter_image
37
+ return result
38
+
39
+ @classmethod
40
+ def from_dict(cls, data: dict[str, Any] | None) -> LinkMetadata | None:
41
+ if not data:
42
+ return None
43
+ return cls(
44
+ title=data.get("title"),
45
+ description=data.get("description"),
46
+ og_title=data.get("ogTitle"),
47
+ og_description=data.get("ogDescription"),
48
+ og_image=data.get("ogImage"),
49
+ twitter_title=data.get("twitterTitle"),
50
+ twitter_description=data.get("twitterDescription"),
51
+ twitter_image=data.get("twitterImage"),
52
+ )
53
+
54
+
55
+ @dataclass
56
+ class DynamicLinkResponse:
57
+ id: str
58
+ app_id: str
59
+ short_code: str
60
+ deep_path: str
61
+ url: str
62
+ custom_alias: str | None = None
63
+ deep_query: str | None = None
64
+ status: str = "ACTIVE"
65
+ expires_at: str | None = None
66
+ campaign_id: str | None = None
67
+ metadata: LinkMetadata | None = None
68
+
69
+ @property
70
+ def project_id(self) -> str:
71
+ return self.app_id
72
+
73
+ @property
74
+ def slug(self) -> str:
75
+ return self.custom_alias if self.custom_alias else self.short_code
76
+
77
+ @classmethod
78
+ def from_dict(cls, data: dict[str, Any], link_domain: str) -> DynamicLinkResponse:
79
+ slug = data.get("customAlias") or data.get("shortCode") or ""
80
+ clean_domain = link_domain.rstrip("/")
81
+ full_url = f"{clean_domain}/{slug}"
82
+ resolved_app_id = data.get("appId") or data.get("projectId") or ""
83
+
84
+ return cls(
85
+ id=data["id"],
86
+ app_id=resolved_app_id,
87
+ short_code=data["shortCode"],
88
+ custom_alias=data.get("customAlias"),
89
+ deep_path=data["deepPath"],
90
+ deep_query=data.get("deepQuery"),
91
+ status=data.get("status", "ACTIVE"),
92
+ expires_at=data.get("expiresAt"),
93
+ campaign_id=data.get("campaignId"),
94
+ metadata=LinkMetadata.from_dict(data.get("metadata")),
95
+ url=full_url,
96
+ )
97
+
98
+
99
+ @dataclass
100
+ class ParsedLink:
101
+ id: str
102
+ app_id: str
103
+ short_code: str
104
+ deep_path: str
105
+ custom_alias: str | None = None
106
+ deep_query: str | None = None
107
+ status: str = "ACTIVE"
108
+ expires_at: str | None = None
109
+ campaign_id: str | None = None
110
+ metadata: LinkMetadata | None = None
111
+ query_parameters: dict[str, str] = field(default_factory=dict)
112
+
113
+ @property
114
+ def project_id(self) -> str:
115
+ return self.app_id
116
+
117
+ @classmethod
118
+ def from_dict(cls, data: dict[str, Any]) -> ParsedLink:
119
+ deep_query = data.get("deepQuery")
120
+ query_params: dict[str, str] = {}
121
+ if deep_query:
122
+ parsed = parse_qs(deep_query)
123
+ query_params = {k: v[0] if v else "" for k, v in parsed.items()}
124
+ resolved_app_id = data.get("appId") or data.get("projectId") or ""
125
+
126
+ return cls(
127
+ id=data["id"],
128
+ app_id=resolved_app_id,
129
+ short_code=data["shortCode"],
130
+ custom_alias=data.get("customAlias"),
131
+ deep_path=data["deepPath"],
132
+ deep_query=deep_query,
133
+ status=data.get("status", "ACTIVE"),
134
+ expires_at=data.get("expiresAt"),
135
+ campaign_id=data.get("campaignId"),
136
+ metadata=LinkMetadata.from_dict(data.get("metadata")),
137
+ query_parameters=query_params,
138
+ )
139
+
140
+
141
+ @dataclass
142
+ class CampaignResponse:
143
+ id: str
144
+ app_id: str
145
+ name: str
146
+ source: str | None = None
147
+ medium: str | None = None
148
+ campaign: str | None = None
149
+ term: str | None = None
150
+ content: str | None = None
151
+ starts_at: str | None = None
152
+ ends_at: str | None = None
153
+
154
+ @classmethod
155
+ def from_dict(cls, data: dict[str, Any]) -> CampaignResponse:
156
+ return cls(
157
+ id=data["id"],
158
+ app_id=data.get("appId") or data.get("projectId") or "",
159
+ name=data["name"],
160
+ source=data.get("source"),
161
+ medium=data.get("medium"),
162
+ campaign=data.get("campaign"),
163
+ term=data.get("term"),
164
+ content=data.get("content"),
165
+ starts_at=data.get("startsAt"),
166
+ ends_at=data.get("endsAt"),
167
+ )
cavlyn/py.typed ADDED
File without changes
@@ -0,0 +1,243 @@
1
+ Metadata-Version: 2.4
2
+ Name: cavlyn
3
+ Version: 1.0.0
4
+ Summary: Official Python server SDK for Cavlyn: generate dynamic links, parse/resolve deep links, configure multi-platform routing, and ingest server events.
5
+ Author-email: Cavlyn System <dev@cavlyn.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/casontek/smart-attribution-system/tree/main/sdk/python
8
+ Project-URL: Repository, https://github.com/casontek/smart-attribution-system
9
+ Project-URL: Issues, https://github.com/casontek/smart-attribution-system/issues
10
+ Project-URL: Documentation, https://docs.cavlyn.com
11
+ Keywords: dynamic-links,deep-linking,deferred-deep-linking,attribution,smart-links,url-shortener,mobile-attribution
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # Cavlyn Python Server SDK
27
+
28
+ Official server-side Python library for Cavlyn. Create and manage intelligent dynamic deep links and UTM campaigns, parse/resolve deep links, configure multi-platform routing, and ingest server-side conversion events.
29
+
30
+ ## Features
31
+
32
+ - **Programmatic Dynamic Deep Link CRUD**: Create, list, inspect, update, and delete branded short links from backend services, Celery jobs, transactional emails, or Django/FastAPI applications.
33
+ - **Programmatic Campaign Creation & Querying**: Create and list UTM attribution campaigns and attach `campaign_id` directly to dynamic links.
34
+ - **Automatic App Scoping**: `app_id` is inferred automatically from your `X-API-Key` when omitted.
35
+ - **Deep links for mobile apps**: Links open your app through Universal Links and App Links. What happens when the app isn't installed (App Store, Play Store or web) is configured per app in the Cavlyn dashboard, not per link.
36
+ - **Dynamic Link Parsing & Resolution**: Decode short codes or full dynamic link URLs into structured data, parameters, and campaign tokens.
37
+ - **Open Graph Preview Customizer**: Attach custom social share preview cards for WhatsApp, iMessage, Twitter, and Slack.
38
+ - **Zero Heavy Dependencies**: Built with pure Python standard library (`urllib`, `dataclasses`, `json`), ensuring zero package conflicts in your environment.
39
+
40
+ ---
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ pip install cavlyn
46
+ ```
47
+
48
+ *(Or copy `cavlyn/` directly into your Python project)*
49
+
50
+ ---
51
+
52
+ ## Quickstart
53
+
54
+ ### 1. Initialize Client
55
+
56
+ ```python
57
+ import os
58
+ from cavlyn import CavlynClient
59
+
60
+ client = CavlynClient(
61
+ api_key=os.environ["CAVLYN_API_KEY"],
62
+ base_url="https://api.cavlyn.com", # default; use "http://localhost:8080" for local development
63
+ link_domain="https://link.yourdomain.com", # Branded short link domain used to build link.url
64
+ # timeout=30.0, # seconds
65
+ # default_app_id is optional — inferred automatically from X-API-Key
66
+ )
67
+ ```
68
+
69
+ ---
70
+
71
+ ### 2. Create & List UTM Campaigns
72
+
73
+ ```python
74
+ campaign = client.create_campaign(
75
+ name="Summer Drop 2026",
76
+ source="newsletter",
77
+ medium="email",
78
+ campaign="summer_drop",
79
+ starts_at="2026-06-01T00:00:00Z",
80
+ ends_at="2026-08-31T23:59:59Z",
81
+ )
82
+
83
+ campaigns = client.list_campaigns()
84
+ fetched = client.get_campaign(campaign.id)
85
+ ```
86
+
87
+ ---
88
+
89
+ ### 3. Generate & Manage Dynamic Deep Links
90
+
91
+ ```python
92
+ link = client.create_dynamic_link(
93
+ client.new_link()
94
+ .deep_path("/products/summer-jacket")
95
+ .custom_alias("summer-sale-2026")
96
+ .campaign_id(campaign.id)
97
+ .utm(source="newsletter", medium="email", campaign="summer_drop")
98
+ .query_param("ref", "vip_creator_42")
99
+ .social_preview(
100
+ title="Summer Jacket - 40% Off",
101
+ description="Shop the exclusive summer collection directly in the app.",
102
+ image_url="https://cdn.yourdomain.com/images/jacket.jpg",
103
+ )
104
+ )
105
+
106
+ print("Dynamic Link URL:", link.url)
107
+ # -> "https://link.yourdomain.com/summer-sale-2026"
108
+
109
+ # List, get, update, or delete existing links
110
+ all_links = client.list_dynamic_links()
111
+ single = client.get_dynamic_link(link.id)
112
+ client.update_dynamic_link(link.id, {"deepPath": "/products/summer-jacket-v2", "status": "ACTIVE"})
113
+ client.delete_dynamic_link(link.id)
114
+ ```
115
+
116
+ ---
117
+
118
+ ### 4. Parse and Resolve a Dynamic Link
119
+
120
+ When your backend receives a dynamic link or short code (e.g. from an affiliate webhook, incoming email click, or QR scan), parse it into its structured payload:
121
+
122
+ ```python
123
+ parsed = client.parse_dynamic_link("summer-sale-2026")
124
+
125
+ print("In-App Route:", parsed.deep_path) # "/products/summer-jacket"
126
+ print("UTM Source:", parsed.query_parameters.get("utm_source")) # "newsletter"
127
+ print("Referral:", parsed.query_parameters.get("ref")) # "vip_creator_42"
128
+ ```
129
+
130
+ ---
131
+
132
+ ### 5. Track Server-Side Conversions
133
+
134
+ Record conversions that occur off-device (e.g. Stripe webhook handler, subscription renewals):
135
+
136
+ ```python
137
+ client.track_event(
138
+ event_type="CONVERSION",
139
+ click_id="550e8400-e29b-41d4-a716-446655440000",
140
+ revenue=129.99,
141
+ idempotency_key="stripe_evt_1Nxyz", # optional: makes retries safe
142
+ currency="USD",
143
+ metadata={
144
+ "order_id": "ORD-12849",
145
+ "plan": "annual_pro",
146
+ },
147
+ )
148
+ ```
149
+
150
+ ---
151
+
152
+ ## Error handling
153
+
154
+ ```python
155
+ from cavlyn import CavlynApiError, CavlynNetworkError
156
+
157
+ try:
158
+ client.get_dynamic_link(link_id)
159
+ except CavlynApiError as e: # non-2xx response
160
+ print(e.status_code, e.message)
161
+ except CavlynNetworkError: # timeout / connection failure
162
+ ...
163
+ ```
164
+
165
+ Requests are not retried automatically. Requires Python 3.9+; no third-party dependencies.
166
+
167
+ ---
168
+
169
+ ## Framework Integration Examples
170
+
171
+ ### FastAPI
172
+
173
+ ```python
174
+ from fastapi import FastAPI
175
+ from cavlyn import CavlynClient
176
+
177
+ app = FastAPI()
178
+ client = CavlynClient(api_key="...", link_domain="https://link.yourdomain.com")
179
+
180
+ @app.post("/api/referral-links")
181
+ def create_referral_link(user_id: str, campaign_id: str | None = None):
182
+ builder = (
183
+ client.new_link()
184
+ .deep_path(f"/invite/{user_id}")
185
+ .custom_alias(f"invite-{user_id}")
186
+ .utm(source="app_referral", medium="in_app", campaign="user_invites")
187
+ )
188
+ if campaign_id:
189
+ builder.campaign_id(campaign_id)
190
+ link = client.create_dynamic_link(builder)
191
+ return {"id": link.id, "dynamic_link": link.url}
192
+ ```
193
+
194
+ ### Django
195
+
196
+ ```python
197
+ # views.py
198
+ from django.conf import settings
199
+ from django.http import JsonResponse
200
+ from cavlyn import CavlynClient
201
+
202
+ client = CavlynClient(api_key=settings.CAVLYN_API_KEY, base_url=settings.CAVLYN_API_URL)
203
+
204
+ def generate_order_link(request, order_id):
205
+ link = client.create_dynamic_link(
206
+ client.new_link()
207
+ .deep_path(f"/orders/{order_id}")
208
+ .utm(source="transactional_email", medium="email", campaign="receipt")
209
+ )
210
+ return JsonResponse({"link_url": link.url})
211
+ ```
212
+
213
+ ---
214
+
215
+ ## API Reference
216
+
217
+ ### `CavlynClient`
218
+
219
+ - `new_link() -> DynamicLink`: Starts a fluent builder.
220
+ - `create_dynamic_link(link: DynamicLink | dict) -> DynamicLinkResponse`: Creates a dynamic link (`POST /api/v1/links`).
221
+ - `list_dynamic_links(app_id: str | None = None) -> list[DynamicLinkResponse]`: Lists links for the app (`GET /api/v1/links`).
222
+ - `get_dynamic_link(link_id: str) -> DynamicLinkResponse`: Gets a single link (`GET /api/v1/links/{id}`).
223
+ - `update_dynamic_link(link_id: str, updates: dict) -> DynamicLinkResponse`: Partially updates a link (`PATCH /api/v1/links/{id}`).
224
+ - `delete_dynamic_link(link_id: str) -> None`: Deletes a link (`DELETE /api/v1/links/{id}`).
225
+ - `create_campaign(name, source=None, medium=None, campaign=None, term=None, content=None, starts_at=None, ends_at=None, app_id=None) -> CampaignResponse`: Creates a campaign (`POST /api/v1/campaigns`).
226
+ - `list_campaigns(app_id: str | None = None) -> list[CampaignResponse]`: Lists campaigns (`GET /api/v1/campaigns`).
227
+ - `get_campaign(campaign_id: str) -> CampaignResponse`: Gets a campaign (`GET /api/v1/campaigns/{id}`).
228
+ - `parse_dynamic_link(code_or_url: str) -> ParsedLink`: Parses/resolves a link (`GET /api/v1/links/resolve`).
229
+ - `track_event(event_type, click_id=None, revenue=None, currency="USD", metadata=None, link_id=None, installation_id=None, idempotency_key=None)`: Sends a server event (`POST /api/v1/events`). Events are only attributed when they carry a `link_id` or `click_id`.
230
+
231
+ ### `DynamicLink` Builder Methods
232
+
233
+ - `.deep_path(path: str)`
234
+ - `.custom_alias(alias: str)`
235
+ - `.app_id(app_id: str)` *(optional when using `X-API-Key`; `.project_id()` kept as deprecated alias)*
236
+ - `.campaign_id(campaign_id: str)`
237
+ - `.utm(source, medium, campaign, term=None, content=None)`
238
+ - `.query_param(key, value)`
239
+ - `.query_params(params: dict)`
240
+ - `.social_preview(title, description, image_url=None)`
241
+ - `.metadata(meta: LinkMetadata | dict)`
242
+ - `.expires_at(expiry: datetime | str)`
243
+ - `.build_payload(default_app_id=None) -> dict`
@@ -0,0 +1,12 @@
1
+ cavlyn/__init__.py,sha256=_WriZc6Gul0_sOM6b3LQIAfYcncTkeZTqnoMC3sX1NU,553
2
+ cavlyn/_version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
3
+ cavlyn/builder.py,sha256=KhoqqM9-fzoEbwLVJTvoXIcfoyvvaOgXO5uur1oD4zQ,5209
4
+ cavlyn/client.py,sha256=hKf97g7I1ohcqnTb7m-AZM1mb8A5vCDKL1PIgdpnhKo,9398
5
+ cavlyn/exceptions.py,sha256=TgvUCN3EHh9OO629DTJwuFah-AG29idfrvUzKK2i7uE,580
6
+ cavlyn/models.py,sha256=llPZm9wrv4IgBiJnIG3wOROebyju-hvlHBzXTVxUFXA,5391
7
+ cavlyn/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ cavlyn-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ cavlyn-1.0.0.dist-info/METADATA,sha256=NMiMsF4whcC7anUjbj0k5eRAbvAHqmKbLLMqPcJgRbI,9135
10
+ cavlyn-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ cavlyn-1.0.0.dist-info/top_level.txt,sha256=EvFWvT2tmgEcvdaOGs2EYUNuRUdf2UWQpAgfx82MwAA,7
12
+ cavlyn-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ cavlyn