1use std::collections::HashMap;
12
13const CAPABILITIES_PAGE: &str = "https://bynk-lang.org/reference/bynk-capabilities/";
15
16type Entry = (
22 &'static str,
23 &'static str,
24 &'static str,
25 &'static [&'static str],
26);
27pub const FIRST_PARTY_DOCS: &[Entry] = &[
28 ("bynk", "Clock", "the-portable-surface--bynk", &["now"]),
29 (
30 "bynk",
31 "Random",
32 "the-portable-surface--bynk",
33 &["uuid", "int", "bytes"],
34 ),
35 (
36 "bynk",
37 "Logger",
38 "the-portable-surface--bynk",
39 &["info", "error", "warn", "debug", "log"],
40 ),
41 (
42 "bynk",
43 "Fetch",
44 "the-portable-surface--bynk",
45 &[
46 "send",
47 "sendWith",
48 "receiveBytes",
49 "sendBytes",
50 "receiveStream",
51 "sendStream",
52 ],
53 ),
54 ("bynk", "Secrets", "the-portable-surface--bynk", &["get"]),
55 ("bynk", "Locale", "the-portable-surface--bynk", &["current"]),
56 (
57 "bynk",
58 "Idempotency",
59 "the-idempotency-capability",
60 &["dedup", "remember", "claim"],
61 ),
62 ("bynk", "Events", "the-events-capability", &["emit"]),
63 (
64 "bynk.cloudflare",
65 "Kv",
66 "the-cloudflare-surface--bynkcloudflare",
67 &[
68 "get", "put", "putTtl", "delete", "list", "getWith", "putWith", "getBytes", "putBytes",
69 "listPage",
70 ],
71 ),
72 (
73 "bynk.cloudflare",
74 "Service",
75 "calling-a-worker-outside-the-project-service",
76 &["send"],
77 ),
78 (
79 "bynk.cloudflare",
80 "R2",
81 "object-storage-r2",
82 &["get", "head", "put", "putWith", "delete", "list"],
83 ),
84 (
85 "bynk.cloudflare",
86 "RateLimit",
87 "rate-limiting-ratelimit",
88 &["allow"],
89 ),
90 (
91 "bynk.cloudflare",
92 "Queue",
93 "sending-to-a-queue-queue",
94 &[
95 "send",
96 "sendWith",
97 "sendBatch",
98 "sendValue",
99 "sendValueWith",
100 "sendValueBatch",
101 ],
102 ),
103 (
104 "bynk.cloudflare",
105 "Analytics",
106 "writing-events-analytics",
107 &["write", "dataset"],
108 ),
109 (
110 "bynk.cloudflare",
111 "D1",
112 "sql-databases-d1",
113 &["all", "first", "run", "batch"],
114 ),
115 (
116 "bynk.cloudflare",
117 "EdgeCache",
118 "edge-caching-edgecache",
119 &["purge"],
120 ),
121 (
122 "bynk.cloudflare",
123 "Version",
124 "the-running-version-version",
125 &["current"],
126 ),
127 ("bynk.cloudflare", "Ai", "workers-ai-ai", &["run"]),
128 ("bynk.cloudflare", "Images", "images-images", &["transform"]),
129 (
130 "bynk.cloudflare",
131 "StoredSecret",
132 "account-secrets-storedsecret",
133 &["get"],
134 ),
135 (
136 "bynk.cloudflare",
137 "Email",
138 "outbound-email-email",
139 &["send"],
140 ),
141 (
142 "bynk.cloudflare",
143 "Postgres",
144 "postgres-databases-postgres",
145 &["all", "first", "run", "transaction"],
146 ),
147 (
148 "bynk.cloudflare",
149 "MySql",
150 "mysql-databases-mysql",
151 &["all", "first", "run", "transaction"],
152 ),
153 (
154 "bynk.cloudflare",
155 "Vectorize",
156 "vector-indexes-vectorize",
157 &[
158 "upsert",
159 "insert",
160 "upsertValue",
161 "query",
162 "getByIds",
163 "deleteByIds",
164 "describe",
165 ],
166 ),
167 (
168 "bynk.cloudflare",
169 "Container",
170 "containers-container",
171 &["send", "receiveBytes", "sendBytes"],
172 ),
173 (
174 "bynk.cloudflare",
175 "AiSearch",
176 "ai-search-aisearch",
177 &["search", "answer"],
178 ),
179 (
180 "bynk.cloudflare",
181 "MtlsCertificate",
182 "mutual-tls-mtlscertificate",
183 &["send"],
184 ),
185 (
186 "bynk.cloudflare",
187 "AnalyticsSql",
188 "reading-events-analyticssql",
189 &["query"],
190 ),
191];
192
193pub fn resolve_first_party_doc_link(
197 doc_scope: &HashMap<String, Vec<String>>,
198 owner_unit: &str,
199 name: &str,
200) -> Option<String> {
201 let mut parts = name.split('.');
202 let capability = parts.next()?;
203 let op = parts.next();
204 if parts.next().is_some() {
205 return None;
206 }
207 let scope = doc_scope.get(owner_unit)?;
208 FIRST_PARTY_DOCS
209 .iter()
210 .find(|(unit, cap, _, ops)| {
211 *cap == capability
212 && op.is_none_or(|o| ops.contains(&o))
213 && scope.iter().any(|u| u == unit)
214 })
215 .map(|(_, _, anchor, _)| format!("{CAPABILITIES_PAGE}#{anchor}"))
216}
217
218pub fn in_scope_names(doc_scope: &HashMap<String, Vec<String>>, owner_unit: &str) -> Vec<String> {
222 let Some(scope) = doc_scope.get(owner_unit) else {
223 return Vec::new();
224 };
225 FIRST_PARTY_DOCS
226 .iter()
227 .filter(|(unit, ..)| scope.iter().any(|u| u == unit))
228 .flat_map(|(_, cap, _, ops)| {
229 std::iter::once((*cap).to_string()).chain(ops.iter().map(move |o| format!("{cap}.{o}")))
230 })
231 .collect()
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237
238 fn slug(heading: &str) -> String {
240 heading
241 .trim()
242 .to_lowercase()
243 .chars()
244 .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
245 .map(|c| if c == ' ' { '-' } else { c })
246 .collect()
247 }
248
249 #[test]
250 fn every_mapped_anchor_and_operation_exists_in_the_book_source() {
251 let site = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
252 .parent()
253 .unwrap()
254 .join("site");
255 if !site.exists() {
256 return; }
258 let text = std::fs::read_to_string(
259 site.join("src/content/docs/reference/bynk-capabilities.md"),
260 )
261 .expect("the first-party capabilities page moved: update CAPABILITIES_PAGE and this test");
262 let mut in_fence = false;
263 let mut anchors = Vec::new();
264 for l in text.lines() {
265 if l.trim_start().starts_with("```") {
266 in_fence = !in_fence;
267 } else if !in_fence && l.starts_with('#') {
268 anchors.push(slug(l.trim_start_matches('#')));
269 }
270 }
271 for (_, cap, anchor, ops) in FIRST_PARTY_DOCS {
272 assert!(anchors.iter().any(|a| a == anchor), "{cap}: no `#{anchor}`");
273 for op in *ops {
274 assert!(
275 text.contains(&format!("{op}(")) || text.contains(&format!("{op}[")),
276 "{cap}.{op}: not in the Book"
277 );
278 }
279 }
280 }
281
282 fn scope(units: &[&str]) -> HashMap<String, Vec<String>> {
283 HashMap::from([(
284 "ratelimit".to_string(),
285 units.iter().map(|u| u.to_string()).collect(),
286 )])
287 }
288
289 #[test]
290 fn op_links_to_its_capability_when_the_unit_is_in_scope() {
291 let url =
292 resolve_first_party_doc_link(&scope(&["ratelimit", "bynk"]), "ratelimit", "Clock.now");
293 assert_eq!(
294 url.as_deref(),
295 Some("https://bynk-lang.org/reference/bynk-capabilities/#the-portable-surface--bynk")
296 );
297 }
298
299 #[test]
300 fn out_of_scope_or_unknown_names_do_not_link() {
301 let s = scope(&["ratelimit"]);
302 assert!(resolve_first_party_doc_link(&s, "ratelimit", "Clock").is_none());
303 let s = scope(&["ratelimit", "bynk"]);
304 assert!(resolve_first_party_doc_link(&s, "ratelimit", "Kv").is_none());
305 assert!(resolve_first_party_doc_link(&s, "ratelimit", "Nope").is_none());
306 assert!(resolve_first_party_doc_link(&s, "ratelimit", "Clock.nwo").is_none());
308 assert!(resolve_first_party_doc_link(&s, "ratelimit", "Kv.a.b").is_none());
309 }
310}