Menu
Sign inDownload

Example: UEX data

Add-ons sharing data: one add-on owns a web API, others ask it questions.

Our published UEX data connector, whole: add-ons sharing data. One add-on owns a web API (UEX's trade data, for one game): the cache on disk, one request budget for every add-on (a rolling 60 a minute), one optional key, back-off after failures. Its manifest provides questions (search, offers, places, place_from_game, distances, a cached read-only get), each answered in handle_call inside an add-on call's 256 KB and 10 s. Other add-ons declare "depends": {"uex": ">=1.0"} and uses.uex.<fn>, call it with await api.call("uex", fn, body), and never talk to the web API themselves; installing one from the hub brings UEX data along. Where to buy is its consumer: the next example.

manifest.json

{
 "author": "Comms Array",
 "name": "uex",
 "package": "commsarray_uex",
 "title": "UEX data",
 "tier": "official",
 "api": 1,
 "api_version": "1.4",
 "games": [
  "starcitizen"
 ],
 "widgets": [
  "uex_status"
 ],
 "pad_js": "pad_uex.js",
 "permissions": [
  "pad.widgets"
 ],
 "provides": [
  "status",
  "search",
  "offers",
  "places",
  "place_from_game",
  "distances",
  "get"
 ],
 "description": "UEX's Star Citizen trade data (prices, terminals, places) for every add-on that uses it: one cache, one request budget, one optional UEX key. Add-ons that need it bring it along.",
 "version": "1.0.1"
}

commsarray_uex/__init__.py

"""UEX data (a Comms Array add-on): the one connection to UEX, Star Citizen's community trade data, for every add-on.

Wiring only: the connector is connector.UexData (what other add-ons may call, its own tile); UEX's API and the cache in
uex.py, the request budget in budget.py, places in places.py, the price lists in catalogue.py; the tile in pad_uex.js.
"""
from .connector import UexData

__version__ = "1.0.1"
__all__ = ["UexData", "create"]


def create(api):
    return UexData(api)

commsarray_uex/connector.py

"""UEX data: the one connection to UEX for every add-on that uses it (operator, 30 Nov 2026: "Everything goes through the
data plugin. 1 api key, 1 cache store").

It keeps UEX's big lists on disk (uex.Store), the player's key, one request budget for all callers (budget.py), and a
week of terminal distances; it backs off after failures. Other add-ons never talk to UEX: they declare
`"depends": {"uex": ">=1.0"}` and call these (each needs `uses.uex.<fn>`), answers small enough for an add-on call
(256 KB) and quick enough for one (10 s):

  status                       -> {ready, loading, error, age_s, has_key}
  search {q, limit?}           -> {results: [{key, kind, name, places, from, unit}]}   items, commodities, ships
  offers {key}                 -> {key, name, unit, offers: [{terminal, shop, where, place, place_id, near, system,
                                   moon_id, planet_id, system_id, price, updated}]}   open terminals only
  places                       -> {places: [{id, name, system, near, system_id, planet_id, moon_id, terminal}]}
  place_from_game {path}       -> {anchor: {place, moon, planet, system, name, terminal} | null}   a game's place names
  distances {origin, to: [..]} -> {gm: {terminal: gigameters | null}}   up to 6, kept a week
  get {resource, params?}      -> {data}   any read-only UEX resource (uex.PASSTHROUGH), cached by UEX's own times

Its own pad widget shows the data's age and any trouble, and takes the key.
"""
from __future__ import annotations

import asyncio
import json
import time
from pathlib import Path

from . import catalogue, places, uex
from .budget import Budget

REFRESH_S = 10 * 60                     # look for stale big lists this often
BACKOFF_MAX_S = 2 * 3600                # after failures, wait up to this long before trying UEX again
DIST_TTL_S = 7 * 86400                  # a terminal-to-terminal distance is kept this long
DIST_TIMEOUT_S = 4                      # one distance request waits this long at most
CALL_BUDGET_S = 8                       # an answer to another add-on: inside its 10 s
MAX_ANSWER = 200_000                    # bytes of JSON: inside an add-on call's 256 KB
MAX_DISTANCES = 6
FAIL_KEEP_S = 30                        # a failed get() answers the same for this long (callers waiting on it too)


class UexData:
    def __init__(self, api, fetch=uex.get, budget: Budget | None = None):
        self.api = api
        self.folder = Path(getattr(api, "data_dir", None) or ".")
        self.settings_file = self.folder / "settings.json"
        self.key = ""                       # the player's own UEX key, optional; never sent to a pad or another add-on
        self.budget = budget or Budget()
        self._raw = fetch
        self.store = uex.Store(self.folder / "uex", fetch=self.fetch)
        self.dist: dict[str, list] = {}
        self.cache: dict[str, list] = {}    # get(): key -> [data, at]
        self.failed: dict[str, tuple] = {}  # get(): key -> (why, at), a failure shared for FAIL_KEEP_S
        self.users: dict[str, float] = {}   # add-ons that asked, and when (shown on the tile)
        self._locks: dict[str, asyncio.Lock] = {}
        self._task = None
        self._derive()
        try:
            self.key = str(json.loads(self.settings_file.read_text(encoding="utf-8")).get("uex_key") or "")
        except (OSError, ValueError, AttributeError):
            pass

    def fetch(self, name, params=None, **kw):
        """Every request to UEX: within the shared budget, with the key when there is one."""
        if not self.budget.take():
            raise uex.UexError("busy: too many UEX requests this minute, try again shortly")
        return self._raw(name, params, key=self.key, **kw)

    def _save(self):
        try:
            self.folder.mkdir(parents=True, exist_ok=True)
            self.settings_file.write_text(json.dumps({"uex_key": self.key}), encoding="utf-8")
        except OSError:
            pass

    def _derive(self):
        t = [x for x in self.store.data.get("terminals") or [] if isinstance(x, dict) and x.get("id")]
        self.terminals = {x["id"]: x for x in t}
        self.places = places.places(t)
        self.idx = catalogue.index(self.store.data)

    def ready(self) -> bool:
        return self.store.ready() and bool(self.places) and bool(self.idx)

    # ---- keeping the big lists ----------------------------------------------------------------------------------
    async def start(self):
        await asyncio.to_thread(self.store.load)
        self._derive()
        self._task = asyncio.create_task(self._keep_fresh())

    async def stop(self):
        if self._task:
            self._task.cancel()

    async def _keep_fresh(self):
        wait = REFRESH_S
        while True:
            if self.store.stale():
                if await asyncio.to_thread(self.store.refresh):
                    self._derive()
                wait = min(BACKOFF_MAX_S, wait * 2) if self.store.error else REFRESH_S
            await asyncio.sleep(wait)

    # ---- distances ---------------------------------------------------------------------------------------------
    def _dist_file(self) -> Path:
        return self.folder / "uex" / "distances.json"

    def _distances(self, origin: int, dests: list[int], deadline: float) -> dict:
        """Gigameters from origin to each dest (None when unknown), asked once and kept a week; stops at the deadline."""
        if not self.dist:
            try:
                self.dist = json.loads(self._dist_file().read_text(encoding="utf-8"))
            except (OSError, ValueError):
                self.dist = {}
        out, now, asked = {}, time.time(), False
        for d in dests:
            k = f"{origin}-{d}"
            hit = self.dist.get(k)
            if isinstance(hit, list) and len(hit) == 2 and now - hit[1] < DIST_TTL_S:
                out[d] = hit[0]
                continue
            if time.monotonic() > deadline:
                out[d] = None
                continue
            try:
                r = self.fetch("terminals_distances", {"id_terminal_origin": origin, "id_terminal_destination": d},
                               timeout=DIST_TIMEOUT_S)
                gm = float(r["distance"]) if isinstance(r, dict) and r.get("distance") is not None else None
            except (uex.UexError, TypeError, ValueError, KeyError):
                out[d] = None
                continue
            self.dist[k], out[d], asked = [gm, now], gm, True
        if asked:
            try:
                self._dist_file().parent.mkdir(parents=True, exist_ok=True)
                self._dist_file().write_text(json.dumps(self.dist), encoding="utf-8")
            except OSError:
                pass
        return out

    # ---- get: any read-only resource, cached ---------------------------------------------------------------------
    async def _get(self, resource: str, params: dict) -> tuple[dict, int]:
        if resource not in uex.PASSTHROUGH:
            return {"status": "not_allowed", "message": f"UEX data doesn't pass on {resource!r}"}, 400
        key = resource + "?" + json.dumps(params, sort_keys=True)
        lock = self._locks.setdefault(key, asyncio.Lock())
        async with lock:                     # the same question at once: one request to UEX, both get the answer
            hit = self.cache.get(key)
            if hit and time.time() - hit[1] < uex.PASSTHROUGH[resource]:
                return {"data": hit[0], "age_s": round(time.time() - hit[1])}, 200
            failed = self.failed.get(key)
            if failed and time.time() - failed[1] < FAIL_KEEP_S:
                # just failed for whoever asked first: the same answer, not a second wait (Codex, keys PR 28): the last
                # good one with its age when there is one, else the failure (Codex, hub PR 155)
                if hit:
                    return {"data": hit[0], "age_s": round(time.time() - hit[1]), "stale": failed[0]}, 200
                return {"status": "uex_error", "message": failed[0]}, 502
            try:
                data = await asyncio.to_thread(self.fetch, resource, params or None, timeout=CALL_BUDGET_S - 1)
            except uex.UexError as e:
                self.failed[key] = (str(e), time.time())
                if hit:                      # UEX trouble: the last good answer, with its age
                    return {"data": hit[0], "age_s": round(time.time() - hit[1]), "stale": str(e)}, 200
                return {"status": "uex_error", "message": str(e)}, 502
            self.failed.pop(key, None)
            if len(json.dumps(data)) > MAX_ANSWER:
                return {"status": "too_big", "message": f"{resource} is too big to hand over whole: narrow it with "
                                                         "UEX's own filters (params), or ask UEX data's search / offers"}, 413
            self.cache[key] = [data, time.time()]
            return {"data": data, "age_s": 0}, 200

    # ---- other add-ons -----------------------------------------------------------------------------------------
    async def handle_call(self, fn: str, caller: str, body: dict):
        self.users[str(caller)[:40]] = time.time()
        body = body if isinstance(body, dict) else {}
        if fn == "status":
            return {"ready": self.ready(), "loading": not self.ready() and not self.store.error,
                    "error": self.store.error, "age_s": self.store.age_s(), "has_key": bool(self.key)}, 200
        if fn == "get":
            params = body.get("params") if isinstance(body.get("params"), dict) else {}
            params = {str(k)[:40]: str(v)[:200] for k, v in list(params.items())[:10]}
            return await self._get(str(body.get("resource") or ""), params)
        if not self.ready():
            return {"status": "not_ready", "message": self.store.error or "UEX data is still getting UEX's lists"}, 503
        if fn == "search":
            limit = body.get("limit") if isinstance(body.get("limit"), int) else catalogue.MAX_RESULTS
            return {"results": catalogue.search(self.idx, str(body.get("q") or "")[:60], limit)}, 200
        if fn == "offers":
            entry = self.idx.get(str(body.get("key") or ""))
            return (catalogue.offers(entry, self.terminals), 200) if entry else ({"status": "unknown"}, 404)
        if fn == "places":
            return {"places": [{"id": p["id"], "name": p["name"], "system": p["system"], "near": p["near"],
                                "system_id": p["system_id"], "planet_id": p["planet_id"], "moon_id": p["moon_id"],
                                "terminal": p["terminals"][0] if p["terminals"] else None} for p in self.places]}, 200
        if fn == "place_from_game":
            path = [str(x)[:80] for x in body.get("path") or [] if isinstance(x, str)][:12]
            return {"anchor": places.anchor_from_game(path, list(self.terminals.values()), self.places)}, 200
        if fn == "distances":
            to = [d for d in body.get("to") or [] if isinstance(d, int)][:MAX_DISTANCES]
            origin = body.get("origin")
            if not isinstance(origin, int):
                return {"status": "bad_request", "message": "origin: a terminal id"}, 400
            gm = await asyncio.to_thread(self._distances, origin, to, time.monotonic() + CALL_BUDGET_S - DIST_TIMEOUT_S)
            return {"gm": {str(k): v for k, v in gm.items()}}, 200
        return {"status": "no_such_function"}, 404

    # ---- its own tile: the data's age, trouble, the key ------------------------------------------------------------
    async def handle_pad(self, device: dict, body: dict):
        op = body.get("op")
        if op == "status":
            return {"ready": self.ready(), "loading": not self.ready() and not self.store.error, "error": self.store.error,
                    "age_s": self.store.age_s(), "has_key": bool(self.key),
                    "users": sorted(u for u, t in self.users.items() if time.time() - t < 86400)}, 200
        if op == "key":
            key = str(body.get("key") or "").strip()
            if len(key) > 200 or any(c.isspace() or not c.isprintable() for c in key):
                return {"status": "bad_key", "message": "That doesn't look like a UEX API key"}, 400
            self.key = key
            self._save()
            if self.store.error and await asyncio.to_thread(self.store.refresh):
                self._derive()
            return {"status": "ok", "has_key": bool(key)}, 200
        return {"status": "bad_request"}, 400

commsarray_uex/uex.py

"""UEX (uexcorp.space), the community's Star Citizen trade data: read-only GETs, cached on disk, a key optional.

Base https://api.uexcorp.uk/2.0/<resource>; every answer is {"status": "ok", "data": [...]}. Free to use (UEX's API
docs, read 30 Nov 2026); 120 requests a minute. Cache times follow UEX's own: terminals and item / ship prices 12 h,
commodity prices 30 min. A failed fetch keeps the last good copy (with its age), never an empty one.
"""
from __future__ import annotations

import json
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

BASE = "https://api.uexcorp.uk/2.0/"
AGENT = "CommsArray-UEX/1.0"
TIMEOUT_S = 30
TTL = {"terminals": 12 * 3600, "items_prices_all": 12 * 3600, "vehicles_purchases_prices_all": 12 * 3600,
       "commodities_prices_all": 30 * 60}
DATASETS = tuple(TTL)                    # the big lists the connector keeps whole, on disk
HOUR, DAY = 3600, 86400
# what another add-on may ask for through the connector's cached `get`, and how long an answer is kept (UEX's own
# cache times, from its API docs, 30 Nov 2026). Read-only, nothing else.
PASSTHROUGH = {
    "star_systems": DAY, "planets": DAY, "moons": DAY, "orbits": DAY, "space_stations": DAY, "cities": DAY,
    "outposts": DAY, "poi": DAY, "terminals": 12 * HOUR, "categories": DAY, "companies": DAY, "items": DAY,
    "items_prices": DAY, "commodities": HOUR, "commodities_prices": 30 * 60, "vehicles": DAY,
    "vehicles_purchases_prices": 12 * HOUR, "vehicles_rentals_prices": 12 * HOUR, "fuel_prices": HOUR,
    "terminals_distances": 12 * HOUR, "commodities_routes": HOUR,
}


class UexError(Exception):
    pass


LIMITED = "requests_limit_reached"          # UEX's answer when a caller is over its quota


class LimitReached(UexError):
    pass


def get(resource: str, params: dict | None = None, key: str = "", timeout: float = TIMEOUT_S):
    """One GET; the answer's data (a list, or one object for a lookup like terminals_distances). Raises UexError on
    anything but a good answer (LimitReached when UEX says too many requests). key: the player's own UEX API key,
    optional (sent as a Bearer token, UEX's "Authentication Method"): the read endpoints work without one, but a key
    keeps a player from being shut out by a limit on keyless callers (operator, 30 Nov 2026)."""
    url = BASE + resource + ("?" + urllib.parse.urlencode(params) if params else "")
    headers = {"User-Agent": AGENT, "Accept": "application/json"}
    if key:
        headers["Authorization"] = f"Bearer {key}"
    req = urllib.request.Request(url, headers=headers)
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            body = json.loads(r.read().decode("utf-8"))
    except urllib.error.HTTPError as e:                     # an error answer can still say why (its status)
        try:
            body = json.loads(e.read().decode("utf-8"))
        except (OSError, ValueError):
            raise UexError(f"UEX answered {e.code}") from e
    except (OSError, ValueError) as e:
        raise UexError(f"UEX didn't answer ({type(e).__name__})") from e
    status = body.get("status") if isinstance(body, dict) else None
    if status == LIMITED:
        raise LimitReached("UEX's request limit is reached: add your UEX API key (below) to keep going")
    if status != "ok" or not isinstance(body.get("data"), (list, dict)):
        raise UexError(f"UEX said {status or 'something odd'}")
    return body["data"]


class Store:
    """The datasets on disk (<data_dir>/uex/<name>.json: {"at", "data"}), refreshed when older than their TTL."""

    def __init__(self, folder: Path, fetch=get, now=time.time):
        self.folder, self.fetch, self.now = Path(folder), fetch, now
        self.data: dict[str, list] = {}
        self.at: dict[str, float] = {}
        self.error = ""

    def load(self):
        for name in DATASETS:
            try:
                d = json.loads((self.folder / f"{name}.json").read_text(encoding="utf-8"))
                if isinstance(d.get("data"), list):
                    self.data[name], self.at[name] = d["data"], float(d.get("at") or 0)
            except (OSError, ValueError, AttributeError):
                pass

    def stale(self) -> list[str]:
        return [n for n in DATASETS if self.now() - self.at.get(n, 0) > TTL[n]]

    def refresh(self, names=None) -> bool:
        """Fetch what's stale (or `names`). True if anything changed. Blocking: run it in a thread."""
        changed, failed = False, ""
        for name in names or self.stale():
            try:
                rows = self.fetch(name)
                if not isinstance(rows, list) or not rows:
                    raise UexError(f"UEX sent no {name}")
            except UexError as e:
                failed = failed or str(e)              # the first failure stands, whatever succeeds after it (Codex)
                continue
            self.data[name], self.at[name] = rows, self.now()
            changed = True
            try:
                self.folder.mkdir(parents=True, exist_ok=True)
                (self.folder / f"{name}.json").write_text(json.dumps({"at": self.at[name], "data": rows}), encoding="utf-8")
            except OSError:
                pass
        self.error = failed
        return changed

    def ready(self) -> bool:
        return all(self.data.get(n) for n in ("terminals",)) and any(
            self.data.get(n) for n in ("items_prices_all", "commodities_prices_all", "vehicles_purchases_prices_all"))

    def age_s(self) -> float | None:
        ats = [self.at[n] for n in DATASETS if n in self.at]
        return max(0.0, self.now() - min(ats)) if ats else None

commsarray_uex/budget.py

"""One request budget for everything that reaches UEX through this connector, whichever add-on asked.

UEX allows 120 requests a minute; we use at most half (operator, 30 Nov 2026: "Let's not create API spam for them"):
never more than 60 in any 60 seconds (a rolling window: no burst on top after a quiet spell, Codex, keys PR 28). A
request that would go over waits a little for room, or isn't made: the caller gets "busy", never a burst at UEX.
Thread-safe: the fetches run in worker threads.
"""
from __future__ import annotations

import collections
import threading
import time

PER_MINUTE = 60
WINDOW_S = 60.0


class Budget:
    def __init__(self, per_minute: int = PER_MINUTE, now=time.monotonic, sleep=time.sleep):
        self.limit, self.now, self.sleep = per_minute, now, sleep
        self.sent: collections.deque[float] = collections.deque()     # when each request in the window went
        self.lock = threading.Lock()

    def take(self, wait_s: float = 2.0) -> bool:
        """Room for one request, waiting up to wait_s for it. False: none, don't ask UEX now."""
        end = self.now() + wait_s
        while True:
            with self.lock:
                n = self.now()
                while self.sent and n - self.sent[0] >= WINDOW_S:
                    self.sent.popleft()
                if len(self.sent) < self.limit:
                    self.sent.append(n)
                    return True
                free_at = self.sent[0] + WINDOW_S                      # the oldest leaves the window then
            if free_at > end:
                return False
            self.sleep(max(0.0, free_at - self.now()))

commsarray_uex/catalogue.py

"""What can be bought, and at which terminals: UEX's price lists turned into answers small enough to hand another add-on.

Items (per unit), commodities (per SCU), ships (per ship). A price of 0 means "doesn't sell"; a closed or unknown
terminal is never counted, priced or offered.
"""
from __future__ import annotations

from . import places as P

KINDS = {"items_prices_all": ("item", "id_item", "item_name", "each"),
         "commodities_prices_all": ("commodity", "id_commodity", "commodity_name", "per SCU"),
         "vehicles_purchases_prices_all": ("ship", "id_vehicle", "vehicle_name", "each")}
MAX_RESULTS = 25


def index(data: dict) -> dict:
    """{key: {key, kind, name, unit, offers: [{terminal, price, updated}]}} for everything with a buy price at an open
    terminal."""
    live = {t["id"] for t in data.get("terminals") or [] if isinstance(t, dict) and t.get("id") and t.get("is_available_live", 1)}
    out: dict[str, dict] = {}
    for ds, (kind, idf, namef, unit) in KINDS.items():
        for r in data.get(ds) or []:
            if not r.get(idf) or r.get("id_terminal") not in live or not (r.get("price_buy") or 0) > 0:
                continue
            key = f"{kind}:{r[idf]}"
            e = out.setdefault(key, {"key": key, "kind": kind, "name": r.get(namef) or key, "unit": unit, "offers": []})
            e["offers"].append({"terminal": r["id_terminal"], "price": float(r["price_buy"]),
                                "updated": r.get("date_modified") or 0})
    return out


def search(idx: dict, q: str, limit: int = MAX_RESULTS) -> list[dict]:
    """Names containing every word of q (case- and punctuation-blind), shortest name first (the closest match)."""
    words = [P.norm(w) for w in str(q or "").split() if P.norm(w)]
    if not words:
        return []
    hits = [e for e in idx.values() if all(w in P.norm(e["name"]) for w in words)]
    hits.sort(key=lambda e: (len(e["name"]), e["name"].lower()))
    return [{"key": e["key"], "kind": e["kind"], "name": e["name"], "places": len(e["offers"]),
             "from": min(o["price"] for o in e["offers"]), "unit": e["unit"]} for e in hits[:max(1, min(limit, 100))]]


def offers(entry: dict, terminals: dict[int, dict]) -> dict:
    """Every open terminal selling it, with where it is: names to show and ids to judge nearness by."""
    rows = []
    for o in entry["offers"]:
        t = terminals.get(o["terminal"])
        if not t or not t.get("is_available_live", 1):
            continue
        p = P.place_of(t)
        a = P.anchor_of(t)
        rows.append({"terminal": t["id"], "shop": t.get("name") or "", "where": t.get("displayname") or t.get("name") or "",
                     "place": p[1] if p else (t.get("moon_name") or t.get("planet_name") or ""), "place_id": a["place"],
                     "near": t.get("moon_name") or t.get("planet_name") or t.get("orbit_name") or "",
                     "system": t.get("star_system_name") or "", "moon_id": a["moon"], "planet_id": a["planet"],
                     "system_id": a["system"], "price": o["price"], "updated": o["updated"]})
    return {"key": entry["key"], "name": entry["name"], "unit": entry["unit"], "offers": rows}

commsarray_uex/places.py

"""Where things are, in UEX's terms: its terminals grouped into places, and a game's place names matched to them.

A terminal knows its system, planet, moon and its station / city / outpost / point of interest (ids and names; any of
them may be 0 / missing). A **place** is the most specific of those a terminal has (a station, a city...). An
**anchor** is a place, or a moon, planet or system when that's all a game's location names match. Which one is
nearer to what is the consumer's business (Where to buy: nearness.py).
"""
from __future__ import annotations

import re

KINDS = (("space_station", "station"), ("city", "city"), ("outpost", "outpost"), ("poi", "poi"))


def norm(s) -> str:
    return re.sub(r"[^a-z0-9]+", "", str(s or "").lower())


def place_of(t: dict) -> tuple[str, str] | None:
    """(key, name) of a terminal's place: its station, city, outpost or point of interest."""
    for field, kind in KINDS:
        if t.get(f"id_{field}"):
            name = t.get(f"{field}_name") or t.get("displayname") or t.get("name")
            return f"{kind}:{t[f'id_{field}']}", name
    return None


def anchor_of(t: dict) -> dict:
    p = place_of(t)
    return {"place": p[0] if p else None, "moon": t.get("id_moon") or None, "planet": t.get("id_planet") or None,
            "system": t.get("id_star_system") or None}


def places(terminals: list[dict]) -> list[dict]:
    """The dropdown: every place with a live terminal, grouped by system and planet (or moon), sorted."""
    out: dict[str, dict] = {}
    for t in terminals:
        if not t.get("is_available_live", 1):
            continue
        p = place_of(t)
        if not p:
            continue
        key, name = p
        body = t.get("moon_name") or t.get("planet_name") or t.get("orbit_name") or ""
        a = anchor_of(t)                         # ids for nearness, kept apart from the names shown (Codex, keys PR 26)
        pl = out.setdefault(key, {"id": key, "name": name, "system": t.get("star_system_name") or "", "near": body,
                                  "terminals": [], "system_id": a["system"], "planet_id": a["planet"], "moon_id": a["moon"]})
        pl["terminals"].append(t["id"])
    return sorted(out.values(), key=lambda p: (p["system"], p["near"], p["name"]))


def anchor_for_pick(pick: str, all_places: list[dict]) -> dict | None:
    p = next((x for x in all_places if x["id"] == pick), None)
    if not p:
        return None
    return {"place": p["id"], "moon": p["moon_id"], "planet": p["planet_id"], "system": p["system_id"], "name": p["name"],
            "terminal": p["terminals"][0] if p["terminals"] else None}


def anchor_from_game(path_names: list[str], terminals: list[dict], all_places: list[dict]) -> dict | None:
    """The game's location path (system down to the most specific place) matched to UEX, most specific name first: a
    place, else a moon, planet or system. None when nothing matches (then the dropdown is still the source)."""
    by_place = {norm(p["name"]): p for p in all_places}
    bodies = {}
    for t in terminals:
        for lvl, idf, namef in (("moon", "id_moon", "moon_name"), ("planet", "id_planet", "planet_name"),
                                ("system", "id_star_system", "star_system_name")):
            if t.get(idf) and t.get(namef):
                bodies.setdefault(norm(t[namef]), (lvl, t))
    for name in reversed([n for n in path_names if n]):
        n = norm(name)
        if n in by_place:
            return {**anchor_for_pick(by_place[n]["id"], all_places), "name": name}
        if n in bodies:
            lvl, t = bodies[n]
            a = {"place": None, "moon": None, "planet": None, "system": t.get("id_star_system") or None, "name": name,
                 "terminal": None}
            if lvl in ("moon", "planet"):
                a["planet"] = t.get("id_planet") or None
            if lvl == "moon":
                a["moon"] = t.get("id_moon") or None
            return a
    return None

commsarray_uex/pad_uex.js

// UEX data: a small tile saying how fresh UEX's data is and which add-ons use it; tapping it opens the key and details.
// Runs in its own sandboxed frame (window.CA); it asks the connector on the PC (CA.call). Colours: the pad's or the
// button pack's own text colour (--text / --dim), so it reads on any pack.
(() => {
  const { esc } = CA;
  const ago = (s) => (s == null ? "never" : s < 3600 ? `${Math.max(1, Math.round(s / 60))} min ago` : s < 172800
    ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} days ago`);
  const STYLE = `<style>
    .uex { color: var(--text, #d6e2ee); display: flex; flex-direction: column; gap: 8px; min-width: 0; }
    .uex .dim { color: var(--dim, #7d8fa3); }
    .uex input, .uex button { font: inherit; color: inherit; border-radius: 8px; padding: 8px 10px;
      border: 1px solid color-mix(in srgb, currentColor 40%, transparent); background: color-mix(in srgb, currentColor 8%, transparent); }
    .uex input::placeholder { color: inherit; opacity: .65; }
    .uex .warn { color: var(--warn, #ffb547); }
  </style>`;

  function details(root) {
    root.innerHTML = `${STYLE}<div class="uex">
      <div class="state"></div>
      <div class="dim" style="font-size:13px">Every add-on that uses UEX goes through here: one cache, one request budget,
        one key. Works without a key; if UEX ever limits requests without one, make a free app at uexcorp.space/api/apps
        and paste its token. It stays on your PC.</div>
      <input type="password" class="keyin" placeholder="Paste your UEX API token" autocomplete="off">
      <div style="display:flex;gap:6px"><button class="save">Save key</button><button class="clear">Remove key</button></div>
      <div class="dim" style="font-size:11px">Data: UEX (uexcorp.space)</div></div>`;
    const $ = (s) => root.querySelector(s);
    const draw = async () => {
      const s = await CA.call({ op: "status" });
      if (s.status === "offline") { $(".state").textContent = s.message || "Comms Array isn't answering"; return; }
      $(".state").innerHTML = `<b>${s.ready ? "Ready" : s.loading ? "Getting UEX's lists…" : "Not ready"}</b>
        <span class="dim">· updated ${esc(ago(s.age_s))} · ${s.has_key ? "a key is saved" : "no key"}</span>
        ${s.error ? `<div class="warn" style="font-size:12px">${esc(s.error)}</div>` : ""}
        <div class="dim" style="font-size:12px">${s.users?.length ? "Used by: " + s.users.map(esc).join(", ") : "No add-on has used it yet today"}</div>`;
      $(".clear").hidden = !s.has_key;
    };
    const save = async (key) => {
      const r = await CA.call({ op: "key", key });
      CA.toast(r.status === "ok" ? (r.has_key ? "UEX key saved" : "UEX key removed") : r.message || "Couldn't save the key");
      $(".keyin").value = "";
      draw();
    };
    $(".save").onclick = () => { const k = $(".keyin").value.trim(); if (k) save(k); };
    $(".clear").onclick = () => save("");
    draw();
  }

  CA.widget("uex_status", {
    add: { label: "UEX data", desc: "How fresh UEX's trade data is, which add-ons use it, and your optional UEX key",
           size: [4, 2], props: () => ({ label: "UEX data" }) },
    settings: [{ type: "panel", panel: "details", label: "Details and key…" }, { key: "label", type: "text", label: "Label", max: 40 }],
    tile(root, w, { editing }) {
      root.innerHTML = `<div class="w b"><span>${esc(w.label || "UEX data")}</span><span class="sub"></span></div>`;
      const el = root.firstChild;
      const draw = async () => {
        const s = await CA.call({ op: "status" });
        el.classList.toggle("on", !!s.ready);              // lit while the data is there
        el.querySelector(".sub").textContent = s.status === "offline" ? "" : s.error && !s.ready ? "trouble" : s.ready ? ago(s.age_s) : "loading";
      };
      draw();
      setInterval(draw, 60000);
      if (!editing) el.addEventListener("click", () => CA.openPanel("details"));
    },
    panels: { details: () => CA.sheet(`<h3><span>UEX data</span></h3><div class="uex-root"></div>`, (r) => details(r.querySelector(".uex-root"))) },
  });
})();
From the Comms Array source, commsarray-agent d615c4d.