- axum 0.8 + pglite:12 张表,多应用按 App-Code 头解析 f_system_id 隔离 - 面 A(ssw/react 形状)+ 面 B(官方 JNPF 形状,Vue-Version: 3)双契约并存 - 业务模块 asset/DataResource;面 B 用户 CRUD 9 条已落地 - 六道闸门 + 两把运行时尺子(perm-smoke 43 / perm-smoke-jnpf 23) - scripts/:前端接口清单、页面依赖反查、运行时探针
188 lines
6.7 KiB
Python
188 lines
6.7 KiB
Python
#!/usr/bin/env python3
|
||
"""fe-page-deps.py —— **页面 → 接口** 的依赖清单(驱动「从 web 端逐个 api 突破」)。
|
||
|
||
前端页面不直接写 URL,而是 `import { getUserList } from '#/api/permission/user'`。
|
||
所以「打开某个页面会打哪些接口」这件事,**只能靠 import 图反推**。
|
||
|
||
输入:
|
||
- `docs/fe/endpoints.tsv`(`fe-api-inventory.py` 产出:METHOD/PATH/FUNC/WHERE)
|
||
- 前端 `apps/*/src/views/**/*.vue`(页面)与 `apps/*/src/api/**/*.ts`(接口定义)
|
||
|
||
输出:每个页面 → 它直接调用(含经 composable 一层转发)的接口列表,按 METHOD+PATH 去重。
|
||
|
||
用法:
|
||
python3 scripts/fe-page-deps.py # 全部页面汇总
|
||
python3 scripts/fe-page-deps.py --page permission/user/index
|
||
python3 scripts/fe-page-deps.py --tsv docs/fe/page-deps.tsv
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import collections
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||
ENDPOINTS = ROOT / "docs" / "fe" / "endpoints.tsv"
|
||
FE_ROOT = pathlib.Path(
|
||
"/Users/xs/Desktop/workspace/jnpf/7.0/frontend/web/jnpf-web-monorepo-framework/apps"
|
||
)
|
||
|
||
# `import { a, b as c } from '#/api/permission/user'`
|
||
IMPORT_API = re.compile(
|
||
r"""import\s*\{([^}]*)\}\s*from\s*['"]#/api/([^'"]+)['"]""", re.S
|
||
)
|
||
IMPORT_ANY = re.compile(r"""from\s*['"]([^'"]+)['"]""")
|
||
|
||
|
||
def load_endpoints() -> dict[tuple[str, str], tuple[str, str]]:
|
||
"""(api文件路径去扩展名, 函数名) -> (METHOD, PATH)。"""
|
||
out: dict[tuple[str, str], tuple[str, str]] = {}
|
||
with ENDPOINTS.open(encoding="utf-8") as fh:
|
||
fh.readline()
|
||
for line in fh:
|
||
p = line.rstrip("\n").split("\t")
|
||
if len(p) < 4:
|
||
continue
|
||
method, path, func, where = p[0], p[1], p[2], p[3]
|
||
fpath = where.rsplit(":", 1)[0]
|
||
key = (fpath[: -len(".ts")] if fpath.endswith(".ts") else fpath, func)
|
||
out[key] = (method, path)
|
||
return out
|
||
|
||
|
||
def parse_names(block: str) -> list[str]:
|
||
names = []
|
||
for part in block.split(","):
|
||
part = part.strip()
|
||
if not part:
|
||
continue
|
||
# `a as b` -> 用 b(本地名)
|
||
if " as " in part:
|
||
part = part.split(" as ")[-1].strip()
|
||
names.append(part)
|
||
return names
|
||
|
||
|
||
def page_imports(vue: pathlib.Path) -> list[tuple[str, str]]:
|
||
"""返回 [(api文件去扩展名, 函数名)],只算 `#/api/...` 的具名导入。"""
|
||
text = vue.read_text(encoding="utf-8", errors="replace")
|
||
hits = []
|
||
for block, mod in IMPORT_API.findall(text):
|
||
mod = mod.strip()
|
||
for name in parse_names(block):
|
||
hits.append((mod, name))
|
||
return hits
|
||
|
||
|
||
def local_components(vue: pathlib.Path) -> list[pathlib.Path]:
|
||
"""同目录下被 import 的本地 .vue(如 `./Form.vue`)—— 它们也算该页面的依赖。"""
|
||
text = vue.read_text(encoding="utf-8", errors="replace")
|
||
out = []
|
||
for spec in IMPORT_ANY.findall(text):
|
||
if not spec.startswith("."):
|
||
continue
|
||
cand = (vue.parent / spec).resolve()
|
||
for suffix in ("", ".vue", ".ts"):
|
||
p = pathlib.Path(str(cand) + suffix)
|
||
if p.is_file():
|
||
out.append(p)
|
||
break
|
||
return out
|
||
|
||
|
||
def closure(vue: pathlib.Path, seen: set[pathlib.Path] | None = None) -> set[pathlib.Path]:
|
||
# 🔴 必须用 `is None` 判空:空 set 是 falsy,`seen or set()` 会让每层递归都拿到
|
||
# 一个**新的** set ⇒ 环形 import 时无限递归直到被 OOM kill(实测 SIGKILL 137)。
|
||
if seen is None:
|
||
seen = set()
|
||
vue = vue.resolve()
|
||
if vue in seen:
|
||
return seen
|
||
seen.add(vue)
|
||
for child in local_components(vue):
|
||
if child.suffix == ".vue":
|
||
closure(child, seen)
|
||
return seen
|
||
|
||
|
||
def endpoints_of(files: set[pathlib.Path], index: dict) -> list[tuple[str, str, str]]:
|
||
got: dict[tuple[str, str], str] = {}
|
||
for f in files:
|
||
for mod, func in page_imports(f):
|
||
# 页面写 `#/api/permission/user`,清单里记的是 `api/permission/user.ts`
|
||
# ⇒ 两边都要带/不带 `api/` 前缀各试一次。
|
||
hit = index.get((mod, func)) or index.get((f"api/{mod}", func))
|
||
if hit:
|
||
got[hit] = f"{mod}:{func}"
|
||
else:
|
||
got.setdefault(("?", f"{mod}#{func}"), f.name)
|
||
return [(m, p, src) for (m, p), src in sorted(got.items())]
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--page", help="只看某页,如 permission/user/index")
|
||
ap.add_argument("--tsv", help="明细写文件")
|
||
ap.add_argument("--missing", action="store_true", help="只列解析不到定义的导入")
|
||
args = ap.parse_args()
|
||
|
||
folder = ENDPOINTS.parent
|
||
index = load_endpoints()
|
||
|
||
pages = sorted(FE_ROOT.glob("*/src/views/**/*.vue"))
|
||
if not pages:
|
||
sys.exit(f"没找到页面:{FE_ROOT}")
|
||
if args.page:
|
||
pages = [p for p in pages if args.page in str(p)]
|
||
|
||
rows = []
|
||
for v in pages:
|
||
files = closure(v)
|
||
eps = endpoints_of(files, index)
|
||
real = [e for e in eps if e[0] != "?"]
|
||
unknown = [e for e in eps if e[0] == "?"]
|
||
rows.append((v, real, unknown))
|
||
|
||
if args.tsv:
|
||
out = pathlib.Path(args.tsv)
|
||
with out.open("w", encoding="utf-8") as fh:
|
||
fh.write("PAGE\tMETHOD\tPATH\tVIA\n")
|
||
for v, real, _ in rows:
|
||
for m, p, src in real:
|
||
fh.write(f"{v.relative_to(FE_ROOT)}\t{m}\t{p}\t{src}\n")
|
||
total = sum(len(r[1]) for r in rows)
|
||
print(f"明细已写 {out}({len(rows)} 页 / {total} 条页面-接口关系)")
|
||
|
||
if args.page or args.missing:
|
||
for v, real, unknown in rows:
|
||
print(f"\n### {v.relative_to(FE_ROOT)} ({len(real)} 条接口)")
|
||
for m, p, src in real:
|
||
print(f" {m:<6} {p:<52} ← {src}")
|
||
for _, p, _ in unknown:
|
||
print(f" ?? {p}")
|
||
return 0
|
||
|
||
# ---- 汇总:哪些页面依赖最多、哪些接口被最多页面共用 ----
|
||
print(f"{'页面':<52}{'接口数':>6}")
|
||
print("-" * 60)
|
||
for v, real, _ in sorted(rows, key=lambda r: -len(r[1]))[:25]:
|
||
print(f"{str(v.relative_to(FE_ROOT)):<52}{len(real):>6}")
|
||
print("-" * 60)
|
||
print(f"页面总数 {len(rows)},接口关系 {sum(len(r[1]) for r in rows)} 条")
|
||
|
||
shared: collections.Counter = collections.Counter()
|
||
for _, real, _ in rows:
|
||
for m, p, _ in real:
|
||
shared[(m, p)] += 1
|
||
print("\n被最多页面共用的接口(先做这些,收益最大):")
|
||
for (m, p), n in shared.most_common(15):
|
||
print(f" {n:>3} 个页面 {m:<6} {p}")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|