← Commit history
v2.1.3: Listings say what they are, and a reel listing no longer reads as "out of stock". DigiKey and JLCPCB data is still partial upstream (see below).
12 files changed
+565−112
Cargo.lock+1−1@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "adom-parts-search"-version = "2.1.2"+version = "2.1.3" dependencies = [ "base64", "clap",
Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.2"+version = "2.1.3" edition = "2021" description = "Parts Search Electronics component search — CLI, backend HTTP service, and Hydrogen webview app" license = "MIT"
VERSION+1−1@@ -1 +1 @@-2.1.2+2.1.3
install.shpackage.json+1−33@@ -34,37 +34,5 @@ "SKILL.md", "BUILD-SKILL.md", "CHANGELOG.md"- ],- "changelog": "Listings say what they are, and a reel listing no longer reads as \"out of stock\". DigiKey and JLCPCB data is still partial upstream (see below).",- "discovery_triggers": [- "parts-search",- "parts-search parts",- "parts-search pricing",- "parts-search search",- "parts-search part number",- "component search",- "part lookup",- "price breaks",- "datasheet parts-search",- "in stock parts-search"- ],- "discovery_pitch": "Search Parts Search Electronics for components, pricing, stock, and datasheets \u2014 CLI + webview app + shared backend service.",- "sample_prompts": [- {- "label": "source an STM32F103RBT6",- "prompt": "source an STM32F103RBT6"- },- {- "label": "where can I get an ESP32-S3-WROOM cheape",- "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"- },- {- "label": "compare Mouser, DigiKey and JLCPCB for a",- "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"- },- {- "label": "price this BOM across distributors",- "prompt": "price this BOM across distributors"- } ]-}+}
page.json+19−49@@ -36,60 +36,30 @@ "path": "screenshots/hero.png" }, "sample_prompts": [- {- "label": "source an STM32F103RBT6",- "prompt": "source an STM32F103RBT6"- },- {- "label": "where can I get an ESP32-S3-WROOM cheape",- "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"- },- {- "label": "compare Mouser, DigiKey and JLCPCB for a",- "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"- },- {- "label": "price this BOM across distributors",- "prompt": "price this BOM across distributors"- }+ "source an STM32F103RBT6",+ "where can I get an ESP32-S3-WROOM cheapest and fastest",+ "compare Mouser, DigiKey and JLCPCB for an LM555",+ "price this BOM across distributors" ], "discovery_triggers": [- "parts-search",- "parts-search parts",- "parts-search pricing",- "parts-search search",- "parts-search part number",- "component search",- "part lookup",- "price breaks",- "datasheet parts-search",- "in stock parts-search"+ "parts search",+ "find part",+ "source component",+ "source part",+ "compare distributors",+ "compare vendors",+ "Mouser or DigiKey",+ "BOM sourcing",+ "price this part",+ "where can I get",+ "check stock",+ "parts availability",+ "fastest delivery" ],- "discovery_pitch": "Search Parts Search Electronics for components, pricing, stock, and datasheets — CLI + webview app + shared backend service.",+ "discovery_pitch": "Search Mouser + DigiKey + JLCPCB in parallel from one interface, with product photos and a Mouser-preferred best-source pick.", "metadata": { "platform": "linux" }, "category": "tools",- "org": "adom",- "description": "One search box across Mouser, DigiKey and JLCPCB. Parallel queries, side-by-side product photos, and a Mouser-preferred recommendation that reasons around stock and lead time. Dock Bar ready: serve, health, settings, Say it.",- "dependencies": {},- "needs_sudo": false,- "scripts": {- "install": "./install.sh",- "uninstall": "./uninstall.sh"- },- "files": [- "bin/**",- "skills/**",- "docs/icon.svg",- "dockbar.json",- "install.sh",- "uninstall.sh",- "package.json",- "README.md",- "SKILL.md",- "BUILD-SKILL.md",- "CHANGELOG.md"- ],- "changelog": "Listings say what they are, and a reel listing no longer reads as \"out of stock\". DigiKey and JLCPCB data is still partial upstream (see below)."+ "org": "adom" }
publish.sh+1−1@@ -181,7 +181,7 @@ ok "registry tarball clean + release binary returns --version $VERSION" step "7. push page repo (dockbar.json, docs, screenshots, source)" PAGE_FILES=(dockbar.json docs/icon.svg README.md SKILL.md BUILD-SKILL.md CHANGELOG.md VERSION Cargo.toml Cargo.lock package.json page.json build.sh publish.sh install.sh uninstall.sh LICENSE- src/main.rs src/cli.rs src/install.rs src/serve.rs src/settings.rs src/taskbar.rs src/vendors.rs+ src/main.rs src/cli.rs src/install.rs src/serve.rs src/settings.rs src/taskbar.rs src/vendors.rs src/wiki.rs src/app/mod.rs src/app/tab.rs src/app/ui.html src/app/vendor/newbie-panel.js skills/adom-parts-search-dock/SKILL.md) for f in src/app/audio/demo-*.mp3 src/app/audio/narration.json; do [ -f "$f" ] && PAGE_FILES+=("$f"); done for f in src/app/fonts/*.woff2 screenshots/*.png docs/hero.png; do [ -f "$f" ] && PAGE_FILES+=("$f"); done
src/app/ui.html+7@@ -239,6 +239,9 @@ main>:first-child{margin-top:0} .row-price{display:flex;gap:10px;font-size:12px;margin-top:4px;align-items:baseline;flex-wrap:wrap} .price{font:700 15px var(--mono);color:var(--accent)} .price-100{font:11px var(--mono);color:var(--text-2)}+.listing{font:600 11px var(--mono);color:var(--text-body);margin-top:4px}+.breaks{font:11px var(--mono);color:var(--text-2);margin-top:2px;overflow-wrap:anywhere}+.hit-note{font-size:12px;line-height:1.35;color:var(--yellow);margin-top:4px} .stock{font-size:12px;display:inline-flex;align-items:center;gap:6px} .stock i{display:inline-block;width:34px;height:4px;border-radius:999px;background:var(--overlay);overflow:hidden;position:relative} .stock i::after{content:"";position:absolute;inset:0;width:var(--fill,0%);background:currentColor;border-radius:999px}@@ -807,6 +810,7 @@ function renderCard(hit){ if(hit.datasheet_url)actions.push('<a href="'+escape(hit.datasheet_url)+'" target="_blank" rel="noopener" data-tooltip="Open the manufacturer datasheet (PDF) in a new tab.">Datasheet '+ICON_EXT+'</a>'); if(hit.cad_3d_url){const fmt=(hit.cad_3d_format||'3D').toUpperCase();const xref=(hit.cad_3d_source||'').includes('xref'); actions.push('<a href="'+escape(hit.cad_3d_url)+'" target="_blank" rel="noopener" data-tooltip="Opens the '+escape(fmt)+' CAD model for '+escape(hit.mpn||'this part')+'. Most links go through SamacSys or Ultra Librarian, which may ask you to sign in first. With the STEP file local, adom-molecule create --step brings it into Adom.'+(xref?' This link came from a DigiKey hit with the same MPN; '+VNAME[String(hit.vendor).toLowerCase()]+' does not publish its own CAD.':'')+'">3D '+escape(fmt)+(xref?'<span class="xref">via DigiKey</span>':'')+' '+ICON_EXT+'</a>');}+ const breaks=(hit.price_breaks||[]).slice(0,4).map(b=>fmtStock(b.qty)+'+ '+escape(b.price)).join(' · '); const img=settings.showImages&&hit.image_url; const cap=escape((hit.mpn||'')+(hit.manufacturer?' '+hit.manufacturer:'')); return '<div class="card">'@@ -819,6 +823,9 @@ function renderCard(hit){ +(hit.description?'<div class="desc" title="'+escape(hit.description)+'">'+escape(hit.description)+'</div>':'') +'<div class="row-price">'+(hit.unit_price?'<span class="price">'+escape(hit.unit_price)+'</span>':'')+(hit.price_100?'<span class="price-100">@100: '+escape(hit.price_100)+'</span>':'') +'<span class="stock '+stockClass(hit.stock)+'" title="'+(hit.stock||0)+' units"><i style="--fill:'+Math.min(100,Math.round(Math.log10((hit.stock||0)+1)/5*100))+'%"></i>'+fmtStock(hit.stock)+' in stock</span>'+(hit.lead_time?'<span class="vendor-pn">lead '+escape(hit.lead_time)+'</span>':'')+'</div>'+ +(hit.packaging||hit.min_order>1?'<div class="listing">'+[hit.packaging?escape(hit.packaging):'',hit.min_order>1?'min '+fmtStock(hit.min_order):''].filter(Boolean).join(' · ')+'</div>':'')+ +(breaks?'<div class="breaks" data-tooltip="Price per unit at each quantity">'+breaks+'</div>':'')+ +(hit.note?'<div class="hit-note">'+escape(hit.note)+'</div>':'') +(flags?'<div class="flags">'+flags+'</div>':'')+(actions.length?'<div class="card-actions">'+actions.join('')+'</div>':'')+'</div></div>'; } function renderColumn(v,block){
src/cli.rs+10@@ -277,6 +277,16 @@ fn render_summary_to_stdout(query: &str, resp: &serde_json::Value) { color(YELLOW, &format!("{:>9}", price1)), format_stock(stock), color(DIM, lead));+ let pack = h.get("packaging").and_then(|v| v.as_str()).unwrap_or("");+ let min = h.get("min_order").and_then(|v| v.as_u64()).filter(|m| *m > 1);+ let breaks: Vec<String> = h.get("price_breaks").and_then(|v| v.as_array()).map(|a| a.iter().take(4).filter_map(|b|+ Some(format!("{}+ {}", b.get("qty")?.as_u64()?, b.get("price")?.as_str()?))).collect()).unwrap_or_default();+ let mut facts: Vec<String> = vec![];+ if !pack.is_empty() { facts.push(pack.to_string()); }+ if let Some(m) = min { facts.push(format!("min {}", m)); }+ if !breaks.is_empty() { facts.push(breaks.join(", ")); }+ if !facts.is_empty() { println!(" {}", color(DIM, &facts.join(" | "))); }+ if let Some(n) = h.get("note").and_then(|v| v.as_str()) { println!(" {}", color(YELLOW, n)); } } }
src/vendors.rs+244−26@@ -51,6 +51,18 @@ pub struct VendorHit { pub datasheet_url: Option<String>, pub product_url: Option<String>, pub flags: Vec<String>, // "RoHS", "basic", "preferred", etc.+ /// Every price break the vendor answered, lowest quantity first.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub price_breaks: Vec<PriceBreak>,+ /// Fewest units this listing sells. The vendor's own figure, or the first price break's quantity for JLCPCB.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub min_order: Option<u64>,+ /// "Tape & Reel", "Cut Tape" or "Digi-Reel": what this listing ships as, when the vendor or its part number says.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub packaging: Option<String>,+ /// What this hit's numbers do not tell you: a reel listing's 0 stock, or a price the vendor did not send.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>, /// URL to a STEP/IGES/GLB/ZIP CAD model, when the source vendor /// exposes one. Click-through usually redirects through SamacSys / /// SnapEDA / Ultra Librarian auth.@@ -65,6 +77,12 @@ pub struct VendorHit { pub cad_3d_source: Option<String>, } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct PriceBreak {+ pub qty: u64,+ pub price: String,+}+ #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct AggregatedResults { pub query: String,@@ -129,6 +147,9 @@ pub struct Recommendation { pub mpn: String, pub unit_price: Option<String>, pub stock: u64,+ /// Fewest units this listing sells, when more than one. A full reel is not a prototype quantity.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub min_order: Option<u64>, /// What the user actually asked for, when the query was an exact MPN. #[serde(skip_serializing_if = "Option::is_none")] pub requested_mpn: Option<String>,@@ -298,25 +319,51 @@ fn redact(raw: &str) -> String { s } -fn price_at_qty(tiers: Option<&Vec<Value>>, qty: u32) -> Option<String> {- let tiers = tiers?;- // Find the tier with the largest qty ≤ requested- let mut best: Option<(u32, String)> = None;- for t in tiers {- let tqty = t.get("qty").and_then(|v| v.as_u64()).unwrap_or(0) as u32;- let tprice = t.get("price").and_then(|v| v.as_str()).unwrap_or("");- if tqty <= qty && !tprice.is_empty() {- let keep = best.as_ref().map(|(q, _)| tqty >= *q).unwrap_or(true);- if keep {- best = Some((tqty, tprice.to_string()));- }- }- }- best.map(|(_, p)| p)+/// A vendor's price breaks in any of the shapes the services send: {qty, price: "$0.10"} (Mouser, DigiKey),+/// {from, to, usd} (JLCPCB's live read) and {qty_from, qty_to, price_usd} (JLCPCB's search).+fn price_breaks(c: &Value) -> Vec<PriceBreak> {+ let mut out: Vec<PriceBreak> = c.get("price_tiers").and_then(|v| v.as_array()).map(|tiers| tiers.iter().filter_map(|t| {+ let qty = ["qty", "from", "qty_from"].iter().find_map(|k| t.get(*k).and_then(|v| v.as_u64()))?;+ let price = t.get("price").and_then(|v| v.as_str()).filter(|p| !p.is_empty()).map(String::from)+ .or_else(|| ["usd", "price_usd", "price"].iter().find_map(|k| t.get(*k).and_then(|v| v.as_f64())).map(money))?;+ Some(PriceBreak { qty, price })+ }).collect()).unwrap_or_default();+ out.sort_by_key(|b| b.qty);+ out+}++fn money(v: f64) -> String { format!("${:.4}", v) }++fn price_at_qty(breaks: &[PriceBreak], qty: u64) -> Option<String> {+ breaks.iter().filter(|b| b.qty <= qty).max_by_key(|b| b.qty).map(|b| b.price.clone())+}++/// What a DigiKey listing ships as: the service's own field when it sends one, otherwise DigiKey's part-number+/// convention (...TR-ND and ...-2-ND are full reels, ...CT-ND and ...-1-ND cut tape, ...DKR-ND and ...-6-ND Digi-Reel).+fn digikey_packaging(c: &Value, pn: &str) -> Option<String> {+ if let Some(p) = c.get("packaging").and_then(|v| v.as_str()).filter(|p| !p.is_empty()) { return Some(p.to_string()); }+ let u = pn.to_uppercase();+ let is = |endings: [&str; 2]| endings.iter().any(|e| u.ends_with(e));+ if is(["TR-ND", "-2-ND"]) { Some("Tape & Reel".into()) }+ else if is(["CT-ND", "-1-ND"]) { Some("Cut Tape".into()) }+ else if is(["DKR-ND", "-6-ND"]) { Some("Digi-Reel".into()) }+ else { None }+}++/// DigiKey sells one part as several listings. A hit that is only the full reel and reads 0 says nothing about the+/// cut tape, so nothing here may call the part out of stock at DigiKey on its strength (adom/adom-parts-search#11).+fn reel_stock_unknown(h: &VendorHit) -> bool {+ h.vendor == Vendor::DigiKey && h.stock == 0 && h.packaging.as_deref() == Some("Tape & Reel")+}++fn digikey_note(h: &VendorHit) -> Option<String> {+ if !reel_stock_unknown(h) { return None; }+ Some(format!("Full-reel listing{}. DigiKey's cut tape and Digi-Reel stock is not in this answer, so 0 here does not mean DigiKey is out: check the product page.",+ h.min_order.filter(|m| *m > 1).map(|m| format!(" (minimum {})", m)).unwrap_or_default())) } fn normalize_mouser(c: &Value) -> VendorHit {- let tiers = c.get("price_tiers").and_then(|v| v.as_array());+ let breaks = price_breaks(c); VendorHit { vendor: Vendor::Mouser, vendor_pn: c.get("mouser_pn").and_then(|v| v.as_str()).unwrap_or("").to_string(),@@ -325,7 +372,7 @@ fn normalize_mouser(c: &Value) -> VendorHit { description: c.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string(), stock: c.get("stock").and_then(|v| v.as_u64()).unwrap_or(0), unit_price: c.get("unit_price").and_then(|v| v.as_str()).map(String::from),- price_100: price_at_qty(tiers, 100),+ price_100: price_at_qty(&breaks, 100), lead_time: c.get("lead_time").and_then(|v| v.as_str()).unwrap_or("").to_string(), image_url: c.get("image_url").and_then(|v| v.as_str()).map(String::from), datasheet_url: c.get("datasheet_url").and_then(|v| v.as_str()).map(String::from),@@ -336,6 +383,10 @@ fn normalize_mouser(c: &Value) -> VendorHit { if let Some(s) = c.get("lifecycle").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) { f.push(s.to_string()); } f },+ min_order: c.get("min_order").and_then(|v| v.as_u64()),+ packaging: c.get("packaging").and_then(|v| v.as_str()).filter(|p| !p.is_empty()).map(String::from),+ note: None,+ price_breaks: breaks, cad_3d_url: None, // Mouser API doesn't expose CAD links cad_3d_format: None, cad_3d_source: None,@@ -343,19 +394,21 @@ fn normalize_mouser(c: &Value) -> VendorHit { } fn normalize_digikey(c: &Value) -> VendorHit {- let tiers = c.get("price_tiers").and_then(|v| v.as_array());+ let breaks = price_breaks(c);+ let pn = c.get("digikey_pn").and_then(|v| v.as_str()).unwrap_or("").to_string(); let cad_url = c.get("cad_3d_url").and_then(|v| v.as_str()).map(String::from); let cad_fmt = c.get("cad_3d_format").and_then(|v| v.as_str()).map(String::from); let has_cad = cad_url.is_some();- VendorHit {+ let mut hit = VendorHit { vendor: Vendor::DigiKey,- vendor_pn: c.get("digikey_pn").and_then(|v| v.as_str()).unwrap_or("").to_string(),+ packaging: digikey_packaging(c, &pn),+ vendor_pn: pn, mpn: c.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_string(), manufacturer: c.get("manufacturer").and_then(|v| v.as_str()).unwrap_or("").to_string(), description: c.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string(), stock: c.get("stock").and_then(|v| v.as_u64()).unwrap_or(0), unit_price: c.get("unit_price").and_then(|v| v.as_str()).map(String::from),- price_100: price_at_qty(tiers, 100),+ price_100: price_at_qty(&breaks, 100), lead_time: c.get("lead_time").and_then(|v| v.as_str()).unwrap_or("").to_string(), image_url: c.get("image_url").and_then(|v| v.as_str()).map(String::from), datasheet_url: c.get("datasheet_url").and_then(|v| v.as_str()).map(String::from),@@ -366,14 +419,21 @@ fn normalize_digikey(c: &Value) -> VendorHit { if let Some(s) = c.get("lifecycle").and_then(|v| v.as_str()).filter(|s| !s.is_empty()) { f.push(s.to_string()); } f },+ min_order: c.get("min_order").and_then(|v| v.as_u64()),+ note: None,+ price_breaks: breaks, cad_3d_url: cad_url, cad_3d_format: cad_fmt, cad_3d_source: if has_cad { Some("digikey".into()) } else { None },- }+ };+ hit.note = digikey_note(&hit);+ hit } fn normalize_jlcpcb(c: &Value) -> VendorHit {- let tiers = c.get("price_tiers").and_then(|v| v.as_array());+ let breaks = price_breaks(c);+ let unit_price = c.get("unit_price_usd").and_then(|v| v.as_f64()).map(money)+ .or_else(|| breaks.first().map(|b| b.price.clone())); let is_basic = c.get("is_basic").and_then(|v| v.as_bool()).unwrap_or(false); let is_preferred = c.get("is_preferred").and_then(|v| v.as_bool()).unwrap_or(false); let lcsc = c.get("lcsc").and_then(|v| v.as_str()).unwrap_or("").to_string();@@ -387,12 +447,17 @@ fn normalize_jlcpcb(c: &Value) -> VendorHit { manufacturer: c.get("manufacturer").and_then(|v| v.as_str()).unwrap_or("").to_string(), description: c.get("description").and_then(|v| v.as_str()).unwrap_or("").to_string(), stock: c.get("stock").and_then(|v| v.as_u64()).unwrap_or(0),- unit_price: tiers.and_then(|t| t.first()).and_then(|t| t.get("price")).and_then(|v| v.as_str()).map(String::from),- price_100: price_at_qty(tiers, 100),+ min_order: c.get("min_order").and_then(|v| v.as_u64()).or_else(|| breaks.first().map(|b| b.qty)),+ packaging: None,+ // JLCPCB's search snapshot can answer with stock and no price (adom/adom-parts-search#10): say so, never a blank+ note: if unit_price.is_none() { Some("JLCPCB's parts snapshot sent no price for this part. See the price on its JLCPCB page.".into()) } else { None },+ price_100: price_at_qty(&breaks, 100),+ unit_price,+ price_breaks: breaks, lead_time: String::new(), image_url, datasheet_url: c.get("datasheet").and_then(|v| v.as_str()).map(String::from),- product_url: c.get("jlcpcb_url").and_then(|v| v.as_str()).map(String::from),+ product_url: c.get("jlcpcb_url").or_else(|| c.get("jlcpcb_parts_url")).and_then(|v| v.as_str()).map(String::from), flags: { let mut f = vec![]; if is_basic { f.push("basic".into()); }@@ -598,6 +663,15 @@ fn build_empty_state(agg: &AggregatedResults) -> EmptyState { // said "returned zero hits ... are currently erroring" with nothing erroring. if m_ok && d_ok && j_ok && (m_hits + d_hits + j_hits) > 0 { let jlc_stock: u64 = agg.jlcpcb.hits.iter().map(|h| h.stock).max().unwrap_or(0);+ if agg.digikey.hits.iter().any(reel_stock_unknown) {+ return EmptyState {+ title: format!("No in-stock listing found for \"{q}\", but DigiKey's cut tape was not checked."),+ explanation: format!(+ "Mouser has no stock or a long lead time. DigiKey answered with its full-reel listing only, which reads 0; its cut tape and Digi-Reel stock is not in this answer.{}",+ if jlc_stock > 0 { format!(" JLCPCB has {} for boards it assembles.", jlc_stock) } else { String::new() }),+ hint: "Open the part's DigiKey page from its card to see cut-tape stock before calling it unavailable.".into(),+ };+ } return EmptyState { title: format!("No distributor has \"{q}\" in stock right now."), explanation: format!(@@ -662,8 +736,15 @@ fn is_exact_query(agg: &AggregatedResults, query: &str) -> bool { fn finish(h: &VendorHit, reason: String, query: &str, exact_query: bool) -> Recommendation { let exact = exact_query && norm_mpn(&h.mpn) == norm_mpn(query);+ let min_order = h.min_order.filter(|m| *m > 1);+ let reason = match (min_order, h.packaging.as_deref()) {+ (Some(m), Some(p)) => format!("{} Minimum order {} ({}).", reason, m, p),+ (Some(m), None) => format!("{} Minimum order {}.", reason, m),+ _ => reason,+ }; Recommendation { winner: h.vendor,+ min_order, reason, mpn: h.mpn.clone(), unit_price: h.unit_price.clone(),@@ -681,6 +762,9 @@ fn finish(h: &VendorHit, reason: String, query: &str, exact_query: bool) -> Reco } } +/// A minimum order above this means the listing sells by the reel or the pack, not for a prototype.+const BULK_ONLY_MIN: u64 = 100;+ /// The "cheapest" policy: lowest in-stock unit price across every vendor /// that answered, ties broken toward Mouser (shipping is still near zero). ///@@ -696,6 +780,10 @@ fn pick_cheapest(agg: &AggregatedResults, query: &str) -> Option<Recommendation> .filter(eligible).collect(); let exact: Vec<&VendorHit> = all.iter().copied().filter(|h| norm_mpn(&h.mpn) == q).collect(); let pool = if exact_query && !exact.is_empty() { exact } else { all };+ // A reel price is not a price for a few parts: a $0.002 listing with a minimum of 5000 costs $10 to touch. Listings+ // sold in small quantities compete first; a bulk-only listing wins only when nothing else is in stock.+ let small: Vec<&VendorHit> = pool.iter().copied().filter(|h| h.min_order.unwrap_or(1) <= BULK_ONLY_MIN).collect();+ let pool = if small.is_empty() { pool } else { small }; let mut best: Option<(f64, &VendorHit)> = None; for h in pool { let v = price_value(&h.unit_price)?;@@ -741,6 +829,9 @@ fn distributor_substitution(rec: Option<Recommendation>, agg: &AggregatedResults j.vendor_pn, j.mpn, j.stock )); }+ if agg.digikey.hits.iter().any(|h| reel_stock_unknown(h) && norm_mpn(&h.mpn) == q) {+ text.push_str(" DigiKey answered with its full-reel listing only, so check the exact part's cut-tape stock on its DigiKey page first.");+ } rec.substitution = Some(text); Some(rec) }@@ -795,6 +886,7 @@ mod recommendation_tests { manufacturer: "TI".into(), description: "test".into(), stock, unit_price: Some(price.into()), price_100: None, lead_time: "0".into(), image_url: None, datasheet_url: None, product_url: None, flags: vec![],+ price_breaks: vec![], min_order: None, packaging: None, note: None, cad_3d_url: None, cad_3d_format: None, cad_3d_source: None, } }@@ -960,6 +1052,7 @@ mod empty_state_tests { fn hit(v: Vendor, stock: u64) -> VendorHit { VendorHit { vendor: v, vendor_pn: "x".into(), mpn: "TPS62840DLCR".into(), manufacturer: String::new(), description: String::new(), stock, unit_price: None, price_100: None, lead_time: String::new(), image_url: None, datasheet_url: None, product_url: None, flags: vec![],+ price_breaks: vec![], min_order: None, packaging: None, note: None, cad_3d_url: None, cad_3d_format: None, cad_3d_source: None } } #[test]@@ -981,3 +1074,128 @@ mod route_limit_tests { assert_eq!([0, 1, 2, 3, 4, 5, 6, 10, 25].map(super::route_limit), [3, 3, 3, 3, 5, 5, 10, 10, 10]); } }++#[cfg(test)]+mod listing_tests {+ //! adom/adom-parts-search#10 and #11. The fixtures are the service answers captured on 2026-11-05.+ use super::*;++ fn breaks(pairs: &[(u64, &str)]) -> Vec<PriceBreak> { pairs.iter().map(|(q, p)| PriceBreak { qty: *q, price: p.to_string() }).collect() }++ fn dk_reel() -> Value {+ json!({"digikey_pn": "311-100KHRTR-ND", "mpn": "RC0603FR-07100KL", "manufacturer": "YAGEO", "stock": 0, "unit_price": "$0.1000", "min_order": 5000,+ "price_tiers": [{"price": "$0.0054", "qty": 5000}, {"price": "$0.0048", "qty": 10000}]})+ }++ #[test]+ fn jlcpcb_search_answer_with_no_price_says_so() {+ let h = normalize_jlcpcb(&json!({"lcsc": "C14675", "mfr": "RC0603FR-07100KL", "stock": 11626702, "unit_price_usd": null, "price_tiers": []}));+ assert_eq!(h.unit_price, None);+ assert_eq!(h.price_100, None);+ assert_eq!(h.min_order, None);+ assert!(h.note.unwrap().contains("sent no price"));+ // the note sends you to the JLCPCB page, so the card must link it+ let linked = normalize_jlcpcb(&json!({"lcsc": "C14675", "jlcpcb_parts_url": "https://jlcpcb.com/parts/componentSearch?searchTxt=C14675"}));+ assert_eq!(linked.product_url.as_deref(), Some("https://jlcpcb.com/parts/componentSearch?searchTxt=C14675"));+ }++ /// The tiers JLCPCB's live read sends today; the search answer gets the same data once the service fills it in.+ #[test]+ fn jlcpcb_live_tiers_become_prices_and_a_minimum() {+ let h = normalize_jlcpcb(&json!({"lcsc": "C14675", "mfr": "RC0603FR-07100KL", "stock": 11626702, "unit_price_usd": 0.0021,+ "price_tiers": [{"from": 1, "to": 999, "usd": 0.0021}, {"from": 1000, "to": 4999, "usd": 0.0015}]}));+ assert_eq!(h.unit_price.as_deref(), Some("$0.0021"));+ assert_eq!(h.price_100.as_deref(), Some("$0.0021"));+ assert_eq!(h.min_order, Some(1));+ assert_eq!(h.price_breaks, breaks(&[(1, "$0.0021"), (1000, "$0.0015")]));+ assert!(h.note.is_none());+ }++ /// The shape the service's published source writes: numbers under price_usd, no unit_price_usd.+ #[test]+ fn jlcpcb_snapshot_tiers_are_read_too() {+ let h = normalize_jlcpcb(&json!({"mfr": "X", "stock": 5, "price_tiers": [{"qty_from": 20, "qty_to": 199, "price_usd": 0.5}]}));+ assert_eq!(h.unit_price.as_deref(), Some("$0.5000"));+ assert_eq!(h.min_order, Some(20));+ assert_eq!(h.price_100.as_deref(), Some("$0.5000"));+ }++ #[test]+ fn mouser_and_digikey_tiers_still_read_the_same() {+ let h = normalize_mouser(&json!({"mouser_pn": "m", "mpn": "X", "unit_price": "$1.00", "price_tiers": [{"qty": 1, "price": "$1.00"}, {"qty": 100, "price": "$0.70"}, {"qty": 1000, "price": "$0.50"}]}));+ assert_eq!(h.price_100.as_deref(), Some("$0.70"));+ assert_eq!(h.price_breaks.len(), 3);+ }++ #[test]+ fn digikey_part_numbers_name_their_packaging() {+ for (pn, want) in [("311-100KHRTR-ND", Some("Tape & Reel")), ("311-1886-2-ND", Some("Tape & Reel")), ("311-100KHRCT-ND", Some("Cut Tape")),+ ("311-1886-1-ND", Some("Cut Tape")), ("311-100KHRDKR-ND", Some("Digi-Reel")), ("311-1886-6-ND", Some("Digi-Reel")), ("296-1395-5-ND", None)] {+ assert_eq!(digikey_packaging(&json!({}), pn).as_deref(), want, "{pn}");+ }+ assert_eq!(digikey_packaging(&json!({"packaging": "Bulk"}), "311-100KHRTR-ND").as_deref(), Some("Bulk"));+ }++ #[test]+ fn a_reel_listing_reading_zero_is_labelled_not_called_out_of_stock() {+ let h = normalize_digikey(&dk_reel());+ assert_eq!(h.packaging.as_deref(), Some("Tape & Reel"));+ assert_eq!(h.min_order, Some(5000));+ assert_eq!(h.price_100, None);+ assert_eq!(h.price_breaks.first().map(|b| b.qty), Some(5000));+ let note = h.note.unwrap();+ assert!(note.contains("minimum 5000") && note.contains("does not mean DigiKey is out"), "{note}");+ }++ #[test]+ fn a_cut_tape_listing_at_zero_gets_no_excuse() {+ let h = normalize_digikey(&json!({"digikey_pn": "311-100KHRCT-ND", "mpn": "X", "stock": 0, "min_order": 1}));+ assert!(h.note.is_none());+ }++ #[test]+ fn nobody_says_out_of_stock_on_a_reel_listing_alone() {+ let ok = |h: Vec<VendorHit>| VendorBlock { ok: true, total: h.len() as u64, hits: h, ..Default::default() };+ let mut mouser = normalize_mouser(&json!({"mouser_pn": "m", "mpn": "RC0603FR-07100KL"}));+ mouser.stock = 0;+ let a = AggregatedResults { query: "RC0603FR-07100KL".into(), mouser: ok(vec![mouser]), digikey: ok(vec![normalize_digikey(&dk_reel())]), jlcpcb: ok(vec![]), ..Default::default() };+ assert!(pick_winner(&a, &a.query).is_none());+ let e = build_empty_state(&a);+ assert!(e.title.contains("cut tape was not checked"), "{}", e.title);+ assert!(!e.title.contains("No distributor has"), "{}", e.title);+ }++ #[test]+ fn a_variant_at_mouser_is_flagged_with_the_unchecked_cut_tape() {+ let ok = |h: Vec<VendorHit>| VendorBlock { ok: true, total: h.len() as u64, hits: h, ..Default::default() };+ let variant = normalize_mouser(&json!({"mouser_pn": "m", "mpn": "RC0603FR-07100KP", "stock": 500, "unit_price": "$0.10"}));+ let a = AggregatedResults { query: "RC0603FR-07100KL".into(), mouser: ok(vec![variant]), digikey: ok(vec![normalize_digikey(&dk_reel())]), jlcpcb: ok(vec![]), ..Default::default() };+ let note = pick_winner(&a, &a.query).unwrap().substitution.unwrap();+ assert!(note.contains("full-reel listing only"), "{note}");+ }++ /// The reported $0.002 marketplace reel must not win "cheapest" over a price someone can actually pay for a few.+ #[test]+ fn cheapest_does_not_pick_a_reel_only_price_over_small_quantities() {+ let ok = |h: Vec<VendorHit>| VendorBlock { ok: true, total: h.len() as u64, hits: h, ..Default::default() };+ let reel = normalize_digikey(&json!({"digikey_pn": "abc-2-ND", "mpn": "CC0805", "stock": 40000, "unit_price": "$0.0020", "min_order": 4000}));+ let cut = normalize_mouser(&json!({"mouser_pn": "m", "mpn": "CC0805", "stock": 900, "unit_price": "$0.30", "min_order": 1}));+ let a = AggregatedResults { query: "CC0805".into(), mouser: ok(vec![cut]), digikey: ok(vec![reel.clone()]), jlcpcb: ok(vec![]), ..Default::default() };+ let r = pick_cheapest(&a, &a.query).unwrap();+ assert_eq!(r.winner, Vendor::Mouser);+ // alone, the reel still wins, and says what it costs to buy it+ let b = AggregatedResults { query: "CC0805".into(), mouser: ok(vec![]), digikey: ok(vec![reel]), jlcpcb: ok(vec![]), ..Default::default() };+ let r = pick_cheapest(&b, &b.query).unwrap();+ assert_eq!(r.min_order, Some(4000));+ assert!(r.reason.contains("Minimum order 4000 (Tape & Reel)"), "{}", r.reason);+ }++ #[test]+ fn the_preferred_recommendation_names_a_bulk_minimum() {+ let ok = |h: Vec<VendorHit>| VendorBlock { ok: true, total: h.len() as u64, hits: h, ..Default::default() };+ let reel = normalize_digikey(&json!({"digikey_pn": "abc-2-ND", "mpn": "CC0805", "stock": 40000, "unit_price": "$0.05", "min_order": 4000}));+ let a = AggregatedResults { query: "CC0805".into(), mouser: ok(vec![]), digikey: ok(vec![reel]), jlcpcb: ok(vec![]), ..Default::default() };+ let r = pick_winner(&a, &a.query).unwrap();+ assert!(r.reason.ends_with("Minimum order 4000 (Tape & Reel)."), "{}", r.reason);+ }+}
src/wiki.rsadded+280@@ -0,0 +1,280 @@+//! The Adom wiki side of a search: component pages with ready-made CAD, their Verified state and Adom stock, the+//! request flow for a part with no page, and the transport for the wiki's parts-search route. wiki.adom.inc is the+//! only host this module calls.+//!+//! This file was missing from the page repo (publish.sh never listed it), so 2.1.3 rebuilt it from the routes, keys and+//! messages in the 2.1.2 binary and checked it against that binary's output. If the original turns up, diff the two.++use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::thread;+use std::time::Duration;++pub const DEFAULT_WIKI: &str = "https://wiki.adom.inc";+/// How many search rows are looked at closely: each one costs up to three wiki reads.+const MAX_PAGES: usize = 5;+const USER_AGENT: &str = concat!("adom-parts-search/", env!("CARGO_PKG_VERSION"));++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct Cad {+ pub symbol: bool,+ pub footprint: bool,+ #[serde(rename = "3d")]+ pub model_3d: bool,+ pub step: bool,+ pub lbr: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct WikiHit {+ pub r#ref: String,+ pub url: String,+ pub title: String,+ pub mpn: String,+ pub manufacturer: String,+ pub visibility: String,+ pub exact: bool,+ pub cad: Cad,+ /// "none", "verified" or "stale".+ pub verified: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub lifecycle: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub adom: Option<Value>,+ #[serde(default)]+ pub distributor_links: Value,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub stock: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub datasheet_url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub package: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct WikiBlock {+ pub ok: bool,+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub skipped: bool,+ pub error: Option<String>,+ pub ready_made: bool,+ pub hits: Vec<WikiHit>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub request: Option<Value>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub candidates: Vec<Value>,+ pub miss_recorded: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub miss_note: Option<String>,+ pub signed_in: bool,+ pub elapsed_ms: u64,+}++/// The wiki's public route, or a direct test route (ADOM_PARTS_SEARCH_URL + ADOM_PARTS_SEARCH_KEY).+#[derive(Debug, Clone)]+pub struct Route {+ pub url: String,+ pub via: String,+ pub key: Option<String>,+ pub user: Option<String>,+}++pub fn parts_search_route() -> Route {+ let env = |k: &str| std::env::var(k).ok().filter(|s| !s.is_empty());+ if let Some(url) = env("ADOM_PARTS_SEARCH_URL") {+ return Route { url, via: "test-route".into(), key: env("ADOM_PARTS_SEARCH_KEY"), user: env("ADOM_PARTS_SEARCH_USER") };+ }+ Route { url: format!("{}/api/parts-search", DEFAULT_WIKI), via: "wiki".into(), key: None, user: None }+}++/// The wiki CLI's sign-in: ADOM_WIKI_TOKEN, or api_token in ~/.config/adom-wiki/config.json.+fn token() -> Option<String> {+ if let Some(t) = std::env::var("ADOM_WIKI_TOKEN").ok().filter(|s| !s.trim().is_empty()) { return Some(t.trim().to_string()); }+ let home = std::env::var("HOME").ok()?;+ let raw = std::fs::read_to_string(format!("{}/.config/adom-wiki/config.json", home)).ok()?;+ let v: Value = serde_json::from_str(&raw).ok()?;+ v.get("api_token").and_then(|t| t.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(String::from)+}++pub fn signed_in() -> bool { token().is_some() }++fn netlog(method: &str, url: &str) {+ if std::env::var("ADOM_PARTS_SEARCH_NETLOG").map(|v| v == "1").unwrap_or(false) {+ eprintln!("NET {} {}", method, url.split('?').next().unwrap_or(url));+ }+}++fn agent(secs: u64) -> ureq::Agent { ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build() }++fn with_identity(mut req: ureq::Request) -> ureq::Request {+ req = req.set("User-Agent", USER_AGENT).set("X-Adom-Client", USER_AGENT).set("X-Adom-Caller", "parts-search");+ if let Some(t) = token() { req = req.set("Authorization", &format!("Bearer {}", t)); }+ req+}++fn answer(res: Result<ureq::Response, ureq::Error>) -> Result<Value, String> {+ match res {+ Ok(r) => r.into_json().map_err(|e| format!("bad JSON: {}", e)),+ Err(ureq::Error::Status(code, r)) => Err(format!("http {}: {}", code, r.into_string().unwrap_or_default().chars().take(300).collect::<String>())),+ Err(e) => Err(e.to_string()),+ }+}++fn get(path: &str, secs: u64) -> Result<Value, String> {+ let url = format!("{}{}", DEFAULT_WIKI, path);+ netlog("GET", &url);+ answer(with_identity(agent(secs).get(&url)).call())+}++fn post(path: &str, body: Value, secs: u64) -> Result<Value, String> {+ let url = format!("{}{}", DEFAULT_WIKI, path);+ netlog("POST", &url);+ answer(with_identity(agent(secs).post(&url)).set("Content-Type", "application/json").send_json(body))+}++/// One search through the parts-search route. Component Ocean may ask three vendors live, so this waits longer than a read.+pub fn post_route(route: &Route, body: Value) -> Result<Value, String> {+ netlog("POST", &route.url);+ let mut req = with_identity(agent(60).post(&route.url)).set("Content-Type", "application/json");+ if route.via == "test-route" {+ if let Some(k) = &route.key { req = req.set("X-Adom-Request-Key", k); }+ req = req.set("X-Adom-User", route.user.as_deref().unwrap_or("anon")).set("X-Adom-Anon-Ip", "127.0.0.1");+ }+ answer(req.send_json(body)).map_err(|e| {+ if e.starts_with("http 404") { format!("{} the wiki's parts-search route is not live yet (adom/wiki#261)", e) } else { e }+ })+}++fn enc(s: &str) -> String {+ let mut out = String::new();+ for b in s.bytes() {+ match b {+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),+ _ => out.push_str(&format!("%{:02X}", b)),+ }+ }+ out+}++pub fn request_offer(mpn: &str) -> Value {+ json!({+ "mpn": mpn,+ "message": format!("No Adom wiki page for {} yet. Request it and Adom's factory builds one (symbol, footprint, 3D, datasheet).", mpn),+ "cli": format!("adom-parts-search request {}", mpn),+ "web": format!("{}/search?q={}", DEFAULT_WIKI, enc(mpn)),+ })+}++fn norm(s: &str) -> String { s.trim().to_uppercase() }++fn text(v: &Value, ptr: &str) -> Option<String> {+ v.pointer(ptr).and_then(|x| x.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(String::from)+}++fn raw_text(v: &Value, ptr: &str) -> Option<String> { v.pointer(ptr).and_then(|x| x.as_str()).map(String::from) }++/// page.json + verification + stock -> one hit. A file that does not answer leaves its fields empty, never an error.+/// None for a page that is neither the part asked for nor has a symbol or footprint (a group page, a library): it is no+/// part to show, and its stock is not read.+fn hit_from(row: &Value, q: &str) -> Option<WikiHit> {+ let owner = row.get("owner").and_then(|v| v.as_str()).unwrap_or("").to_string();+ let slug = row.get("slug").and_then(|v| v.as_str()).unwrap_or("").to_string();+ let reference = format!("{}/{}", owner, slug);+ let base = format!("/api/pages/{}/{}", owner, slug);+ let page = get(&format!("{}/files/page.json", base), 10).unwrap_or(Value::Null);+ let parts = page.pointer("/component/parts").cloned().unwrap_or(Value::Null);+ let has = |k: &str| parts.get(k).and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false);+ let title = row.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string();+ let mpn = text(&page, "/component/mpn").unwrap_or_else(|| title.clone());+ let verified = match get(&format!("{}/verification", base), 10).ok().and_then(|v| v.get("verification").cloned()).filter(|v| !v.is_null()) {+ None => "none",+ Some(v) if v.get("stale").and_then(|s| s.as_bool()).unwrap_or(false) => "stale",+ Some(_) => "verified",+ }.to_string();+ let exact = norm(&mpn) == norm(q) || norm(&slug) == norm(q) || norm(&title) == norm(q);+ if !(exact || has("symbol") || has("footprint")) { return None; }+ let stock = get(&format!("{}/stock", base), 10).ok();+ Some(WikiHit {+ url: format!("{}/{}", DEFAULT_WIKI, reference),+ exact,+ r#ref: reference,+ title,+ manufacturer: text(&page, "/component/manufacturer").unwrap_or_default(),+ visibility: row.get("visibility").and_then(|v| v.as_str()).unwrap_or("public").to_string(),+ cad: Cad {+ symbol: has("symbol"),+ footprint: has("footprint"),+ model_3d: has("model_3d") || has("model_3d_plain"),+ step: has("model_3d_step") || has("model_3d_step_plain"),+ lbr: has("lbr"),+ },+ verified,+ lifecycle: text(&page, "/component/lifecycle").or_else(|| text(&page, "/distributor_check/manufacturer/lifecycle")),+ adom: stock.as_ref().and_then(|s| s.get("adom")).filter(|a| !a.is_null()).cloned(),+ distributor_links: page.pointer("/component/distributor_links").cloned().unwrap_or(Value::Null),+ stock,+ datasheet_url: raw_text(&page, "/component/datasheet"),+ package: Some(raw_text(&page, "/component/package").unwrap_or_default()),+ description: text(&page, "/brief").or_else(|| row.get("brief").and_then(|v| v.as_str()).map(String::from)),+ mpn,+ })+}++/// Tell the wiki an exact part had no page. The wiki takes this from its own search page only for now, so a refusal is+/// a note on the block, never a failed search. Component Ocean counts the demand either way.+fn record_miss(q: &str) -> (bool, Option<String>) {+ match post("/api/part-search-miss", json!({"mpn": q}), 8) {+ Ok(_) => (true, None),+ Err(e) if e.contains("PART_SEARCH_MISS_CROSS_SITE") =>+ (false, Some("not recorded: the wiki accepts search misses from its own search page only (an API route is pending on the wiki side)".into())),+ Err(e) => (false, Some(format!("not recorded: {}", e))),+ }+}++pub fn search(q: &str, _host: Option<&str>) -> WikiBlock {+ let t0 = std::time::Instant::now();+ let mut block = WikiBlock { signed_in: signed_in(), ..Default::default() };+ let found = get(&format!("/api/search?q={}&type=component&limit=12", enc(q)), 10);+ let rows = match found {+ Ok(v) => v.get("results").and_then(|r| r.as_array()).cloned().unwrap_or_default(),+ Err(e) => { block.error = Some(e); block.elapsed_ms = t0.elapsed().as_millis() as u64; return block; }+ };+ block.ok = true;+ let handles: Vec<_> = rows.into_iter().take(MAX_PAGES).map(|row| { let q = q.to_string(); thread::spawn(move || hit_from(&row, &q)) }).collect();+ let mut hits: Vec<WikiHit> = handles.into_iter().filter_map(|h| h.join().ok().flatten()).collect();+ hits.sort_by_key(|h| !h.exact); // exact pages first; the sort is stable, so the wiki's rank holds within each group+ block.ready_made = hits.iter().any(|h| h.exact && (h.cad.symbol || h.cad.footprint));+ // keywords ("100nF 0402") are not a part number the request flow can take+ if !hits.iter().any(|h| h.exact) && !q.trim().contains(char::is_whitespace) {+ let candidates = get(&format!("/api/part-request/candidates?q={}", enc(q)), 10).unwrap_or(Value::Null);+ block.candidates = candidates.get("candidates").and_then(|c| c.as_array()).cloned().unwrap_or_default();+ if candidates.get("exact").and_then(|e| e.as_bool()).unwrap_or(false) {+ let mpn = block.candidates.iter().find(|c| norm(c.get("mpn").and_then(|m| m.as_str()).unwrap_or("")) == norm(q))+ .and_then(|c| c.get("mpn").and_then(|m| m.as_str())).unwrap_or(q.trim()).to_string();+ block.request = Some(request_offer(&mpn));+ let (recorded, note) = record_miss(&mpn);+ block.miss_recorded = recorded;+ block.miss_note = note;+ }+ }+ block.hits = hits;+ block.elapsed_ms = t0.elapsed().as_millis() as u64;+ block+}++/// The wiki's own request flow (POST /api/part-request). Needs a sign-in.+pub fn request(mpn: &str, urgency: &str, _host: Option<&str>) -> Result<Value, String> {+ if !signed_in() { return Err("not signed in to the wiki: run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then request again".into()); }+ let mut v = post("/api/part-request", json!({"mpn": mpn, "urgency": urgency}), 30)?;+ // the route answers a site-relative status link; print one a person can open+ if let Some(path) = v.get("status_url").and_then(|u| u.as_str()).filter(|u| u.starts_with('/')).map(String::from) {+ v["status_url"] = json!(format!("{}{}", DEFAULT_WIKI, path));+ }+ Ok(v)+}++pub fn request_status(id: &str, _host: Option<&str>) -> Result<Value, String> {+ get(&format!("/api/part-request/status/{}", enc(id)), 15)+}
uninstall.sh