1use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18
19use crate::discovery::read_source;
20
21pub const FIRST_PARTY_REGISTRY: &str = "bynk";
23
24pub const FIRST_PARTY: Option<(&str, &str)> = None;
29
30pub const LOCK_FILE: &str = "bynk.lock";
32
33pub const LOCK_VERSION: i64 = 1;
35
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
38pub struct LockedPackage {
39 pub name: String,
41 pub version: Option<String>,
43 pub source: String,
45 pub checksum: Option<String>,
47 pub dependencies: Vec<String>,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
56pub struct LockedNpm {
57 pub package: String,
58 pub range: String,
59 pub required_by: Vec<String>,
61 pub approved: bool,
65 pub first_party: bool,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
75pub struct LockedRegistry {
76 pub name: String,
79 pub id: String,
81 pub key: String,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
87pub struct Lock {
88 pub packages: Vec<LockedPackage>,
89 pub registries: Vec<LockedRegistry>,
91 pub npm: Vec<LockedNpm>,
95}
96
97impl Lock {
98 pub fn git(&self, name: &str, url: &str, rev: &str) -> Option<(&LockedPackage, String)> {
100 self.packages.iter().find_map(|p| {
101 let (u, r, commit) = parse_git_source(&p.source)?;
102 (p.name == name && u == url && r == rev).then_some((p, commit))
103 })
104 }
105
106 pub fn render(&self) -> String {
109 let mut packages = self.packages.clone();
110 packages.sort();
111 let mut out =
112 String::from("# bynk.lock — written by `bynk`; commit it. Do not edit by hand.\n");
113 out.push_str(&format!("version = {LOCK_VERSION}\n"));
114 for p in &packages {
115 out.push_str("\n[[package]]\n");
116 out.push_str(&format!("name = {}\n", toml_string(&p.name)));
117 if let Some(v) = &p.version {
118 out.push_str(&format!("version = {}\n", toml_string(v)));
119 }
120 out.push_str(&format!("source = {}\n", toml_string(&p.source)));
121 if let Some(c) = &p.checksum {
122 out.push_str(&format!("checksum = {}\n", toml_string(c)));
123 }
124 let deps: Vec<String> = p.dependencies.iter().map(|d| toml_string(d)).collect();
125 out.push_str(&format!("dependencies = [{}]\n", deps.join(", ")));
126 }
127 let mut registries = self.registries.clone();
128 registries.sort();
129 for r in ®istries {
130 out.push_str("\n[[registry]]\n");
131 out.push_str(&format!("name = {}\n", toml_string(&r.name)));
132 out.push_str(&format!("id = {}\n", toml_string(&r.id)));
133 out.push_str(&format!("key = {}\n", toml_string(&r.key)));
134 }
135 let mut npm = self.npm.clone();
136 npm.sort();
137 for n in &npm {
138 out.push_str("\n[[npm]]\n");
139 out.push_str(&format!("package = {}\n", toml_string(&n.package)));
140 out.push_str(&format!("range = {}\n", toml_string(&n.range)));
141 let by: Vec<String> = n.required_by.iter().map(|d| toml_string(d)).collect();
142 out.push_str(&format!("required-by = [{}]\n", by.join(", ")));
143 if n.first_party {
144 out.push_str("first-party = true\n");
145 }
146 if n.approved {
147 out.push_str("approved = true\n");
148 }
149 }
150 out
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct LockError(pub String);
157
158impl std::fmt::Display for LockError {
159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160 f.write_str(&self.0)
161 }
162}
163
164pub fn parse_lock(text: &str) -> Result<Lock, LockError> {
166 let doc: toml::Table = text
167 .parse()
168 .map_err(|_| LockError("`bynk.lock` is not valid TOML".to_string()))?;
169 match doc.get("version").and_then(|v| v.as_integer()) {
170 Some(LOCK_VERSION) => {}
171 Some(v) => {
172 return Err(LockError(format!(
173 "`bynk.lock` is version {v}, which this toolchain doesn't read (it reads version {LOCK_VERSION})"
174 )));
175 }
176 None => {
177 return Err(LockError(
178 "`bynk.lock` has no `version` — it may be truncated; delete it and run `bynk fetch`"
179 .to_string(),
180 ));
181 }
182 }
183 let mut packages = Vec::new();
184 let entries = match doc.get("package") {
185 None => Vec::new(),
186 Some(toml::Value::Array(items)) => items.clone(),
187 Some(_) => {
188 return Err(LockError(
189 "`bynk.lock`'s `package` must be an array of tables".into(),
190 ));
191 }
192 };
193 for entry in entries {
194 let Some(t) = entry.as_table() else {
195 return Err(LockError(
196 "a `[[package]]` in `bynk.lock` isn't a table".into(),
197 ));
198 };
199 let text = |k: &str| t.get(k).and_then(|v| v.as_str()).map(str::to_owned);
200 let (Some(name), Some(source)) = (text("name"), text("source")) else {
201 return Err(LockError(
202 "a `[[package]]` in `bynk.lock` lacks `name` or `source`".into(),
203 ));
204 };
205 let dependencies = t
206 .get("dependencies")
207 .and_then(|v| v.as_array())
208 .map(|a| {
209 a.iter()
210 .filter_map(|d| d.as_str().map(str::to_owned))
211 .collect()
212 })
213 .unwrap_or_default();
214 packages.push(LockedPackage {
215 name,
216 version: text("version"),
217 source,
218 checksum: text("checksum"),
219 dependencies,
220 });
221 }
222 let mut npm = Vec::new();
223 let rows = match doc.get("npm") {
224 None => Vec::new(),
225 Some(toml::Value::Array(items)) => items.clone(),
226 Some(_) => {
227 return Err(LockError(
228 "`bynk.lock`'s `npm` must be an array of tables".into(),
229 ));
230 }
231 };
232 for row in rows {
233 let Some(t) = row.as_table() else {
234 return Err(LockError(
235 "an `[[npm]]` in `bynk.lock` isn't a table".into(),
236 ));
237 };
238 let text = |k: &str| t.get(k).and_then(|v| v.as_str()).map(str::to_owned);
239 let (Some(package), Some(range)) = (text("package"), text("range")) else {
240 return Err(LockError(
241 "an `[[npm]]` in `bynk.lock` lacks `package` or `range`".into(),
242 ));
243 };
244 let required_by = match t.get("required-by") {
245 None => Vec::new(),
246 Some(toml::Value::Array(items)) => items
247 .iter()
248 .map(|d| d.as_str().map(str::to_owned))
249 .collect::<Option<Vec<_>>>()
250 .ok_or_else(|| {
251 LockError(
252 "an `[[npm]]`'s `required-by` in `bynk.lock` must list strings".into(),
253 )
254 })?,
255 Some(_) => {
256 return Err(LockError(
257 "an `[[npm]]`'s `required-by` in `bynk.lock` must be a list".into(),
258 ));
259 }
260 };
261 let approved = match t.get("approved") {
262 None => false,
263 Some(toml::Value::Boolean(b)) => *b,
264 Some(_) => {
265 return Err(LockError(
266 "an `[[npm]]`'s `approved` in `bynk.lock` must be `true` or `false`".into(),
267 ));
268 }
269 };
270 let first_party = match t.get("first-party") {
271 None => false,
272 Some(toml::Value::Boolean(b)) => *b,
273 Some(_) => {
274 return Err(LockError(
275 "an `[[npm]]`'s `first-party` in `bynk.lock` must be `true` or `false`".into(),
276 ));
277 }
278 };
279 npm.push(LockedNpm {
280 package,
281 range,
282 required_by,
283 approved,
284 first_party,
285 });
286 }
287 let mut registries = Vec::new();
288 let rows = match doc.get("registry") {
289 None => Vec::new(),
290 Some(toml::Value::Array(items)) => items.clone(),
291 Some(_) => {
292 return Err(LockError(
293 "`bynk.lock`'s `registry` must be an array of tables".into(),
294 ));
295 }
296 };
297 for row in rows {
298 let t = row.as_table();
299 let text = |k: &str| {
300 t.and_then(|t| t.get(k))
301 .and_then(|v| v.as_str())
302 .map(str::to_owned)
303 };
304 let (Some(name), Some(id), Some(key)) = (text("name"), text("id"), text("key")) else {
305 return Err(LockError(
306 "a `[[registry]]` in `bynk.lock` needs `name`, `id` and `key`".into(),
307 ));
308 };
309 registries.push(LockedRegistry { name, id, key });
310 }
311 Ok(Lock {
312 packages,
313 registries,
314 npm,
315 })
316}
317
318pub fn registry_source(name: &str) -> String {
320 format!("registry+{name}")
321}
322
323pub fn parse_registry_source(source: &str) -> Option<&str> {
325 source.strip_prefix("registry+")
326}
327
328impl Lock {
329 pub fn package(&self, name: &str) -> Option<&LockedPackage> {
331 self.packages.iter().find(|p| p.name == name)
332 }
333
334 pub fn registry(&self, name: &str) -> Option<&LockedRegistry> {
336 self.registries.iter().find(|r| r.name == name)
337 }
338}
339
340pub fn adapter_requires(source: &str) -> Option<(String, Vec<(String, String)>)> {
345 let tokens = bynk_syntax::lexer::tokenize(source).ok()?;
346 let (unit, _errors) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, source);
347 let bynk_syntax::ast::SourceUnit::Adapter(a) = unit? else {
348 return None;
349 };
350 let binding = a.binding.as_ref()?;
351 Some((
352 a.name.joined(),
353 binding
354 .requires
355 .iter()
356 .map(|d| (d.package.clone(), d.range.clone()))
357 .collect(),
358 ))
359}
360
361pub fn lock_root(project_root: &Path) -> PathBuf {
365 let real = project_root
368 .canonicalize()
369 .unwrap_or_else(|_| project_root.to_path_buf());
370 crate::workspace::find_parent_workspace(&real).unwrap_or_else(|| project_root.to_path_buf())
371}
372
373pub fn read_lock(
376 lock_root: &Path,
377 overlay: &HashMap<PathBuf, String>,
378) -> Result<Option<Lock>, LockError> {
379 let path = lock_root.join(LOCK_FILE);
380 let text = match read_source(&path, overlay) {
381 Ok(text) => text,
382 Err(_) => match std::fs::read_to_string(&path) {
383 Ok(text) => text,
384 Err(_) => return Ok(None),
385 },
386 };
387 parse_lock(&text).map(Some)
388}
389
390pub fn git_source(url: &str, rev: &str, commit: &str) -> String {
392 format!("git+{url}?rev={rev}#{commit}")
393}
394
395pub fn parse_git_source(source: &str) -> Option<(String, String, String)> {
397 let rest = source.strip_prefix("git+")?;
398 let (rest, commit) = rest.rsplit_once('#')?;
399 let (url, rev) = rest.rsplit_once("?rev=")?;
400 Some((url.to_owned(), rev.to_owned(), commit.to_owned()))
401}
402
403pub fn path_source(dir: &Path) -> String {
405 let parts: Vec<String> = dir
406 .components()
407 .map(|c| c.as_os_str().to_string_lossy().into_owned())
408 .collect();
409 format!("path+{}", parts.join("/"))
410}
411
412pub fn bynk_home() -> Option<PathBuf> {
415 if let Some(home) = std::env::var_os("BYNK_HOME").filter(|v| !v.is_empty()) {
416 return Some(PathBuf::from(home));
417 }
418 if let Some(cache) = std::env::var_os("XDG_CACHE_HOME").filter(|v| !v.is_empty()) {
419 return Some(PathBuf::from(cache).join("bynk"));
420 }
421 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
422 Some(PathBuf::from(home).join(".cache").join("bynk"))
423}
424
425pub fn store_dir(home: &Path, checksum: &str) -> Option<PathBuf> {
428 let hex = checksum_hex(checksum)?;
429 Some(home.join("store").join("sha256").join(hex))
430}
431
432pub fn checksum_of(digest: &[u8; 32]) -> String {
434 format!("sha256-{}", base64_encode(digest))
435}
436
437pub fn checksum_hex(checksum: &str) -> Option<String> {
439 let bytes = base64_decode(checksum.strip_prefix("sha256-")?)?;
440 if bytes.len() != 32 {
441 return None;
442 }
443 Some(bytes.iter().map(|b| format!("{b:02x}")).collect())
444}
445
446const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
447
448pub fn base64_encode(bytes: &[u8]) -> String {
449 let mut out = String::new();
450 for chunk in bytes.chunks(3) {
451 let b = [
452 chunk[0],
453 *chunk.get(1).unwrap_or(&0),
454 *chunk.get(2).unwrap_or(&0),
455 ];
456 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
457 for i in 0..4 {
458 if i <= chunk.len() {
459 out.push(B64[((n >> (18 - 6 * i)) & 63) as usize] as char);
460 } else {
461 out.push('=');
462 }
463 }
464 }
465 out
466}
467
468pub fn base64_decode(text: &str) -> Option<Vec<u8>> {
469 let mut out = Vec::new();
470 let mut buf = 0u32;
471 let mut bits = 0;
472 for c in text.bytes().filter(|&c| c != b'=') {
473 let v = B64.iter().position(|&b| b == c)? as u32;
474 buf = (buf << 6) | v;
475 bits += 6;
476 if bits >= 8 {
477 bits -= 8;
478 out.push((buf >> bits) as u8);
479 buf &= (1 << bits) - 1;
480 }
481 }
482 Some(out)
483}
484
485fn toml_string(s: &str) -> String {
487 let mut out = String::from("\"");
488 for c in s.chars() {
489 match c {
490 '"' => out.push_str("\\\""),
491 '\\' => out.push_str("\\\\"),
492 '\n' => out.push_str("\\n"),
493 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04X}", c as u32)),
494 c => out.push(c),
495 }
496 }
497 out.push('"');
498 out
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504
505 #[test]
506 fn checksums_round_trip_through_base64() {
507 let digest: [u8; 32] = std::array::from_fn(|i| (i * 7) as u8);
508 let c = checksum_of(&digest);
509 assert!(c.starts_with("sha256-") && c.ends_with('='));
510 let hex = checksum_hex(&c).unwrap();
511 assert_eq!(hex.len(), 64);
512 assert_eq!(&hex[..6], "00070e");
513 assert_eq!(checksum_hex("sha256-short"), None);
514 }
515
516 #[test]
517 fn the_lock_round_trips_in_a_fixed_order() {
518 let lock = Lock {
519 registries: vec![LockedRegistry {
520 name: "acme-internal".into(),
521 id: "acme".into(),
522 key: "ed25519-fp:abc".into(),
523 }],
524 npm: vec![
525 LockedNpm {
526 package: "jose".into(),
527 range: "^5.2.0".into(),
528 required_by: vec!["acme/ledger:auth".into()],
529 approved: true,
530 first_party: false,
531 },
532 LockedNpm {
533 package: "postal-mime".into(),
534 range: "4.1.4".into(),
535 required_by: vec!["bynk-std".into()],
536 approved: false,
537 first_party: true,
538 },
539 LockedNpm {
540 package: "stripe".into(),
541 range: "^14.2.0".into(),
542 required_by: vec!["acme/ledger:pay".into()],
543 approved: false,
544 first_party: false,
545 },
546 ],
547 packages: vec![
548 LockedPackage {
549 name: "acme/money".into(),
550 version: None,
551 source: "path+../packages/money".into(),
552 checksum: None,
553 dependencies: vec![],
554 },
555 LockedPackage {
556 name: "acme/ledger".into(),
557 version: Some("0.3.0".into()),
558 source: git_source("https://x/ledger", "v0.3.0", "9f1c"),
559 checksum: Some(checksum_of(&[1; 32])),
560 dependencies: vec!["acme/money".into()],
561 },
562 ],
563 };
564 let text = lock.render();
565 assert!(text.find("acme/ledger").unwrap() < text.find("acme/money").unwrap());
566 let back = parse_lock(&text).unwrap();
567 assert_eq!(back.render(), text);
568 assert!(text.contains("[[npm]]\npackage = \"jose\"\nrange = \"^5.2.0\"\nrequired-by = [\"acme/ledger:auth\"]\napproved = true\n"));
569 assert!(
570 text.contains("required-by = [\"acme/ledger:pay\"]\n\n")
571 || text.ends_with("required-by = [\"acme/ledger:pay\"]\n")
572 );
573 assert_eq!(back.npm, lock.npm, "approval survives the round trip");
574 assert!(
575 text.contains("range = \"4.1.4\"\nrequired-by = [\"bynk-std\"]\nfirst-party = true\n")
576 );
577 assert!(
578 !text.contains("first-party = true\napproved"),
579 "a first-party row is never approved"
580 );
581 assert!(text.find("[[npm]]").unwrap() > text.find("[[package]]").unwrap());
582 assert!(text.contains(
583 "[[registry]]\nname = \"acme-internal\"\nid = \"acme\"\nkey = \"ed25519-fp:abc\"\n"
584 ));
585 assert_eq!(back.registry("acme-internal").unwrap().id, "acme");
586 let (p, commit) = back
587 .git("acme/ledger", "https://x/ledger", "v0.3.0")
588 .unwrap();
589 assert_eq!(commit, "9f1c");
590 assert_eq!(p.version.as_deref(), Some("0.3.0"));
591 assert!(
592 back.git("acme/ledger", "https://x/ledger", "main")
593 .is_none()
594 );
595 }
596
597 #[test]
598 fn a_malformed_required_by_is_refused() {
599 let row = |by: &str| {
600 format!(
601 "version = 1\n\n[[npm]]\npackage = \"jose\"\nrange = \"^5\"\nrequired-by = {by}\n"
602 )
603 };
604 assert!(
605 parse_lock(&row("\"a/b:c\""))
606 .unwrap_err()
607 .0
608 .contains("must be a list")
609 );
610 assert!(
611 parse_lock(&row("[1]"))
612 .unwrap_err()
613 .0
614 .contains("must list strings")
615 );
616 assert_eq!(
617 parse_lock(&row("[\"a/b:c\"]")).unwrap().npm[0].required_by,
618 ["a/b:c"]
619 );
620 }
621
622 #[test]
623 fn a_lock_without_a_version_is_refused() {
624 assert!(
625 parse_lock("[[package]]\nname = \"a/b\"\nsource = \"path+x\"\n")
626 .unwrap_err()
627 .0
628 .contains("no `version`")
629 );
630 assert!(
631 parse_lock("version = 2\n")
632 .unwrap_err()
633 .0
634 .contains("version 2")
635 );
636 assert_eq!(parse_lock("version = 1\n").unwrap(), Lock::default());
637 }
638}
639
640#[cfg(test)]
641mod requires_tests {
642 use super::adapter_requires;
643
644 #[test]
645 fn an_adapters_requires_are_read() {
646 let src = "adapter tokens {\n binding \"./t.binding.ts\" requires { \"jose\": \"^5\", \"zod\": \"3.23.8\" }\n}\n";
647 assert_eq!(
648 adapter_requires(src),
649 Some((
650 "tokens".to_string(),
651 vec![
652 ("jose".into(), "^5".into()),
653 ("zod".into(), "3.23.8".into())
654 ]
655 ))
656 );
657 assert_eq!(adapter_requires("commons x\n"), None);
658 }
659}