// /reps — who represents a place. Own code. Sources are official government feeds only, read live and cached for 12 hours: // U.S. Census Bureau geocoder -> state, congressional district, state legislative districts, county, city // senate.gov member XML -> both U.S. Senators (phone, contact form) // clerk.house.gov member XML -> the U.S. Representative (phone) // azleg.gov member rosters -> Arizona State Senator and Representatives (phone, email) [Arizona only] // GET -> the Park Terrace address (2577 W Greenway Rd, Phoenix) // POST {lat,lon} -> that point. POST {address} -> that street address. POST {state,cd,sldu,sldl} -> those districts (no lookup). // Nothing is stored. An address or point is passed to the Census Bureau only to find the districts. const HOME = { lat: 33.6252, lon: -112.1152 }; const UA = { "user-agent": "TerraceHub/1.0 (resident community page; representative lookup)" }; const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } }); const text = async (url) => { const r = await fetch(url, { headers: UA, cf: { cacheTtl: 43200, cacheEverything: true } }); if (!r.ok) throw new Error(url + " " + r.status); return r.text(); }; const tag = (x, t) => { const m = new RegExp(`<${t}[^>]*>([\\s\\S]*?)`, "i").exec(x); return m ? m[1].replace(/<[^>]+>/g, "").replace(/&/g, "&").trim() : ""; }; const ord = n => { n = +n; const s = ["th", "st", "nd", "rd"], v = n % 100; return n + (s[(v - 20) % 10] || s[v] || s[0]); }; async function locate(b) { const base = "https://geocoding.geo.census.gov/geocoder/geographies/", q = "&benchmark=Public_AR_Current&vintage=Current_Current&format=json"; let g, matched = ""; if (b.address) { const j = await (await fetch(base + "onelineaddress?address=" + encodeURIComponent(String(b.address).slice(0, 200)) + q, { headers: UA })).json(); const m = j.result && j.result.addressMatches && j.result.addressMatches[0]; if (!m) return null; g = m.geographies; matched = m.matchedAddress; } else { const lat = +b.lat, lon = +b.lon; if (!(lat > 17 && lat < 72 && lon < -64 && lon > -180)) return null; const j = await (await fetch(base + `coordinates?x=${lon.toFixed(5)}&y=${lat.toFixed(5)}` + q, { headers: UA })).json(); g = j.result && j.result.geographies; } if (!g) return null; const pick = re => { const k = Object.keys(g).find(k => re.test(k)); return k && g[k][0] ? g[k][0] : null; }; const st = pick(/^States$/), cd = pick(/Congressional/), up = pick(/Legislative Districts - Upper/), lo = pick(/Legislative Districts - Lower/), co = pick(/^Counties$/), pl = pick(/Incorporated Places/); if (!st) return null; return { state: st.STUSAB, stateName: st.NAME, cd: cd ? cd.BASENAME : "", sldu: up ? up.BASENAME : "", sldl: lo ? lo.BASENAME : "", county: co ? co.NAME : "", place: pl ? pl.BASENAME : "", matched }; } async function federal(w) { const out = []; try { const x = await text("https://www.senate.gov/general/contact_information/senators_cfm.xml"); (x.match(/[\s\S]*?<\/member>/g) || []).filter(m => tag(m, "state") === w.state).forEach(m => out.push({ level: "us", role: "U.S. Senator for " + (w.stateName || w.state), name: "Senator " + tag(m, "first_name") + " " + tag(m, "last_name"), phone: tag(m, "phone"), form: /^https:\/\//.test(tag(m, "email")) ? tag(m, "email") : tag(m, "website"), src: "senate.gov" })); } catch (e) { out.push({ level: "us", role: "U.S. Senate", name: "U.S. Senators", note: "The Senate list did not load", form: "https://www.senate.gov/senators/senators-contact.htm", src: "senate.gov" }); } try { const x = await text("https://clerk.house.gov/xml/lists/MemberData.xml"), n = /^\d+$/.test(w.cd) ? +w.cd : 0; const key = w.state + String(n).padStart(2, "0"); const m = (x.match(/[\s\S]*?<\/member>/g) || []).find(m => tag(m, "statedistrict") === key); if (m) { const nm = tag(m, "official-name") || (tag(m, "firstname") + " " + tag(m, "lastname")); out.push(nm.trim() ? { level: "us", role: "U.S. Representative, " + (n ? ord(n) + " District" : "at large") + ", " + (w.stateName || w.state), name: "Representative " + nm, phone: tag(m, "phone"), form: "https://www.house.gov/representatives/find-your-representative", src: "clerk.house.gov" } : { level: "us", role: "U.S. House, " + (n ? ord(n) + " District" : "at large"), name: "Seat currently vacant", form: "https://www.house.gov/representatives/find-your-representative", src: "clerk.house.gov" }); } } catch (e) { out.push({ level: "us", role: "U.S. House", name: "Your U.S. Representative", note: "The House list did not load", form: "https://www.house.gov/representatives/find-your-representative", src: "house.gov" }); } return out; } async function arizona(w) { const out = []; for (const [body, d, title] of [["S", w.sldu, "State Senator"], ["H", w.sldl, "State Representative"]]) { if (!/^\d+$/.test(d)) continue; try { const x = await text("https://www.azleg.gov/memberroster/?body=" + body); (x.match(/]*>[\s\S]*?<\/tr>/g) || []).forEach(r => { const td = (r.match(/]*>[\s\S]*?<\/td>/g) || []).map(t => t.replace(/<[^>]+>/g, " ").replace(/&/g, "&").replace(/\s+/g, " ").trim()); if (td.length < 6 || td[1] !== String(+d)) return; const em = /Email:\s*([A-Za-z0-9._-]+)/.exec(td[3]); out.push({ level: "state", role: `Arizona ${title}, Legislative District ${+d}`, name: (body === "S" ? "Senator " : "Representative ") + td[0].replace(/\s*--.*$/, ""), phone: td[5], email: em ? em[1].toLowerCase() + "@azleg.gov" : "", src: "azleg.gov" }); }); } catch (e) {} } return out; } export async function onRequest({ request }) { let b = {}; if (request.method === "POST") { b = await request.json().catch(() => ({})); } else if (request.method !== "GET") return json({ error: "method" }, 405); let w, home = false; try { if (b.state && /^[A-Z]{2}$/.test(b.state)) w = { state: b.state, stateName: String(b.stateName || "").slice(0, 40), cd: String(b.cd || "").slice(0, 12), sldu: String(b.sldu || "").slice(0, 6), sldl: String(b.sldl || "").slice(0, 6), county: String(b.county || "").slice(0, 60), place: String(b.place || "").slice(0, 60) }; else if (b.address || b.lat != null) w = await locate(b); else { w = await locate(HOME); home = true; } } catch (e) { return json({ error: "The district lookup did not answer just now. Please try again in a minute." }, 502); } if (!w) return json({ error: b.address ? "That address was not found. Try the street number, street, city and state." : "That place could not be matched to a U.S. district." }, 404); const offices = (await federal(w)).concat(w.state === "AZ" ? await arizona(w) : []); return json({ home, where: w, offices, stateListed: w.state === "AZ", checked: new Date().toISOString() }); }