inventory.py

skills/feature-audit/scripts/inventory.py437 lines, 19.0 KBView on GitHub
#!/usr/bin/env python3
"""List an app's routes, API endpoints, jobs, and tables for a feature audit.

Usage:
  inventory.py [app_dir] [--json] [--diff PREVIOUS]

PREVIOUS is an earlier `--json` output, or an earlier Markdown output / audit
file that contains it (headings Pages, API, Jobs, Tables). The diff lists what
was added, removed, or changed methods since then.

Standard library only. Reads files; runs nothing; never prints env values.
"""
import json
import os
import re
import sys

SKIP = {".git", "node_modules", ".next", "dist", "build", ".venv", "venv", "__pycache__",
        ".turbo", ".vercel", ".svelte-kit", ".astro", "coverage", "Pods", ".output",
        "__tests__", "__mocks__", "e2e", "cypress", "playwright"}
TEST_DIRS = {"test", "tests"}  # skipped unless inside a routes/pages/app folder (a /test route)
ROUTE_DIRS = {"routes", "pages", "app"}
PAGE_EXT = (".tsx", ".jsx", ".ts", ".js", ".mdx", ".astro", ".svelte", ".vue")
SERVER_EXT = (".ts", ".js", ".mjs", ".cjs", ".py")
TEST_FILE = re.compile(r"\.(test|spec)\.[cm]?[jt]sx?$|\.d\.ts$")
METHOD = r"(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)"
HTTP = re.compile(r"""\b(app|router|api|server|r|route|routes|hono|fastify)\.(get|post|put|patch|delete|all)\(\s*['"`]([^'"`]+)""", re.I)
FASTIFY_ROUTE = re.compile(r"""\.route\(\s*\{([^}]*)\}""")
FASTAPI = re.compile(r"""@\w+\.(get|post|put|patch|delete)\(\s*['"]([^'"]+)""")
NEST_CTRL = re.compile(r"""@Controller\(\s*(?:['"`]([^'"`]*)['"`]|\{[^}]*path:\s*['"`]([^'"`]*)['"`])?""")
NEST_ROUTE = re.compile(r"""@(Get|Post|Put|Patch|Delete)\(\s*(?:['"`]([^'"`]*)['"`])?\s*\)""")
EXPORT_METHOD = re.compile(r"export\s+(?:async\s+)?(?:function|const|let)\s+" + METHOD + r"\b")
EXPORT_LIST = re.compile(r"export\s*\{([^}]*)\}")
REQ_METHOD = re.compile(r"""req\.method\s*[!=]==?\s*['"]""" + METHOD + r"""['"]|case\s+['"]""" + METHOD + r"""['"]""")
AXIOS = re.compile(r"""from\s+['"](?:axios|ky|ofetch)['"]|require\(\s*['"]axios['"]\)|axios\.create\(""")
PRISMA_MODEL = re.compile(r"^model\s+(\w+)\s*\{", re.M)
SQL_TABLE = re.compile(
    r"""create\s+(?:(?:temp|temporary|unlogged)\s+)?table\s+(?:if\s+not\s+exists\s+)?"""
    r"""(?:[\"`\[]?\w+[\"`\]]?\.)?[\"`\[]?(\w+)""", re.I)
DRIZZLE = re.compile(r"""(?:pgTable|sqliteTable|mysqlTable)\(\s*['"`](\w+)""")
JOB = re.compile(r"""new\s+Worker\(\s*['"`]|cron\.schedule\(|\bschedule\(\s*['"]|\w*[Qq]ueue\.process\(|defineJob\(|"""
                 r"""inngest\.createFunction\(|schedules\.task\(|@shared_task|@\w+\.task\b""")
CONFIGS = {"next.config": "Next.js", "astro.config": "Astro", "svelte.config": "SvelteKit",
           "remix.config": "Remix", "react-router.config": "React Router", "nuxt.config": "Nuxt",
           "nest-cli.json": "NestJS"}


def files(root):
    for dirpath, dirnames, filenames in os.walk(root):
        in_routes = bool(ROUTE_DIRS & set(os.path.relpath(dirpath, root).split(os.sep)))
        dirnames[:] = sorted(d for d in dirnames if d not in SKIP and not d.startswith(".")
                             and (in_routes or d not in TEST_DIRS))
        for f in sorted(filenames):
            yield os.path.join(dirpath, f)


def read(p, limit=400_000):
    try:
        with open(p, encoding="utf-8", errors="ignore") as fh:
            return fh.read(limit)
    except OSError:
        return ""


def http_methods(text, pages_api=False):
    """Exported HTTP method handlers (Next.js, SvelteKit, Astro) or req.method checks."""
    found = set(EXPORT_METHOD.findall(text))
    for block in EXPORT_LIST.findall(text):  # export { handler as GET, handler as POST }
        found.update(re.findall(r"\bas\s+" + METHOD + r"\b", block))
        found.update(m for m in re.findall(r"(?:^|,)\s*" + METHOD + r"\s*(?=,|$)", block))
    if pages_api:
        for a, b in REQ_METHOD.findall(text):
            found.add(a or b)
    return sorted(found) or ["?"]


def clean_segments(parts):
    out = []
    for s in parts:
        if s.startswith("(") and s.endswith(")"):
            continue  # route groups
        if s.startswith("@"):
            continue  # parallel route slots
        if s.startswith("_"):
            return None  # private folders
        out.append(s)
    return out


def url(segs):
    return "/" + "/".join(s for s in segs if s)


def remix_route(rel):
    """Remix / React Router flat routes: app/routes/<rel>. None when not a route module."""
    stem = os.path.splitext(rel[-1])[0]
    if len(rel) == 1:
        tokens = stem.split(".")
    elif stem == "route":
        tokens = ".".join(rel[:-1]).split(".")  # v2 folder route: users.$id/route.tsx
    else:
        return None  # colocated helper inside a folder route
    out = []
    for t in tokens:
        if t in ("_index", "index", "route") or t.startswith("_"):
            continue  # index routes and pathless layouts
        t = t.rstrip("_")  # users_.edit opts out of nesting, not a segment change
        if t == "$":
            t = "*"
        elif t.startswith("$"):
            t = ":" + t[1:]
        out.append(t)
    return url(out)


def config_frameworks(root):
    found = set()
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in SKIP and not d.startswith(".")]
        if os.path.relpath(dirpath, root).count(os.sep) >= 5:
            dirnames[:] = []
        for f in filenames:
            for k, v in CONFIGS.items():
                if f.startswith(k):
                    found.add(v)
    return found


def uses_remix(approot, cache={}):
    """Whether app/routes/ under approot is Remix / React Router rather than Next.js."""
    if approot in cache:
        return cache[approot]
    try:
        names = os.listdir(approot)
    except OSError:
        names = []
    if any(n.startswith(("remix.config", "react-router.config")) for n in names):
        result = True
    else:
        deps = {}
        try:
            with open(os.path.join(approot, "package.json"), encoding="utf-8") as fh:
                pkg = json.load(fh)
            for k in ("dependencies", "devDependencies"):
                deps.update(pkg.get(k) or {})
        except (OSError, ValueError, AttributeError):
            pass
        if any(d.startswith("@remix-run/") or d in ("react-router", "@react-router/dev") for d in deps):
            result = True
        else:
            result = not any(n.startswith("next.config") for n in names)
    cache[approot] = result
    return result


def scan(root):
    inv = {"pages": [], "api": [], "jobs": [], "tables": [], "frameworks": set()}
    configs = config_frameworks(root)
    seen_tables = set()
    sql_seen, sql_tables = set(), []
    for p in files(root):
        rel = os.path.relpath(p, root)
        parts = rel.split(os.sep)
        fname = parts[-1]
        if TEST_FILE.search(fname):
            continue

        # Remix / React Router file routes (app/routes/...)
        ri = len(parts) - 1 - parts[::-1].index("routes") if "routes" in parts[:-1] else -1
        if (ri >= 1 and parts[ri - 1] == "app" and fname.endswith(PAGE_EXT) and not fname.startswith("+")
                and uses_remix(os.path.join(root, *parts[:ri - 1]))):
            route = remix_route(parts[ri + 1:])
            if route is not None:
                inv["frameworks"].add("Remix / React Router")
                text = read(p)
                if re.search(r"export\s+default\b", text) or not re.search(r"export\s+(?:async\s+)?(?:function|const)\s+(loader|action)\b", text):
                    inv["pages"].append({"route": route, "file": rel})
                else:  # resource route: loader/action, no UI
                    methods = (["GET"] if re.search(r"export\s+(?:async\s+)?(?:function|const)\s+loader\b", text) else []) + \
                              (["POST"] if re.search(r"export\s+(?:async\s+)?(?:function|const)\s+action\b", text) else [])
                    inv["api"].append({"route": route, "methods": methods, "file": rel})
            continue

        # Next.js app router (page.* / route.* under app/)
        stem = fname.split(".")[0]
        if "app" in parts[:-1] and stem in ("page", "route") and fname.endswith(PAGE_EXT):
            i = len(parts) - 1 - parts[::-1].index("app")
            segs = clean_segments(parts[i + 1:-1])
            if segs is not None:
                if stem == "page":
                    inv["frameworks"].add("Next.js app router")
                    inv["pages"].append({"route": url(segs), "file": rel})
                else:
                    inv["api"].append({"route": url(segs), "methods": http_methods(read(p)), "file": rel})
            continue

        # Next.js pages router / Astro / Nuxt (pages/...)
        if "pages" in parts[:-1] and fname.endswith(PAGE_EXT) and "components" not in parts:
            i = len(parts) - 1 - parts[::-1].index("pages")
            segs = clean_segments(parts[i + 1:-1])
            name = os.path.splitext(fname)[0]
            if segs is not None and not name.startswith("_"):
                route = url(segs + ([] if name == "index" else [name]))
                is_api = bool(segs) and segs[0] == "api"
                astro = fname.endswith(".astro") or "Astro" in configs
                if astro:
                    inv["frameworks"].add("Astro")
                    is_api = is_api or fname.endswith((".ts", ".js"))  # Astro endpoints
                elif fname.endswith(".vue"):
                    inv["frameworks"].add("Nuxt")
                else:
                    inv["frameworks"].add("Next.js pages router")
                if is_api:
                    inv["api"].append({"route": route, "methods": http_methods(read(p), pages_api=not astro), "file": rel})
                else:
                    inv["pages"].append({"route": route, "file": rel})
            continue

        # SvelteKit (src/routes/.../+page.svelte, +server.ts)
        if "routes" in parts[:-1] and fname.startswith("+"):
            i = len(parts) - 1 - parts[::-1].index("routes")
            segs = clean_segments(parts[i + 1:-1])
            if segs is not None:
                if fname == "+page.svelte":
                    inv["frameworks"].add("SvelteKit")
                    inv["pages"].append({"route": url(segs), "file": rel})
                elif stem == "+server":
                    inv["frameworks"].add("SvelteKit")
                    inv["api"].append({"route": url(segs), "methods": http_methods(read(p)), "file": rel})
            continue

        if fname.endswith(SERVER_EXT):
            text = read(p)
            client = bool(AXIOS.search(text))
            for obj, m, route in HTTP.findall(text):
                if route.startswith("/") and not (client and obj.lower() == "api"):
                    inv["api"].append({"route": route, "methods": [m.upper()], "file": rel})
            for block in FASTIFY_ROUTE.findall(text):
                u = re.search(r"""\b(?:url|path)\s*:\s*['"`]([^'"`]+)""", block)
                ms = re.search(r"""\bmethod\s*:\s*(\[[^\]]*\]|['"`]\w+['"`])""", block)
                if u and ms and u.group(1).startswith("/"):
                    methods = sorted(x.upper() for x in re.findall(r"""['"`](\w+)['"`]""", ms.group(1)))
                    inv["api"].append({"route": u.group(1), "methods": methods, "file": rel})
            for m, route in FASTAPI.findall(text):
                if route.startswith("/"):
                    inv["api"].append({"route": route, "methods": [m.upper()], "file": rel})
            ctrl = NEST_CTRL.search(text)
            if ctrl:
                inv["frameworks"].add("NestJS")
                prefix = (ctrl.group(1) or ctrl.group(2) or "").strip("/")
                for m, sub in NEST_ROUTE.findall(text):
                    route = "/" + "/".join(x for x in (prefix, (sub or "").strip("/")) if x)
                    inv["api"].append({"route": route, "methods": [m.upper()], "file": rel})
            for t in DRIZZLE.findall(text):
                if t not in seen_tables:
                    seen_tables.add(t)
                    inv["tables"].append({"table": t, "file": rel})
            if JOB.search(text):
                inv["jobs"].append({"job": os.path.splitext(fname)[0], "file": rel, "source": "code"})

        if fname.endswith(".prisma"):  # schema.prisma or a prismaSchemaFolder
            for t in PRISMA_MODEL.findall(read(p)):
                if t not in seen_tables:
                    seen_tables.add(t)
                    inv["tables"].append({"table": t, "file": rel})
        if fname.endswith(".sql"):
            for t in SQL_TABLE.findall(read(p)):
                if t not in sql_seen:
                    sql_seen.add(t)
                    sql_tables.append({"table": t, "file": rel})
        if fname == "vercel.json":
            try:
                for c in json.loads(read(p)).get("crons", []):
                    inv["jobs"].append({"job": c.get("path"), "file": rel, "source": "vercel cron " + c.get("schedule", "")})
            except (ValueError, AttributeError):
                pass

    if not inv["tables"]:
        inv["tables"] = sql_tables  # raw SQL only when there is no ORM schema
    # Config files name the framework; layout detail ("app router") is kept when it agrees.
    for c in configs:
        if not any(f.startswith(c) or c in f for f in inv["frameworks"]):
            inv["frameworks"].add(c)
    if "Astro" in configs:
        inv["frameworks"].discard("Next.js pages router")
    inv["pages"] = dedupe(inv["pages"])
    inv["api"] = dedupe(inv["api"])
    inv["frameworks"] = sorted(inv["frameworks"])
    return inv


def dedupe(rows):
    """One row per (route, file); methods from repeated matches are merged."""
    uniq = {}
    for row in rows:
        key = (row["route"], row["file"])
        if key in uniq and "methods" in row:
            merged = set(uniq[key]["methods"]) | set(row["methods"])
            if len(merged) > 1:
                merged.discard("?")
            uniq[key]["methods"] = sorted(merged)
        else:
            uniq.setdefault(key, dict(row))
    return sorted(uniq.values(), key=lambda r: (r["route"], r["file"]))


def markdown(inv):
    out = [f"Frameworks: {', '.join(inv['frameworks']) or 'unknown'}", ""]
    out += [f"## Pages ({len(inv['pages'])})", "", "| Route | File |", "| --- | --- |"]
    out += [f"| `{r['route']}` | {r['file']} |" for r in inv["pages"]]
    out += ["", f"## API ({len(inv['api'])})", "", "| Route | Methods | File |", "| --- | --- | --- |"]
    out += [f"| `{r['route']}` | {', '.join(r.get('methods') or ['?'])} | {r['file']} |" for r in inv["api"]]
    out += ["", f"## Jobs ({len(inv['jobs'])})", ""]
    out += [f"- {j['job']} ({j['source']}) — {j['file']}" for j in inv["jobs"]] or ["(none found)"]
    out += ["", f"## Tables ({len(inv['tables'])})", ""]
    out += [", ".join(t["table"] for t in inv["tables"]) or "(none found)"]
    return "\n".join(out)


# ---- diff against a previous audit ---------------------------------------

def items(inv):
    """{(kind, name): methods-or-None} from an inventory dict."""
    out = {}
    for r in inv.get("pages", []):
        out[("page", r["route"])] = None
    for r in inv.get("api", []):
        key = ("api", r["route"])
        out[key] = sorted(set(out.get(key) or []) | set(r.get("methods") or ["?"]))
    for j in inv.get("jobs", []):
        out[("job", str(j.get("job")))] = None
    for t in inv.get("tables", []):
        out[("table", t["table"])] = None
    return out


def parse_markdown(text):
    """Rebuild an inventory dict from inventory.py Markdown, also when embedded in an audit file."""
    inv = {"pages": [], "api": [], "jobs": [], "tables": []}
    section = None
    for line in text.splitlines():
        h = re.match(r"^#+\s*(\w+)", line)
        if h:
            section = {"pages": "pages", "api": "api", "jobs": "jobs", "tables": "tables"}.get(h.group(1).lower())
            continue
        s = line.strip()
        if not s or section is None:
            continue
        if section == "pages":
            m = re.match(r"^\|\s*`([^`]+)`\s*\|", s)
            if m:
                inv["pages"].append({"route": m.group(1), "file": ""})
        elif section == "api":
            m = re.match(r"^\|\s*`([^`]+)`\s*\|([^|]*)\|", s)
            if m:
                methods = [x.strip() for x in m.group(2).split(",") if x.strip()]
                inv["api"].append({"route": m.group(1), "methods": methods, "file": ""})
        elif section == "jobs":
            m = re.match(r"^- (.+?) \(", s)
            if m:
                inv["jobs"].append({"job": m.group(1), "file": "", "source": ""})
        elif section == "tables" and not s.startswith("("):
            inv["tables"] += [{"table": t.strip(), "file": ""} for t in s.split(",") if t.strip()]
    if not any(inv.values()):
        return None
    return inv


def load_previous(path):
    text = read(path, limit=10_000_000)
    try:
        data = json.loads(text)
        if isinstance(data, dict):
            return data.get("inventory", data)
    except ValueError:
        pass
    return parse_markdown(text)


def diff(prev, cur):
    a, b = items(prev), items(cur)
    added = [{"kind": k, "item": n} for (k, n) in sorted(set(b) - set(a))]
    removed = [{"kind": k, "item": n} for (k, n) in sorted(set(a) - set(b))]
    changed = [{"kind": k, "item": n, "before": a[(k, n)], "after": b[(k, n)]}
               for (k, n) in sorted(set(a) & set(b)) if k == "api" and a[(k, n)] != b[(k, n)]]
    return {"added": added, "removed": removed, "changed": changed}


def diff_markdown(d, against):
    out = [f"## Changes since {against}", "",
           f"Added: {len(d['added'])} · Removed: {len(d['removed'])} · Methods changed: {len(d['changed'])}", ""]
    if not (d["added"] or d["removed"] or d["changed"]):
        return "\n".join(out + ["No changes."])
    out += ["| Change | Kind | Item |", "| --- | --- | --- |"]
    out += [f"| added | {r['kind']} | `{r['item']}` |" for r in d["added"]]
    out += [f"| removed | {r['kind']} | `{r['item']}` |" for r in d["removed"]]
    out += [f"| methods {', '.join(r['before'])} → {', '.join(r['after'])} | {r['kind']} | `{r['item']}` |"
            for r in d["changed"]]
    return "\n".join(out)


def main(argv=None):
    argv = list(sys.argv[1:] if argv is None else argv)
    previous = None
    if "--diff" in argv:
        i = argv.index("--diff")
        if i + 1 >= len(argv):
            print("--diff needs a file", file=sys.stderr)
            return 2
        previous = argv[i + 1]
        del argv[i:i + 2]
    args = [a for a in argv if not a.startswith("--")]
    root = args[0] if args else "."
    if not os.path.isdir(root):
        print(f"not a directory: {root}", file=sys.stderr)
        return 2
    inv = scan(root)
    d = None
    if previous:
        prev = load_previous(previous) if os.path.isfile(previous) else None
        if prev is None:
            print(f"no inventory found in {previous}", file=sys.stderr)
            return 2
        d = diff(prev, inv)
    if "--json" in argv:
        if d is not None:
            inv["diff"] = dict(d, against=previous)
        print(json.dumps(inv, indent=2))
    else:
        print(markdown(inv))
        if d is not None:
            print("\n" + diff_markdown(d, os.path.basename(previous)))
    return 0


if __name__ == "__main__":
    sys.exit(main())