Files
ssw-platform/scripts/fe-api-inventory.py
T
sukyboor 9771fa844d init: 尚数网平台 JNPF 7.0 兼容后端(多应用 + 面 A/面 B 双契约)
- 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/:前端接口清单、页面依赖反查、运行时探针
2026-10-30 22:08:31 +08:00

317 lines
10 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fe-api-inventory.py —— 从 JNPF 官方前端 api 层抽取「端点权威清单」。
为什么要有这把尺子
------------------
本仓此前靠**读 Java Controller** 推断面 B 端点,那是「服务端提供了什么」;
而前端 `src/api/**/*.ts` 写的是「前端**实际怎么调**」—— URL 大小写、
method、路径参数位置、query/body 归属。两者不是一回事,后者才是契约。
抽取规则(覆盖 JNPF 7.0 前端的两种写法)
--------------------------------------
enum Api { Prefix = '/api/permission/Users' }
defHttp.get({ url: Api.Prefix, params }) -> GET /api/permission/Users
defHttp.put({ url: `${Api.Prefix}/${data.id}`, data }) -> PUT /api/permission/Users/{id}
用法
----
python3 scripts/fe-api-inventory.py --fe <前端 src 目录> # 打清单 TSV
python3 scripts/fe-api-inventory.py --fe <...> --diff <契约.md> # 与本仓契约差分
python3 scripts/fe-api-inventory.py --fe <...> --diff <...> --group # 差分按前缀汇总
退出码:0 正常 / 2 前置错误
"""
import os
import re
import sys
RE_HTTP_CALL = re.compile(r"\b(defHttp|reportHttp)\s*\.\s*(get|post|put|delete|patch|request)\s*\(")
RE_ENUM = re.compile(r"enum\s+(\w+)\s*\{([^}]*)\}", re.S)
RE_ENUM_ITEM = re.compile(r"(\w+)\s*=\s*(['\"`])(.*?)\2", re.S)
RE_FUNC = re.compile(r"(?:export\s+)?(?:async\s+)?function\s+(\w+)|(?:export\s+)?const\s+(\w+)\s*=")
def read(path):
with open(path, "r", encoding="utf-8", errors="replace") as fh:
return fh.read()
def line_of(text, pos):
return text.count("\n", 0, pos) + 1
def parse_enums(text):
"""返回 {枚举名: {成员名: 字面值}}。"""
out = {}
for m in RE_ENUM.finditer(text):
name, body = m.group(1), m.group(2)
items = {}
for im in RE_ENUM_ITEM.finditer(body):
items[im.group(1)] = im.group(3)
if items:
out[name] = items
return out
def match_brace(text, start):
"""text[start] == '{' ⇒ 返回配对 '}' 的下标;失败返回 -1。"""
depth = 0
i = start
in_str = None
while i < len(text):
ch = text[i]
if in_str:
if ch == "\\":
i += 2
continue
if ch == in_str:
in_str = None
elif ch in "'\"`":
in_str = ch
elif ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return i
i += 1
return -1
def extract_url_expr(obj):
"""从 `{ url: XXX, ... }` 的对象体里取出 url 的表达式文本。"""
m = re.search(r"\burl\s*:\s*", obj)
if not m:
return None
i = m.end()
# 跳过空白
while i < len(obj) and obj[i] in " \t\r\n":
i += 1
if i >= len(obj):
return None
ch = obj[i]
if ch in "'\"`":
quote = ch
j = i + 1
while j < len(obj):
if obj[j] == "\\":
j += 2
continue
if obj[j] == quote:
return obj[i : j + 1]
j += 1
return obj[i:]
# 非字面量:吃到深度 0 的逗号或对象结束
depth = 0
j = i
while j < len(obj):
c = obj[j]
if c in "([{":
depth += 1
elif c in ")]}":
if depth == 0:
break
depth -= 1
elif c == "," and depth == 0:
break
j += 1
return obj[i:j].strip()
def resolve_path(expr, enums):
"""把 url 表达式解析成真实路径模板。"""
if not expr:
return None
expr = expr.strip()
# 1) 纯字面量
if len(expr) >= 2 and expr[0] == expr[-1] and expr[0] in "'\"`":
body = expr[1:-1]
else:
body = expr
# 2) 内联 `enum Api { ... }` 之内的成员:先整体换掉 ${Api.X} / Api.X
for _ename, items in enums.items():
for key, val in items.items():
body = body.replace("${%s.%s}" % (_ename, key), val)
body = body.replace("${Api.%s}" % key, val)
body = re.sub(r"\b%s\.%s\b" % (re.escape(_ename), re.escape(key)), val, body)
body = re.sub(r"\bApi\.%s\b" % re.escape(key), val, body)
# 3) 剩下的 ${...} 是运行时变量 ⇒ 归一成 {param}
body = re.sub(r"\$\{[^}]*\}", "{param}", body)
# 4) 去掉查询串残留与重复斜杠
body = body.split("?")[0]
body = re.sub(r"/{2,}", "/", body)
if not body.startswith("/"):
return None
if len(body) > 1 and body.endswith("/"):
body = body[:-1]
return body
def scan_fe(fe_root):
"""扫 <fe_root>/api/**/*.ts(无 api 子目录则扫全树)。"""
base = os.path.join(fe_root, "api")
if not os.path.isdir(base):
base = fe_root
rows = []
for dirpath, _dirnames, filenames in os.walk(base):
for fn in sorted(filenames):
if not fn.endswith(".ts") or fn.endswith(".d.ts"):
continue
ap = os.path.join(dirpath, fn)
text = read(ap)
if "defHttp" not in text and "reportHttp" not in text:
continue
enums = parse_enums(text)
for m in RE_HTTP_CALL.finditer(text):
verb, meth = m.group(2), m.group(2)
if verb == "request":
continue # request({url, method}) 少见,先不猜 method
# 找调用参数里的对象体
tail = text[m.end() :]
brace = tail.find("{")
if brace < 0:
continue
end = match_brace(tail, brace)
if end < 0:
continue
obj = tail[brace + 1 : end]
expr = extract_url_expr(obj)
path = resolve_path(expr, enums)
if not path:
continue
# 归属函数名:向上找最近的 function/const
head = text[: m.start()]
fname = ""
for fm in RE_FUNC.finditer(head):
fname = fm.group(1) or fm.group(2) or fname
rel = os.path.relpath(ap, fe_root)
rows.append(
{
"method": meth.upper(),
"path": path,
"func": fname,
"where": "%s:%d" % (rel, line_of(text, m.start())),
}
)
# 去重(同 method+path 只留第一条)
seen = set()
uniq = []
for r in rows:
k = (r["method"], r["path"])
if k in seen:
continue
seen.add(k)
uniq.append(r)
uniq.sort(key=lambda r: (r["path"], r["method"]))
return uniq
def norm(p):
"""路径归一:{xxx} 一律换成 {},便于跨端比对。"""
return re.sub(r"\{[^}]*\}", "{}", p)
def read_contract_endpoints(contract_path):
"""读 docs/contract.md 的 [ENDPOINT] 段。"""
out = []
in_sec = False
for raw in read(contract_path).splitlines():
line = raw.strip()
if line.startswith("[ENDPOINT]"):
in_sec = True
continue
if in_sec and line.startswith("[") and line.endswith("]"):
break
if not in_sec or not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) < 3:
continue
out.append({"face": parts[0], "method": parts[1], "path": parts[2]})
return out
def main(argv):
fe = None
diff = None
group = False
i = 1
while i < len(argv):
a = argv[i]
if a == "--fe" and i + 1 < len(argv):
fe = argv[i + 1]
i += 2
continue
if a == "--diff" and i + 1 < len(argv):
diff = argv[i + 1]
i += 2
continue
if a == "--group":
group = True
i += 1
continue
if a in ("-h", "--help"):
print(__doc__)
return 0
sys.stderr.write("fe-api-inventory: 未知参数 %r\n" % a)
return 2
if not fe or not os.path.isdir(fe):
sys.stderr.write("fe-api-inventory: --fe 必须是存在的前端 src 目录\n")
return 2
rows = scan_fe(fe)
if not diff:
print("METHOD\tPATH\tFUNC\tWHERE")
for r in rows:
print("%s\t%s\t%s\t%s" % (r["method"], r["path"], r["func"], r["where"]))
sys.stderr.write("共 %d 条端点\n" % len(rows))
return 0
if not os.path.isfile(diff):
sys.stderr.write("fe-api-inventory: --diff 指向的契约文件不存在:%s\n" % diff)
return 2
be = read_contract_endpoints(diff)
# 前端发 Vue-Version: 3 ⇒ 只会走面 B;面 B 端点 = face in (B, AB)
be_b = [e for e in be if e["face"] in ("B", "AB")]
be_keys = {(e["method"].upper(), norm(e["path"])) for e in be_b}
fe_keys = {(r["method"], norm(r["path"])) for r in rows}
missing = [r for r in rows if (r["method"], norm(r["path"])) not in be_keys]
extra = [(m, p) for (m, p) in sorted(be_keys) if (m, p) not in fe_keys]
print("== 前端端点总数 %d / 本仓面 B 已实现 %d / 覆盖 %d ==" % (
len(rows), len(be_b), len(rows) - len(missing)))
print()
if group:
buckets = {}
for r in missing:
seg = [s for s in r["path"].split("/") if s and s != "api"]
key = "/".join(seg[:2]) if seg else "(root)"
buckets.setdefault(key, []).append(r)
print("== 未实现端点按前缀汇总(%d 组)==" % len(buckets))
for key in sorted(buckets, key=lambda k: (-len(buckets[k]), k)):
print("%5d %s" % (len(buckets[key]), key))
print()
print("== 本仓已实现但前端不调用(面 B)==")
for m, p in extra:
print("%-6s %s" % (m, p))
print()
print("== 前端调用但本仓未实现(按路径排序)==")
for r in missing:
print("%-6s %-60s %s" % (r["method"], r["path"], r["where"]))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))