api-everything 0.5.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.
Files changed (281) hide show
  1. api_everything/__init__.py +3 -0
  2. api_everything/__main__.py +8 -0
  3. api_everything/check.py +168 -0
  4. api_everything/chrome_cmd.py +131 -0
  5. api_everything/cli.py +803 -0
  6. api_everything/config.py +321 -0
  7. api_everything/delivery.py +518 -0
  8. api_everything/delivery_git.py +94 -0
  9. api_everything/driver/__init__.py +37 -0
  10. api_everything/driver/attach.py +95 -0
  11. api_everything/driver/base.py +80 -0
  12. api_everything/driver/chrome.py +127 -0
  13. api_everything/driver/profile.py +84 -0
  14. api_everything/engine.py +381 -0
  15. api_everything/errors.py +23 -0
  16. api_everything/hooks.py +52 -0
  17. api_everything/login.py +95 -0
  18. api_everything/mcp_bridge.py +249 -0
  19. api_everything/metrics.py +87 -0
  20. api_everything/mock_site/__init__.py +5 -0
  21. api_everything/mock_site/__main__.py +18 -0
  22. api_everything/mock_site/app.py +262 -0
  23. api_everything/pipeline.py +934 -0
  24. api_everything/pool.py +553 -0
  25. api_everything/ratelimit.py +67 -0
  26. api_everything/recipe/__init__.py +6 -0
  27. api_everything/recipe/actions.py +56 -0
  28. api_everything/recipe/jsonpath.py +22 -0
  29. api_everything/recipe/loader.py +142 -0
  30. api_everything/recipe/params.py +120 -0
  31. api_everything/recipe/schema.py +235 -0
  32. api_everything/recipes/alignmentforum/feed.yaml +15 -0
  33. api_everything/recipes/alpine_docs/search.yaml +32 -0
  34. api_everything/recipes/angular_docs/search.yaml +32 -0
  35. api_everything/recipes/anthropic_status/summary.yaml +17 -0
  36. api_everything/recipes/apis_guru/providers.yaml +15 -0
  37. api_everything/recipes/arbeitnow/jobs.yaml +20 -0
  38. api_everything/recipes/arin_rdap/ip.yaml +24 -0
  39. api_everything/recipes/artifacthub/browse.yaml +22 -0
  40. api_everything/recipes/artifacthub/search.yaml +24 -0
  41. api_everything/recipes/astro_docs/search.yaml +32 -0
  42. api_everything/recipes/atlassian_status/summary.yaml +17 -0
  43. api_everything/recipes/babel_docs/search.yaml +32 -0
  44. api_everything/recipes/binance/price.yaml +24 -0
  45. api_everything/recipes/bugzilla/bugs.yaml +24 -0
  46. api_everything/recipes/bundlephobia/size.yaml +24 -0
  47. api_everything/recipes/caddy_docs/search.yaml +32 -0
  48. api_everything/recipes/caniuse/search.yaml +24 -0
  49. api_everything/recipes/capacitor_docs/search.yaml +32 -0
  50. api_everything/recipes/cdnjs/library.yaml +22 -0
  51. api_everything/recipes/cdnjs/search.yaml +27 -0
  52. api_everything/recipes/certspotter/issuances.yaml +27 -0
  53. api_everything/recipes/cheerio_docs/search.yaml +32 -0
  54. api_everything/recipes/circleci_status/summary.yaml +17 -0
  55. api_everything/recipes/cisa_kev/catalog.yaml +17 -0
  56. api_everything/recipes/civitai/models.yaml +26 -0
  57. api_everything/recipes/cloudflare_status/summary.yaml +17 -0
  58. api_everything/recipes/cncf_landscape/projects.yaml +20 -0
  59. api_everything/recipes/cncf_landscape/ui.yaml +18 -0
  60. api_everything/recipes/coinbase/rates.yaml +24 -0
  61. api_everything/recipes/coingecko/trending.yaml +17 -0
  62. api_everything/recipes/conda_forge/package.yaml +25 -0
  63. api_everything/recipes/crates/categories.yaml +15 -0
  64. api_everything/recipes/crates/downloads.yaml +22 -0
  65. api_everything/recipes/crates/keywords.yaml +15 -0
  66. api_everything/recipes/crates/reverse_deps.yaml +22 -0
  67. api_everything/recipes/crates/search.yaml +24 -0
  68. api_everything/recipes/crates/summary.yaml +15 -0
  69. api_everything/recipes/crates/user.yaml +22 -0
  70. api_everything/recipes/crates/versions.yaml +22 -0
  71. api_everything/recipes/crossref/works.yaml +24 -0
  72. api_everything/recipes/cve_org/record.yaml +24 -0
  73. api_everything/recipes/debian_sources/search.yaml +24 -0
  74. api_everything/recipes/deps_dev/npm_spa.yaml +22 -0
  75. api_everything/recipes/deps_dev/package.yaml +23 -0
  76. api_everything/recipes/devdocs/index.yaml +18 -0
  77. api_everything/recipes/devto/articles.yaml +26 -0
  78. api_everything/recipes/devto/latest.yaml +18 -0
  79. api_everything/recipes/devto/tags.yaml +18 -0
  80. api_everything/recipes/devto/top.yaml +18 -0
  81. api_everything/recipes/digitalocean_status/summary.yaml +17 -0
  82. api_everything/recipes/digitalocean_status/ui.yaml +15 -0
  83. api_everything/recipes/discord_status/summary.yaml +17 -0
  84. api_everything/recipes/dns_google/resolve.yaml +24 -0
  85. api_everything/recipes/drizzle_docs/search.yaml +32 -0
  86. api_everything/recipes/echojs/latest.yaml +17 -0
  87. api_everything/recipes/ecosystems/package.yaml +25 -0
  88. api_everything/recipes/endoflife/product.yaml +24 -0
  89. api_everything/recipes/epss/score.yaml +24 -0
  90. api_everything/recipes/exchangerate/latest.yaml +24 -0
  91. api_everything/recipes/firefox_addons/search.yaml +26 -0
  92. api_everything/recipes/fly_status/summary.yaml +17 -0
  93. api_everything/recipes/formik_docs/search.yaml +32 -0
  94. api_everything/recipes/frankfurter/rates.yaml +24 -0
  95. api_everything/recipes/gcp_status/incidents.yaml +20 -0
  96. api_everything/recipes/github/explore.yaml +35 -0
  97. api_everything/recipes/github/gists.yaml +18 -0
  98. api_everything/recipes/github/issues.yaml +30 -0
  99. api_everything/recipes/github/license.yaml +23 -0
  100. api_everything/recipes/github/org.yaml +22 -0
  101. api_everything/recipes/github/releases.yaml +30 -0
  102. api_everything/recipes/github/repo.yaml +28 -0
  103. api_everything/recipes/github/user.yaml +22 -0
  104. api_everything/recipes/github_advisories/list.yaml +20 -0
  105. api_everything/recipes/github_status/summary.yaml +17 -0
  106. api_everything/recipes/github_status/ui.yaml +15 -0
  107. api_everything/recipes/gitlab/issues.yaml +24 -0
  108. api_everything/recipes/gitlab/repo.yaml +21 -0
  109. api_everything/recipes/gitlab/search.yaml +26 -0
  110. api_everything/recipes/go_proxy/latest.yaml +24 -0
  111. api_everything/recipes/grafana_status/summary.yaml +17 -0
  112. api_everything/recipes/hackage/versions.yaml +24 -0
  113. api_everything/recipes/hackernews/ask.yaml +18 -0
  114. api_everything/recipes/hackernews/front_page.yaml +18 -0
  115. api_everything/recipes/hackernews/item.yaml +21 -0
  116. api_everything/recipes/hackernews/jobs.yaml +18 -0
  117. api_everything/recipes/hackernews/latest.yaml +25 -0
  118. api_everything/recipes/hackernews/search.yaml +34 -0
  119. api_everything/recipes/hackernews/show.yaml +18 -0
  120. api_everything/recipes/hashicorp_releases/list.yaml +27 -0
  121. api_everything/recipes/hashicorp_status/summary.yaml +17 -0
  122. api_everything/recipes/helm_docs/search.yaml +32 -0
  123. api_everything/recipes/heroku_status/current.yaml +17 -0
  124. api_everything/recipes/hexpm/search.yaml +27 -0
  125. api_everything/recipes/hf_papers/daily.yaml +20 -0
  126. api_everything/recipes/himalayas/jobs.yaml +17 -0
  127. api_everything/recipes/homebrew/cask.yaml +22 -0
  128. api_everything/recipes/homebrew/formula.yaml +26 -0
  129. api_everything/recipes/hono_docs/search.yaml +32 -0
  130. api_everything/recipes/httpbin/json.yaml +17 -0
  131. api_everything/recipes/httpbin/uuid.yaml +15 -0
  132. api_everything/recipes/huggingface/datasets.yaml +25 -0
  133. api_everything/recipes/huggingface/model_info.yaml +27 -0
  134. api_everything/recipes/huggingface/models.yaml +28 -0
  135. api_everything/recipes/huggingface/spaces.yaml +25 -0
  136. api_everything/recipes/inspirehep/papers.yaml +24 -0
  137. api_everything/recipes/ionic_docs/search.yaml +32 -0
  138. api_everything/recipes/ipify/ipv4.yaml +17 -0
  139. api_everything/recipes/ipwho/lookup.yaml +24 -0
  140. api_everything/recipes/jest_docs/search.yaml +32 -0
  141. api_everything/recipes/jsdelivr/gh.yaml +27 -0
  142. api_everything/recipes/jsdelivr/npm.yaml +24 -0
  143. api_everything/recipes/jsr/search.yaml +27 -0
  144. api_everything/recipes/launchdarkly_status/summary.yaml +17 -0
  145. api_everything/recipes/lemmy/hot.yaml +17 -0
  146. api_everything/recipes/lesswrong/feed.yaml +17 -0
  147. api_everything/recipes/llamaindex_docs/search.yaml +32 -0
  148. api_everything/recipes/lobsters/hottest.yaml +20 -0
  149. api_everything/recipes/luma/category.yaml +22 -0
  150. api_everything/recipes/luma/events.yaml +17 -0
  151. api_everything/recipes/mastodon/explore.yaml +26 -0
  152. api_everything/recipes/mastodon/tag.yaml +23 -0
  153. api_everything/recipes/mastodon/trends_tags.yaml +18 -0
  154. api_everything/recipes/mdn/search.yaml +24 -0
  155. api_everything/recipes/metacpan/search.yaml +24 -0
  156. api_everything/recipes/microlink/preview.yaml +24 -0
  157. api_everything/recipes/mikro_orm_docs/search.yaml +32 -0
  158. api_everything/recipes/mock/items.yaml +35 -0
  159. api_everything/recipes/mongodb_status/summary.yaml +17 -0
  160. api_everything/recipes/nager_date/holidays.yaml +32 -0
  161. api_everything/recipes/neon_docs/search.yaml +32 -0
  162. api_everything/recipes/nestjs_docs/search.yaml +32 -0
  163. api_everything/recipes/netlify_status/summary.yaml +17 -0
  164. api_everything/recipes/nextjs_docs/search.yaml +32 -0
  165. api_everything/recipes/nodejs_dist/releases.yaml +17 -0
  166. api_everything/recipes/npm/dist_tags.yaml +22 -0
  167. api_everything/recipes/npm/package.yaml +25 -0
  168. api_everything/recipes/npm/search.yaml +25 -0
  169. api_everything/recipes/npm_downloads/weekly.yaml +24 -0
  170. api_everything/recipes/npm_status/summary.yaml +17 -0
  171. api_everything/recipes/npmtrends/compare.yaml +22 -0
  172. api_everything/recipes/nuget/search.yaml +27 -0
  173. api_everything/recipes/nuxt_docs/search.yaml +32 -0
  174. api_everything/recipes/nvd/cve.yaml +22 -0
  175. api_everything/recipes/nvd/cves.yaml +24 -0
  176. api_everything/recipes/open_elevation/lookup.yaml +29 -0
  177. api_everything/recipes/openai_status/summary.yaml +17 -0
  178. api_everything/recipes/opencollective/search.yaml +22 -0
  179. api_everything/recipes/openfda/events.yaml +17 -0
  180. api_everything/recipes/openlibrary/search.yaml +24 -0
  181. api_everything/recipes/openmeteo/forecast.yaml +17 -0
  182. api_everything/recipes/openrouter/models.yaml +20 -0
  183. api_everything/recipes/openstreetmap/geocode.yaml +27 -0
  184. api_everything/recipes/openstreetmap/reverse.yaml +27 -0
  185. api_everything/recipes/osv/vuln.yaml +24 -0
  186. api_everything/recipes/packagist/search.yaml +27 -0
  187. api_everything/recipes/peps/list.yaml +17 -0
  188. api_everything/recipes/pinia_docs/search.yaml +32 -0
  189. api_everything/recipes/pkg_go_dev/browse.yaml +15 -0
  190. api_everything/recipes/pkg_go_dev/package.yaml +25 -0
  191. api_everything/recipes/playwright_docs/search.yaml +32 -0
  192. api_everything/recipes/pnpm_docs/search.yaml +32 -0
  193. api_everything/recipes/pokeapi/pokemon.yaml +24 -0
  194. api_everything/recipes/posthog_docs/search.yaml +32 -0
  195. api_everything/recipes/postman_echo/get.yaml +24 -0
  196. api_everything/recipes/postman_status/summary.yaml +17 -0
  197. api_everything/recipes/preact_docs/search.yaml +32 -0
  198. api_everything/recipes/pubdev/search.yaml +24 -0
  199. api_everything/recipes/pubmed/search.yaml +24 -0
  200. api_everything/recipes/puppeteer_docs/search.yaml +32 -0
  201. api_everything/recipes/pypi/package.yaml +24 -0
  202. api_everything/recipes/pypi/version.yaml +27 -0
  203. api_everything/recipes/quay/search.yaml +27 -0
  204. api_everything/recipes/quora/answers.yaml +46 -0
  205. api_everything/recipes/qwik_docs/search.yaml +32 -0
  206. api_everything/recipes/ray_docs/search.yaml +32 -0
  207. api_everything/recipes/rdap/domain.yaml +24 -0
  208. api_everything/recipes/react_docs/search.yaml +32 -0
  209. api_everything/recipes/react_hook_form_docs/search.yaml +32 -0
  210. api_everything/recipes/reactrouter_docs/search.yaml +32 -0
  211. api_everything/recipes/reddit/search.yaml +48 -0
  212. api_everything/recipes/reddit_status/summary.yaml +17 -0
  213. api_everything/recipes/remoteok/jobs.yaml +17 -0
  214. api_everything/recipes/render_status/summary.yaml +17 -0
  215. api_everything/recipes/repology/project.yaml +24 -0
  216. api_everything/recipes/ripe_stat/prefix.yaml +24 -0
  217. api_everything/recipes/rollup_docs/search.yaml +32 -0
  218. api_everything/recipes/rsbuild_docs/search.yaml +32 -0
  219. api_everything/recipes/rubygems/gem.yaml +22 -0
  220. api_everything/recipes/rubygems/search.yaml +27 -0
  221. api_everything/recipes/sendgrid_status/summary.yaml +17 -0
  222. api_everything/recipes/sequelize_docs/search.yaml +32 -0
  223. api_everything/recipes/shodan_internetdb/host.yaml +24 -0
  224. api_everything/recipes/shopify_status/summary.yaml +17 -0
  225. api_everything/recipes/sigstore_rekor/log.yaml +17 -0
  226. api_everything/recipes/slack_status/current.yaml +17 -0
  227. api_everything/recipes/spdx/licenses.yaml +17 -0
  228. api_everything/recipes/stackexchange/sites.yaml +20 -0
  229. api_everything/recipes/stackoverflow/answers.yaml +15 -0
  230. api_everything/recipes/stackoverflow/questions.yaml +18 -0
  231. api_everything/recipes/stackoverflow/search.yaml +27 -0
  232. api_everything/recipes/stackoverflow/tags.yaml +18 -0
  233. api_everything/recipes/strapi_docs/search.yaml +32 -0
  234. api_everything/recipes/strawberry_docs/search.yaml +32 -0
  235. api_everything/recipes/stripe_status/current.yaml +17 -0
  236. api_everything/recipes/substack/explore.yaml +22 -0
  237. api_everything/recipes/substack/search.yaml +31 -0
  238. api_everything/recipes/sunrise_sunset/times.yaml +29 -0
  239. api_everything/recipes/supabase_status/summary.yaml +17 -0
  240. api_everything/recipes/swr_docs/search.yaml +32 -0
  241. api_everything/recipes/tanstack_docs/search.yaml +32 -0
  242. api_everything/recipes/tc39/proposals.yaml +20 -0
  243. api_everything/recipes/techempower/results.yaml +15 -0
  244. api_everything/recipes/temporal_docs/search.yaml +32 -0
  245. api_everything/recipes/terraform_registry/browse.yaml +25 -0
  246. api_everything/recipes/terraform_registry/search.yaml +24 -0
  247. api_everything/recipes/testing_library_docs/search.yaml +32 -0
  248. api_everything/recipes/tvmaze/shows.yaml +24 -0
  249. api_everything/recipes/twilio_status/summary.yaml +17 -0
  250. api_everything/recipes/upstash_docs/search.yaml +32 -0
  251. api_everything/recipes/valibot_docs/search.yaml +32 -0
  252. api_everything/recipes/vercel_status/summary.yaml +17 -0
  253. api_everything/recipes/vercel_status/ui.yaml +15 -0
  254. api_everything/recipes/vue_docs/search.yaml +32 -0
  255. api_everything/recipes/w3c/specs.yaml +17 -0
  256. api_everything/recipes/wayback/available.yaml +24 -0
  257. api_everything/recipes/webdriverio_docs/search.yaml +32 -0
  258. api_everything/recipes/webpack_docs/search.yaml +32 -0
  259. api_everything/recipes/wikidata/entity.yaml +22 -0
  260. api_everything/recipes/wikidata/search.yaml +24 -0
  261. api_everything/recipes/wikimedia_commons/search.yaml +25 -0
  262. api_everything/recipes/wikipedia/search.yaml +25 -0
  263. api_everything/recipes/wikipedia/summary.yaml +33 -0
  264. api_everything/recipes/wordpress_plugins/search.yaml +24 -0
  265. api_everything/recipes/wordpress_themes/search.yaml +24 -0
  266. api_everything/recipes/worldbank/indicator.yaml +17 -0
  267. api_everything/recipes/zenodo/records.yaml +24 -0
  268. api_everything/recipes/zippopotam/in.yaml +22 -0
  269. api_everything/recipes/zippopotam/lookup.yaml +29 -0
  270. api_everything/recipes/zoom_status/summary.yaml +17 -0
  271. api_everything/record.py +327 -0
  272. api_everything/record_session.py +364 -0
  273. api_everything/repair.py +717 -0
  274. api_everything/repair_ai.py +194 -0
  275. api_everything/runlog.py +61 -0
  276. api_everything/server.py +323 -0
  277. api_everything-0.5.0.dist-info/METADATA +363 -0
  278. api_everything-0.5.0.dist-info/RECORD +281 -0
  279. api_everything-0.5.0.dist-info/WHEEL +4 -0
  280. api_everything-0.5.0.dist-info/entry_points.txt +2 -0
  281. api_everything-0.5.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,327 @@
1
+ """Record mode, the pure part: turn what a browsing session saw into a recipe.
2
+
3
+ `api-everything record <url>` opens a visible browser, collects the JSON responses the page
4
+ receives, lets you pick one, and writes an ordinary recipe for it. This module holds every
5
+ step that needs no browser, so it is deterministic and easy to test: the same page URL and the
6
+ same picked response always produce the same recipe text.
7
+
8
+ Privacy rule: only structure is ever shown or stored (paths, key names, types, counts). Response
9
+ values, headers and cookies never reach the screen, the recipe or a log. The one exception is
10
+ the sample values of the parameters you chose, which come from the page URL you typed yourself.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import ipaddress
16
+ import json
17
+ import re
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any
21
+ from urllib.parse import parse_qsl, urlsplit
22
+
23
+ import yaml
24
+ from pydantic import ValidationError
25
+
26
+ from api_everything.recipe import Recipe
27
+
28
+ HEADER = (
29
+ "# Recorded with `api-everything record`. No response values, headers or cookies are stored:\n"
30
+ "# only key names and types. Key names and URL paths can themselves contain data, and\n"
31
+ "# `check.params` holds the sample values from the page URL you recorded on, so read this\n"
32
+ "# file before sharing it.\n"
33
+ )
34
+ SIGNATURE_DEPTH = 3
35
+ SHAPE_KEYS_SHOWN = 8
36
+ CHECK_KEYS_USED = 6
37
+
38
+ _UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
39
+ _ID_SEGMENT = re.compile(r"^(?:\d+|[0-9a-fA-F]{16,})$")
40
+ _NAME_CHARS = re.compile(r"[^a-z0-9_-]+")
41
+ _PARAM_NAME = re.compile(r"^[a-z][a-z0-9_]*$")
42
+ # A key like `user_8841` or a long hex id is data, not structure: it would also make a check
43
+ # that passes today and fails tomorrow.
44
+ _ID_LIKE_KEY = re.compile(r"\d{3,}|[0-9a-fA-F]{16,}")
45
+ _PUBLIC_SECOND_LEVEL = {"co", "com", "org", "net", "gov", "ac", "edu"}
46
+
47
+
48
+ class RecordError(Exception):
49
+ """Recording cannot continue. The message says what to do."""
50
+
51
+
52
+ def signature(data: Any, depth: int = SIGNATURE_DEPTH) -> Any:
53
+ """The nested key-and-type structure of a response, `depth` levels down. No values.
54
+
55
+ A list is described by its first element (or empty); lengths are left out because they vary
56
+ from one load to the next. Two responses with the same signature have the same shape.
57
+ """
58
+ if isinstance(data, dict):
59
+ if depth <= 0:
60
+ return "object"
61
+ return {key: signature(value, depth - 1) for key, value in sorted(data.items())}
62
+ if isinstance(data, list):
63
+ if not data:
64
+ return []
65
+ return [signature(data[0], depth - 1)] if depth > 0 else "list"
66
+ return type_name(data)
67
+
68
+
69
+ def signatures_match(a: Any, b: Any) -> bool:
70
+ """Same structure. A `null` on either side matches anything: optional fields come and go."""
71
+ if a == "null" or b == "null":
72
+ return True
73
+ if isinstance(a, dict) and isinstance(b, dict):
74
+ return a.keys() == b.keys() and all(signatures_match(a[k], b[k]) for k in a)
75
+ if isinstance(a, list) and isinstance(b, list):
76
+ return not a or not b or signatures_match(a[0], b[0])
77
+ return a == b
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class Candidate:
82
+ """One JSON response the page received. `data` stays in memory only; it is never written."""
83
+
84
+ url: str
85
+ status: int
86
+ size: int
87
+ shape: str
88
+ data: Any
89
+ seen: int = 1 # how many responses had this path and structure (the largest is kept)
90
+
91
+ @property
92
+ def structure(self) -> Any:
93
+ return signature(self.data)
94
+
95
+
96
+ # --- describing a response, without its values ---------------------------------------------
97
+
98
+
99
+ def type_name(value: Any) -> str:
100
+ if value is None:
101
+ return "null"
102
+ if isinstance(value, bool):
103
+ return "boolean"
104
+ if isinstance(value, int):
105
+ return "integer"
106
+ if isinstance(value, float):
107
+ return "number"
108
+ if isinstance(value, str):
109
+ return "string"
110
+ if isinstance(value, list):
111
+ return "list"
112
+ return "object"
113
+
114
+
115
+ def describe_shape(data: Any) -> str:
116
+ """Key names, types and list lengths of a response. Never any of its values."""
117
+ if isinstance(data, list):
118
+ return f"list({len(data)})"
119
+ if not isinstance(data, dict):
120
+ return type_name(data)
121
+ parts = []
122
+ for key in list(data)[:SHAPE_KEYS_SHOWN]:
123
+ value = data[key]
124
+ kind = f"list({len(value)})" if isinstance(value, list) else type_name(value)
125
+ parts.append(f"{key}: {kind}")
126
+ extra = len(data) - SHAPE_KEYS_SHOWN
127
+ if extra > 0:
128
+ parts.append(f"+{extra} more")
129
+ return "{" + ", ".join(parts) + "}"
130
+
131
+
132
+ # --- URLs ------------------------------------------------------------------------------------
133
+
134
+
135
+ def _general_segment(segment: str) -> bool:
136
+ return bool(_UUID.match(segment) or _ID_SEGMENT.match(segment))
137
+
138
+
139
+ def matcher_for(api_url: str) -> str:
140
+ """An anchored regex for the picked response's host and path.
141
+
142
+ Numeric, hex and UUID path segments become `[^/]+` so the same call with another id still
143
+ matches. The query string is not part of it: the pattern ends where the path ends.
144
+ """
145
+ parts = urlsplit(api_url)
146
+ segments = [
147
+ "[^/]+" if _general_segment(seg) else re.escape(seg) for seg in parts.path.split("/")
148
+ ]
149
+ host = parts.hostname or ""
150
+ origin = f"{host}:{parts.port}" if parts.port else host # the port is part of the URL
151
+ return f"{re.escape(origin)}{'/'.join(segments)}(\\?|$)"
152
+
153
+
154
+ def path_key(api_url: str) -> str:
155
+ """What makes two responses 'the same call': host and generalised path, no query."""
156
+ return matcher_for(api_url)
157
+
158
+
159
+ def _is_ip(host: str) -> bool:
160
+ try:
161
+ ipaddress.ip_address(host)
162
+ except ValueError:
163
+ return False
164
+ return True
165
+
166
+
167
+ def _slug(text: str) -> str:
168
+ return _NAME_CHARS.sub("-", text.lower()).strip("-") or "data"
169
+
170
+
171
+ def name_for(page_url: str, api_url: str) -> str:
172
+ """A `site.endpoint` name: the page's main domain label and the call's last path piece."""
173
+ host = (urlsplit(page_url).hostname or "site").lower()
174
+ labels = [label for label in host.split(".") if label != "www"]
175
+ if _is_ip(host):
176
+ site = "local" # an address has no site name worth using
177
+ else:
178
+ # `shop.example.co.uk`: the site is `example`, not `co`
179
+ if len(labels) >= 3 and len(labels[-1]) == 2 and labels[-2] in _PUBLIC_SECOND_LEVEL:
180
+ labels = labels[:-1]
181
+ site = labels[-2] if len(labels) >= 2 else labels[0]
182
+ pieces = [p for p in urlsplit(api_url).path.split("/") if p and not _general_segment(p)]
183
+ endpoint = pieces[-1].rsplit(".", 1)[0] if pieces else "data"
184
+ return f"{_slug(site)}.{_slug(endpoint)}"
185
+
186
+
187
+ def template_url(page_url: str, param_keys: list[str]) -> tuple[str, dict[str, str]]:
188
+ """Replace the chosen query values of the page URL with `{{key}}`; return sample values."""
189
+ parts = urlsplit(page_url)
190
+ if parts.scheme not in ("http", "https") or not parts.hostname:
191
+ raise RecordError(f"the page URL must start with http:// or https://, got {page_url!r}")
192
+ present = dict(parse_qsl(parts.query, keep_blank_values=True))
193
+ samples: dict[str, str] = {}
194
+ for key in param_keys:
195
+ if not _PARAM_NAME.match(key):
196
+ raise RecordError(
197
+ f"parameter name {key!r} must be lowercase letters, digits and '_', "
198
+ "starting with a letter"
199
+ )
200
+ if key not in present:
201
+ raise RecordError(
202
+ f"the page URL has no query value named {key!r}; "
203
+ f"it has: {', '.join(present) or 'none'}"
204
+ )
205
+ samples[key] = present[key]
206
+ if not param_keys:
207
+ return page_url, samples
208
+ pieces = []
209
+ for pair in parts.query.split("&"):
210
+ name = pair.split("=", 1)[0]
211
+ pieces.append(f"{name}={{{{{name}}}}}" if name in samples else pair)
212
+ return parts._replace(query="&".join(pieces)).geturl(), samples
213
+
214
+
215
+ # --- choosing and building -------------------------------------------------------------------
216
+
217
+
218
+ def dedupe(found: list[Candidate]) -> list[Candidate]:
219
+ """One candidate per call: the same path AND structure keeps its largest response.
220
+
221
+ Responses on one path with different structures stay separate rows, because a recipe's
222
+ matcher cannot tell them apart by URL and the person must see that they exist.
223
+ """
224
+ best: dict[str, Candidate] = {}
225
+ order: list[str] = []
226
+ for candidate in found:
227
+ key = f"{path_key(candidate.url)}|{json.dumps(candidate.structure, sort_keys=True)}"
228
+ if key not in best:
229
+ order.append(key)
230
+ best[key] = candidate
231
+ else:
232
+ kept = best[key]
233
+ winner = candidate if candidate.size > kept.size else kept
234
+ best[key] = Candidate(
235
+ winner.url, winner.status, winner.size, winner.shape, winner.data, kept.seen + 1
236
+ )
237
+ return [best[key] for key in order]
238
+
239
+
240
+ def pick_by_text(candidates: list[Candidate], text: str) -> Candidate:
241
+ hits = [c for c in candidates if text in c.url]
242
+ if not hits:
243
+ raise RecordError(f"no recorded response has {text!r} in its URL")
244
+ if len(hits) > 1:
245
+ raise RecordError(f"{len(hits)} recorded responses have {text!r} in their URL; be specific")
246
+ return hits[0]
247
+
248
+
249
+ def expectations_for(data: Any) -> list[dict[str, Any]]:
250
+ """Structure-only assertions: which keys exist and of what type, never their values."""
251
+ if isinstance(data, list):
252
+ return [{"path": "$", "type": "list", **({"non_empty": True} if data else {})}]
253
+ if not isinstance(data, dict):
254
+ return []
255
+ out: list[dict[str, Any]] = []
256
+ for key in sorted(data)[:CHECK_KEYS_USED]:
257
+ value = data[key]
258
+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key) or _ID_LIKE_KEY.search(key):
259
+ continue # needs JSONPath quoting, or is data (an id): leave it out
260
+ entry: dict[str, Any] = {"path": f"$.{key}"}
261
+ kind = type_name(value)
262
+ if kind != "null":
263
+ entry["type"] = kind
264
+ if isinstance(value, list) and value:
265
+ entry["non_empty"] = True
266
+ out.append(entry)
267
+ return out
268
+
269
+
270
+ def build_recipe(
271
+ page_url: str,
272
+ candidate: Candidate,
273
+ *,
274
+ name: str | None = None,
275
+ param_keys: list[str] | None = None,
276
+ profile: str | None = None,
277
+ experimental_note: str | None = None,
278
+ ) -> tuple[Recipe, dict[str, Any]]:
279
+ """The recipe for one picked response, validated, plus the ordered dict it was made from."""
280
+ keys = param_keys or []
281
+ url, samples = template_url(page_url, keys)
282
+ expect = expectations_for(candidate.data)
283
+ if not expect:
284
+ raise RecordError("that response has no named keys or items to check; pick another")
285
+ params: dict[str, Any] = {}
286
+ check_params: dict[str, Any] = {}
287
+ for key, sample in samples.items():
288
+ integer = sample.lstrip("-").isdigit()
289
+ params[key] = {"type": "integer" if integer else "string"}
290
+ check_params[key] = int(sample) if integer else sample
291
+ recipe_name = name or name_for(page_url, candidate.url)
292
+ matcher = matcher_for(candidate.url)
293
+ if re.search(matcher, candidate.url) is None: # cannot happen; guards a future edit
294
+ raise RecordError("internal error: the generated matcher does not match its own URL")
295
+
296
+ doc: dict[str, Any] = {"schema_version": 1, "name": recipe_name}
297
+ doc["description"] = f"Recorded from {urlsplit(page_url).hostname}."
298
+ if experimental_note:
299
+ doc["status"] = "experimental"
300
+ doc["session"] = f"profile:{profile}" if profile else "none"
301
+ if params:
302
+ doc["params"] = params
303
+ doc["url"] = url
304
+ doc["matcher"] = {"url_regex": matcher}
305
+ doc["check"] = {**({"params": check_params} if check_params else {}), "expect": expect}
306
+ try:
307
+ return Recipe.model_validate(doc), doc
308
+ except ValidationError as exc:
309
+ problems = "; ".join(
310
+ f"{'.'.join(str(p) for p in e['loc'])}: {e['msg']}" for e in exc.errors()
311
+ )
312
+ raise RecordError(f"the generated recipe is not valid ({problems})") from exc
313
+
314
+
315
+ def render_yaml(doc: dict[str, Any], *, note: str | None = None) -> str:
316
+ """Deterministic text: fixed key order, no timestamps, so a re-record diffs cleanly."""
317
+ head = HEADER
318
+ if note:
319
+ one_line = " ".join(note.split())
320
+ head += f"# NOT VERIFIED: {one_line}\n"
321
+ body = yaml.safe_dump(doc, sort_keys=False, allow_unicode=True, width=100)
322
+ return head + body
323
+
324
+
325
+ def recipe_path(recipes_dir: Path, recipe_name: str) -> Path:
326
+ site, endpoint = recipe_name.split(".", 1)
327
+ return recipes_dir / site / f"{endpoint}.yaml"
@@ -0,0 +1,364 @@
1
+ """Record mode, the browser part: capture, choose, verify by replay, write.
2
+
3
+ The flow of `api-everything record <url>`:
4
+ 1. open a visible browser on the page (a fresh one, or a new tab in a Chrome you started for
5
+ an attached profile) and collect the JSON responses it receives;
6
+ 2. you browse, then say you are done;
7
+ 3. list the responses (structure only), you pick one and the parameters;
8
+ 4. build the recipe and replay it once in a fresh browser to prove it reproduces the capture;
9
+ 5. write it only if the replay passed (or `--keep-unverified`, as an experimental recipe).
10
+
11
+ The pure steps live in `record.py`. Everything that talks to a person or a browser is injectable
12
+ so it can be tested without either.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import contextlib
19
+ import json
20
+ import threading
21
+ from collections.abc import Awaitable, Callable
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from urllib.parse import parse_qsl, urlsplit
25
+
26
+ from playwright.async_api import Page, Response
27
+
28
+ from api_everything.check import check_recipes
29
+ from api_everything.config import Config, ConfigError
30
+ from api_everything.driver import (
31
+ BrowserDriver,
32
+ BrowserNotInstalled,
33
+ BrowserNotRunning,
34
+ ChromeAttachDriver,
35
+ shared_driver_class,
36
+ )
37
+ from api_everything.engine import run_recipe
38
+ from api_everything.record import (
39
+ Candidate,
40
+ RecordError,
41
+ build_recipe,
42
+ dedupe,
43
+ describe_shape,
44
+ pick_by_text,
45
+ recipe_path,
46
+ render_yaml,
47
+ signature,
48
+ signatures_match,
49
+ )
50
+
51
+ # A replay that has not produced its response by now is not going to (a person is waiting).
52
+ REPLAY_DEADLINE_SECONDS = 15.0
53
+
54
+ Ask = Callable[[str], Awaitable[str]]
55
+
56
+
57
+ async def ask_stdin(prompt: str) -> str:
58
+ """Prompt on the terminal without a thread that can outlive Ctrl-C.
59
+
60
+ `input()` in the default executor would keep the program alive until Enter after an
61
+ interrupt. A daemon thread is abandoned when the program exits.
62
+ """
63
+ loop = asyncio.get_running_loop()
64
+ future: asyncio.Future[str] = loop.create_future()
65
+
66
+ def deliver(value: str | None, error: BaseException | None) -> None:
67
+ if future.done():
68
+ return
69
+ if error is not None:
70
+ future.set_exception(error)
71
+ else:
72
+ future.set_result(value or "")
73
+
74
+ def read() -> None:
75
+ try:
76
+ line = input(prompt)
77
+ except BaseException as exc: # EOF or an interrupt: pass it to the waiting task
78
+ loop.call_soon_threadsafe(deliver, None, exc)
79
+ else:
80
+ loop.call_soon_threadsafe(deliver, line, None)
81
+
82
+ threading.Thread(target=read, daemon=True).start()
83
+ return await future
84
+ Say = Callable[[str], None]
85
+ Browse = Callable[[Page], Awaitable[None]]
86
+
87
+
88
+ class _Reject(ValueError):
89
+ pass
90
+
91
+
92
+ def _reject_constant(name: str) -> None:
93
+ raise _Reject(f"{name} is not valid JSON")
94
+
95
+
96
+ class Collector:
97
+ """Gathers the page's successful JSON responses. Bodies are read in the background."""
98
+
99
+ def __init__(self, max_body_bytes: int) -> None:
100
+ self._max = max_body_bytes
101
+ self.found: list[Candidate] = []
102
+ self._tasks: set[asyncio.Task[None]] = set()
103
+
104
+ def on_response(self, response: Response) -> None:
105
+ task = asyncio.ensure_future(self._read(response))
106
+ self._tasks.add(task)
107
+ task.add_done_callback(self._tasks.discard)
108
+
109
+ async def _read(self, response: Response) -> None:
110
+ if not 200 <= response.status < 300:
111
+ return
112
+ path = urlsplit(response.url).path
113
+ kind = response.headers.get("content-type", "")
114
+ if "json" not in kind.lower() and not path.endswith(".json"):
115
+ return
116
+ try:
117
+ body = await response.body()
118
+ if len(body) > self._max:
119
+ return
120
+ data = json.loads(body, parse_constant=_reject_constant)
121
+ except Exception: # a redirect, a closed page, a body that is not JSON: not a candidate
122
+ return
123
+ self.found.append(
124
+ Candidate(response.url, response.status, len(body), describe_shape(data), data)
125
+ )
126
+
127
+ async def settle(self) -> None:
128
+ if self._tasks:
129
+ await asyncio.gather(*self._tasks, return_exceptions=True)
130
+
131
+
132
+ @dataclass
133
+ class RecordOptions:
134
+ url: str
135
+ recipes_dir: Path | None
136
+ name: str | None = None
137
+ params: list[str] = field(default_factory=list)
138
+ profile: str | None = None
139
+ pick: int | None = None
140
+ match: str | None = None
141
+ seconds: float | None = None
142
+ keep_unverified: bool = False
143
+ force: bool = False
144
+
145
+
146
+ @dataclass
147
+ class RecordResult:
148
+ code: int # 0 written, 1 replay failed and nothing written, 2 usage, 3 browser problem
149
+ path: Path | None = None
150
+
151
+
152
+ def _candidate_lines(candidates: list[Candidate]) -> list[str]:
153
+ lines = []
154
+ for number, c in enumerate(candidates, start=1):
155
+ parts = urlsplit(c.url)
156
+ again = f" (x{c.seen})" if c.seen > 1 else ""
157
+ lines.append(
158
+ f" {number}. {c.status} {c.size:>7} B {parts.hostname}{parts.path}{again}\n"
159
+ f" {c.shape}"
160
+ )
161
+ return lines
162
+
163
+
164
+ async def _choose(
165
+ candidates: list[Candidate], options: RecordOptions, ask: Ask, say: Say
166
+ ) -> Candidate:
167
+ if options.match is not None:
168
+ return pick_by_text(candidates, options.match)
169
+ if options.pick is not None:
170
+ if not 1 <= options.pick <= len(candidates):
171
+ raise RecordError(f"--pick must be between 1 and {len(candidates)}")
172
+ return candidates[options.pick - 1]
173
+ for _ in range(3):
174
+ prompt = f"Which response is the data you want? (1-{len(candidates)}): "
175
+ answer = (await ask(prompt)).strip()
176
+ if answer.isdigit() and 1 <= int(answer) <= len(candidates):
177
+ return candidates[int(answer) - 1]
178
+ say("Please type one of the numbers above.")
179
+ raise RecordError("no response was chosen")
180
+
181
+
182
+ async def _choose_params(options: RecordOptions, ask: Ask) -> list[str]:
183
+ if options.params:
184
+ return options.params
185
+ keys = [k for k, _ in parse_qsl(urlsplit(options.url).query, keep_blank_values=True)]
186
+ if not keys or options.pick is not None or options.match is not None:
187
+ return [] # unattended runs only take parameters given as flags
188
+ answer = await ask(
189
+ f"Which parts of the page URL should callers be able to change? "
190
+ f"({', '.join(keys)}; Enter for none): "
191
+ )
192
+ return [k.strip() for k in answer.split(",") if k.strip()]
193
+
194
+
195
+ def _drivers(
196
+ config: Config, options: RecordOptions
197
+ ) -> tuple[Callable[[], BrowserDriver], Callable[[], BrowserDriver]]:
198
+ """(for watching: visible, for the replay check: headless), both on the right profile."""
199
+ if options.profile:
200
+ try:
201
+ attach = config.profile_attach(options.profile)
202
+ except ConfigError as exc:
203
+ raise RecordError(str(exc)) from exc
204
+ if attach is None:
205
+ raise RecordError(
206
+ f"profile {options.profile!r} is not set up to attach, and record needs the "
207
+ f"Chrome you started with `api-everything chrome {options.profile}`. Add "
208
+ f"`attach: http://127.0.0.1:9222` to it in your config file."
209
+ )
210
+ name, url = options.profile, attach.url
211
+
212
+ def attached() -> BrowserDriver:
213
+ return ChromeAttachDriver(url, name)
214
+
215
+ return attached, attached
216
+ cls = shared_driver_class(config.browser)
217
+ return (lambda: cls(headless=False)), (lambda: cls(headless=True))
218
+
219
+
220
+ def _default_browse(options: RecordOptions, ask: Ask, say: Say) -> Browse:
221
+ async def browse(page: Page) -> None:
222
+ with contextlib.suppress(Exception):
223
+ await page.bring_to_front()
224
+ if options.seconds is not None:
225
+ say(f"Recording for {options.seconds:g}s ...")
226
+ await asyncio.sleep(options.seconds)
227
+ return
228
+ await ask(
229
+ "Browse the page until the data you want has loaded, then come back here and "
230
+ "press Enter: "
231
+ )
232
+
233
+ return browse
234
+
235
+
236
+ async def run_record(
237
+ config: Config,
238
+ options: RecordOptions,
239
+ *,
240
+ ask: Ask,
241
+ say: Say,
242
+ browse: Browse | None = None,
243
+ watch_driver: Callable[[], BrowserDriver] | None = None,
244
+ verify_driver: Callable[[], BrowserDriver] | None = None,
245
+ ) -> RecordResult:
246
+ try:
247
+ return await _run(config, options, ask, say, browse, watch_driver, verify_driver)
248
+ except RecordError as exc:
249
+ say(f"error: {exc}")
250
+ return RecordResult(2)
251
+ except (BrowserNotInstalled, BrowserNotRunning) as exc:
252
+ say(f"error: {exc}")
253
+ return RecordResult(3)
254
+
255
+
256
+ async def _run(
257
+ config: Config,
258
+ options: RecordOptions,
259
+ ask: Ask,
260
+ say: Say,
261
+ browse: Browse | None,
262
+ watch_driver: Callable[[], BrowserDriver] | None,
263
+ verify_driver: Callable[[], BrowserDriver] | None,
264
+ ) -> RecordResult:
265
+ if options.recipes_dir is None:
266
+ raise RecordError(
267
+ "no recipes folder: set `recipes_dir` in your config file or pass --recipes-dir"
268
+ )
269
+ watching, replaying = _drivers(config, options)
270
+ watching = watch_driver or watching
271
+ replaying = verify_driver or replaying
272
+ browse = browse or _default_browse(options, ask, say)
273
+
274
+ collector = Collector(config.limits.max_body_bytes)
275
+ async with watching() as driver:
276
+ lease = await driver.open_lease()
277
+ try:
278
+ lease.page.on("response", collector.on_response)
279
+ with contextlib.suppress(Exception): # a slow or odd page may still have data
280
+ await lease.page.goto(options.url, wait_until="commit")
281
+ await browse(lease.page)
282
+ await collector.settle()
283
+ finally:
284
+ await driver.close_lease(lease)
285
+
286
+ candidates = dedupe(collector.found)
287
+ if not candidates:
288
+ raise RecordError(
289
+ "no JSON responses were seen. The page may need a click or typing first (record "
290
+ "does not capture those yet), or it may not load data as JSON."
291
+ )
292
+ say("\nJSON responses the page received (structure only, no values):")
293
+ for line in _candidate_lines(candidates):
294
+ say(line)
295
+ chosen = await _choose(candidates, options, ask, say)
296
+ params = await _choose_params(options, ask)
297
+
298
+ recipe, doc = build_recipe(
299
+ options.url, chosen, name=options.name, param_keys=params, profile=options.profile
300
+ )
301
+ target = recipe_path(options.recipes_dir, recipe.name)
302
+ if target.exists() and not options.force:
303
+ raise RecordError(f"{target} already exists; pass --force to replace it")
304
+
305
+ say(f"\nChecking that {recipe.name} reproduces the capture in a fresh browser ...")
306
+ failure = await _replay(config, recipe, chosen, replaying)
307
+ note = None
308
+ if failure is not None:
309
+ say(f"The replay did not reproduce the capture: {failure}")
310
+ if not options.keep_unverified:
311
+ say(
312
+ "Nothing was written. Pages that need a click or typing before the data loads "
313
+ "need hand-written `actions` for now; add --keep-unverified to save this "
314
+ "recipe as experimental anyway."
315
+ )
316
+ return RecordResult(1)
317
+ note = failure
318
+ _, doc = build_recipe(
319
+ options.url, chosen, name=options.name, param_keys=params,
320
+ profile=options.profile, experimental_note=failure,
321
+ )
322
+
323
+ target.parent.mkdir(parents=True, exist_ok=True)
324
+ target.write_text(render_yaml(doc, note=note))
325
+ label = "experimental (not verified)" if note else "verified"
326
+ say(f"\nWrote {target} ({label}).")
327
+ say(f"Next: `api-everything validate`, then `api-everything check {recipe.name}`.")
328
+ return RecordResult(0, target)
329
+
330
+
331
+ async def _replay(
332
+ config: Config, recipe, chosen: Candidate, replaying: Callable[[], BrowserDriver]
333
+ ) -> str | None:
334
+ """Run the recipe once with its own check values. None means it reproduced the capture.
335
+
336
+ Passing the recipe's own check is not enough: the matcher is made from the URL path, so a
337
+ page that calls one path several times would be captured as its FIRST response, which can be
338
+ a different one from the response you picked. So the replayed data must also have the same
339
+ structure as the picked response.
340
+ """
341
+ captured: dict[str, object] = {}
342
+ async with replaying() as driver:
343
+
344
+ async def run(candidate):
345
+ result = await run_recipe(
346
+ driver,
347
+ candidate,
348
+ candidate.check.params,
349
+ limits=config.limits,
350
+ deadline_seconds=REPLAY_DEADLINE_SECONDS,
351
+ allow_eval=False,
352
+ )
353
+ captured["data"] = result.data
354
+ return result
355
+
356
+ (result,) = await check_recipes([recipe], run)
357
+ if not result.ok:
358
+ return result.detail
359
+ if not signatures_match(signature(captured["data"]), chosen.structure):
360
+ return (
361
+ "the replay captured a different response from the one you picked. A recipe matches "
362
+ "by URL path, and this page makes several calls to that path with different results"
363
+ )
364
+ return None