main
kangwenjing 2026-10-12 09:03:19 +08:00
parent 5cbe0cf0e1
commit 30d78998f1
2563 changed files with 419423 additions and 1 deletions

3
.idea/.gitignore vendored 100644
View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="pythonStudy.day10_inherit.exercise03.GraphicManager.__graphics" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

4
.idea/misc.xml 100644
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (LinearAlgebra)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/it-architecture.iml" filepath="$PROJECT_DIR$/.idea/it-architecture.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml 100644
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

185
README.md
View File

@ -1,2 +1,185 @@
# it-architecture
# 公司 IT 系统全景与数据流向平台
把原来那份单文件 `index.html`(公司 IT 系统全景图)升级成一个真正可运行的系统:
Python 后端 + SQLite 持久化 + 可配置前端,多人访问同一份数据,不再依赖浏览器 localStorage。
## 与原版页面的对应关系
| 原版页面 | 现在的去向 |
| --- | --- |
| ① 系统全景总览 | 保留为「系统全景总览」,字段编辑改为写库,所有人共享;新增「快捷入口」直达各系统 |
| ② 系统关系与业务链路 | **按要求删除**,其信息已并入数据流向图 |
| ③ 目标架构与迁移规划 | 改为**数据流向图**:带流动动画,且可直接拖拽摆放、拉线建流 |
| 系统交换明细 | **按要求移除**,该位置改为「Agent 布局总览图」占位页 |
| localStorage + 导出离线 HTML | 改为 SQLite + 配置备份 JSON 导入/导出 |
| 乐观锁单文档同步 | 改为按行 CRUD,附变更审计(谁在什么时候改了什么) |
## 目录结构
```
backend/ FastAPI + 标准库 sqlite3(无 ORM)
app/db.py 连接、建表、显式事务
app/seed.py 内置清单:3 层级 / 18 系统 / 6 数据类型 / 36 条数据流
app/services/ 指标生成(metrics)与图布局(graph)
app/routers/ content(层级/系统/类型/配置)、flows、graph、backup
tests/ 63 条 pytest
frontend/ Vue 3 + Vite + TS + Tailwind + Pinia(组件风格取自 sub2api)
src/components/ common / icons / layout / panorama / flow
src/views/ 全景、数据流向图、Agent 布局总览图(占位)、配置、审计
```
## 启动
```bash
./start.sh # 生产式:单进程提供 API + 页面,http://localhost:8787
./dev.sh # 开发式:后端 8787 热重载 + 前端 5273 HMR
python3 -m pytest -q # 后端测试(在 backend/ 目录下)
npm run typecheck # 前端类型检查(在 frontend/ 目录下)
```
数据库默认 `backend/panorama.db`,用 `DB_PATH=/path/to.db` 可改位置。直接复制该文件即整库备份。
## 数据模型
- `layers` 层级(通用 / 部门业务 / 底座),决定全景图分区
- `systems` 系统清单:状态、技术栈、地址、域名、负责人、说明、`impl_time`(实现时间)、
`entry_enabled`(是否展示快捷入口),`tier` 决定数据流向图所在列
- `flow_types` 数据类型:决定连线颜色与线型,取值遵循下面「一眼看出主流向」一节的统一图例
- `data_flows` 数据流:起止系统、传输内容、方向、**触发间隔 / 单次条数 / 单批体积 / 时延 / 同步异步 / 高峰时段**
- `flow_metrics` 按小时聚合的 batches、records、bytes、errors、latency
- `settings` 平台配置(含 `editing_enabled` 全站编辑开关、`flow_route_style` 连线线型),`audit_logs` 变更审计
## 系统跳转入口与实现时间
「系统配置 · 系统跳转入口」是一行一个系统的编辑表:跳转地址、是否展示快捷入口、实现时间。
保存后「系统全景总览」顶部出现「快捷入口」一排按钮,点中系统卡片时右侧也会出现「访问系统」。
地址留空则退回用域名打开,两者都没填时这一排会给出填写指引而不是整排消失。
地址不带协议前缀(如 `oa.example.com`)时自动补 `http://`,否则浏览器会当成本站相对路径跳错页面。
「实现时间」是自由文本(`2024-06 上线`、`2023 Q4 立项 / 2024-08 验收` 都行),
在系统详情栏和跳转入口表两处都能填,同一个字段。
## 系统名称随时可改
名称是普通字段,不是建档后就锁死的表头:全景总览选中系统后,右侧详情栏第一个输入框就是「系统名称」;
「系统配置 · 系统跳转入口」那一行的系统名也能直接改,回车或失焦即保存。
改名只动展示名,`key` 作为主键不变,数据流的起止点、画布上的摆放位置都不受影响;
全景图、数据流向图、快捷入口、汇报清单读的都是改名后的名字。
空白名称前端不提交、后端返 `422`,超长名称截到 80 字,改动照旧进变更审计。
## 汇报模式与图片导出
数据流向图工具条上的「汇报模式」把画布换成整屏演示视图(`components/flow/FlowPresentation.vue`):
- 图占满整屏,卡片、连线、层级列头按可用空间放大,不再有统计卡与工具条抢位置
- 「线型」三选一(折线 / 曲线 / 直线,默认折线),当场切给听众看,选中的存进 `flow_route_style`
- 「突出主流向」默认打开:自右向左的回流链路压到很淡,先看清 ①→②→③→④ 这条主干
- 「流向」分步按钮 ①→② / ②→③ / ③→④ / 跨列,一次只讲一跳,其余链路退到底色,
右侧清单同步只列这一跳的链路,讲完点「全部」回到整图
- 关系名称默认不显示(挑中一跳、悬停或选中卡片时才出现),要逐条念就勾「显示全部关系名称」
- 右侧「汇报清单」两个标签页:「业务链路」按数据类型分组编号,从上往下念就是一条条业务线,
点一条即在画布上聚焦;「系统清单」按层级列分组,附每个系统的入向 / 出向链路数与尚未接入的系统
- 顶部图例可点(只看某一类链路),可关流动动画、切速度;`Esc` 或「退出」回到编辑视图
- 「导出图片」出 2× PNG(可直接贴 PPT),「SVG」出矢量图:导出的就是屏幕上这套几何,
含标题、统计、图例、层级列与生成时间,走线与线型跟着屏幕上选的来(`components/flow/flowExport.ts`)
## 一眼看出主流向
四十条链路挤在一张图上,靠的是四件事(都在 `components/flow/flowLayout.ts`):
- **三种线型**:`折线`(默认,直角走线,线段走列与列之间的走廊,交叉最少)、`曲线`(弧线,画面柔和)、
`直线`(两点直线,最短最直接,链路多时交叉会变多)。走线偏好存 `settings.flow_route_style`
- **走廊走线**:每条链路只走它终点前面那条走廊,同走廊的链路按高度排槽位,走廊内部不再互相交叉;
同列互传的链路走列旁的水沟,不从中间卡片上压过去
- **边绑定**:汇入同一个系统的同类链路(例如十来个系统都去 UniHub 做 SSO 票据校验)共用走廊里同一条
干线,到卡片前才散成各自的接入点,画面上先看到一股粗绳、再看到十几条支线;折线共用干线,
曲线在干线上的同一点汇聚,直线保持一对一。干线只在两条以上链路真正重叠的那一段画出来
- **列内重心排序**:卡片按与它通信的卡片的平均高度来回微调(左右各扫三轮),互相调用的系统自然对上,
大部分链路变成短横跳而不是斜穿四列;排序种子与并列规则固定,每次打开都是同一张图
主次靠墨量分:线条宽 1~3.4px、不透明度 32%~92% 都由同步节奏换算,分钟级高频链路粗而实,
夜间批量细而淡;汇报模式的「突出主流向」再把回流链路压到 18%。
颜色与线型是一套统一图例(`components/flow/flowStyle.ts`,种子数据与配置页都按它取值):
| 编码 | 含义 | 线型 |
| --- | --- | --- |
| 蓝 | API / 同步调用(核心业务链路、底座能力调用) | 实线 |
| 紫 | 鉴权 / MCP 取数(统一认证、智能体取数) | 实线 / 点划线(定时) |
| 绿 | 异步消息 / 事件推送 | 虚线 |
| 灰 | 定时任务 / 归档沉淀 | 点划线 |
| 红 | 人工操作 / 线下流程 | 点划线 |
线型本身即节奏:实线同步调用、虚线异步消息、点划线定时任务或人工、点线低频参考链路。
图例在编辑视图、汇报模式和导出的 SVG 里都由同一个组件画(`components/flow/FlowLegend.vue`),
颜色前面带真实线型的小样,不会出现图例和画面对不上。
卡片也按层级上色:入口青、中枢绿、业务蓝、底座橙,列带只包到自己卡片的高度,
两系统的入口层不再拖出一条空白长条;入向 / 出向数量挪到卡片右上角的小角标,卡面只剩系统名和归属。
## 只读模式
「系统配置 · 平台配置」里的「允许编辑」是全站开关。关掉后:
- 各页面隐藏新增 / 编辑 / 删除入口,表单只读,顶部出现「只读模式」标记
- 后端所有写接口返回 `423`,被拒绝的请求不会写入任何数据,也不会留下审计记录
- 数据流向图的拖拽摆放、拉线建流、恢复自动排列同样被锁住(画布仍可查看与播放动画)
- 读取与指标接口不受影响;`PATCH /api/settings` 始终开放,否则就无法解锁
## 数据流动情况是怎么定出来的
初始 36 条链路按业务语义分为 6 类,节奏取自真实系统常见形态,可在界面上随时改:
| 类型 | 典型链路 | 节奏设定 |
| --- | --- | --- |
| 核心业务链路 | PMS 预算闸门 ⇄ OA、OA 合同→OMS、SCC 归档转订单、报销→财务助理→金蝶 | 10~60 分钟批量,同步为主 |
| 移动端入口 / 消息 | OA→企微 待办与收款群通知、企微→财务助理 PDF 报销、企微→EDRS 填报提醒 | 5 分钟级高频小包 |
| MCP 取数(Agent) | unibot ⇄ PMS / OMS / SCC / EDRS、unibot ⇄ UniTensor 算力 | 小时级取数,单次数据量大 |
| 底座能力调用 | 财务助理→k3s OCR/对象存储、docs→UniTensor 推理、DMS→镜像仓库 | 分钟级,单批体积跨度大 |
| 统一认证 SSO | 各业务系统→UniHub 票据校验 | 高频极小包(约 4 KB) |
| 归档 / 知识沉淀 | OA→NAS 盖章合同原件、docs→ekb 知识沉淀、unibot→ekb 检索 | 低频大文件 |
历史流量不是写死的常量:`services/metrics.py` 用每条链路的节奏乘以一条工作时段曲线(含午休回落、夜间低谷、周末系数)生成 30 天逐小时记录,并按固定随机种子加抖动,因此重跑结果稳定;`POST /api/metrics/tick` 再往当前小时累加增量,让看板上的数字持续变化。
## 数据流向图是可以直接编辑的画布
图上的东西就在图上改,不用绕去配置页:
- 「选择 / 摆放」模式下按住系统卡片就能拖,松手即落位;拖到别的列会同时改掉它的层级,列带高亮提示会落到哪一列
- 「连线」模式下从一张卡片拖到另一张卡片,松手后弹出已填好起止点的数据流表单,补一个关系名称就建好这条链路;不想拖也行,先点起点卡片再点终点卡片
- 工具条上的「新增系统」在当前列补一张卡片;「自动整理」清掉全部手动位置回到自动排列
- 位置存在 `systems.flow_x / flow_y`,刷新与换人打开都是同一张图;`PUT /api/graph/layout` 一次拖拽记一条审计,`POST /api/graph/layout/reset` 恢复自动
## 流动感是怎么实现的
这一屏只回答"谁在什么时候往哪儿传什么",因此画面上没有任何流量数字(条数、体积、时延、本小时都在「系统配置 · 数据流」和历史趋势页看):
- 粒子密度与速度取自链路节奏:`cadence = √(1 - log(间隔秒) 映射到 30 秒~6 小时)`,分钟级链路密而快,夜间批量疏而慢,同步调用再加一点
- 动画时长按路径长度与强度反比计算,再除以全局速度倍率;每条链路的粒子用负 `begin` 偏移错开,均匀铺在路径上而不是首尾相接
- 连线标签只显示关系名称,卡片上只显示入向 / 出向链路数
- 顶部可关动画(投屏/低配设备)、调 0.25×~3× 速度、按数据类型筛选
图本身是自适应的(`components/flow/flowLayout.ts`),换窗口大小不会把系统卡片切掉:
- 列间距按面板宽度分配,行间距按面板高度分配;装不下时整图等比缩小(下限 0.68),省出来的宽度回补给列间距
- 同一侧的多条连线在卡片边缘按对端位置排槽位,八条 SSO 链路各走各的接入点,不会挤成一团
- 连线说明逐条摆放:先按序号在本条曲线上取位,再依次试其他位置,避开系统卡片与已放好的说明;实在放不下就先隐藏,鼠标移到连线或选中对应系统时再出现
- 右侧详情栏只在选中连线/系统时出现,平时让图占满整宽;选中系统时给出上下游链路清单,可直接点进某一条
- 每列顶部标出层级名与该列的系统数,卡片上的状态点含义写在图例行右侧,不用回全景图对照
- 没有任何筛选时,还没接上链路的系统也会留在画布上(它们正是等着被连线的对象);一旦筛选就只显示命中子图
## 接口一览
`/api/layers` `/api/systems` `/api/flow-types` `/api/flows` 均为标准 REST;
读模型 `/api/graph`(含拓扑计数 `counts`)`/api/metrics/summary|hourly|live|flows/{id}` `/api/audit`;
画布布局 `PUT /api/graph/layout` `POST /api/graph/layout/reset`;
配置 `/api/settings`;备份 `/api/backup`(`mode` 支持 `replace` / `merge`)。
写请求通过 `X-Editor` 请求头记录编辑者(含中文时前端自动百分号编码,后端解码)。
交互文档:启动后访问 `/docs`。
## 已知边界
- 单文件 SQLite + WAL,适合部门级内部工具;更高并发请换 PG/MySQL
- 数据流向图以桌面屏为主,窄屏下侧栏收成图标栏,图区内可横向拖动查看
- 指标由链路配置推导而来,不是真实采集数据;接入真实埋点时只需改写 `flow_metrics` 的写入方

View File

@ -0,0 +1 @@
"""IT system panorama service."""

View File

@ -0,0 +1,21 @@
"""Runtime configuration for the IT panorama service."""
from __future__ import annotations
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
DEFAULT_DB = BASE_DIR / "panorama.db"
def db_path() -> Path:
raw = os.environ.get("DB_PATH")
return Path(raw).expanduser().resolve() if raw else DEFAULT_DB
# Payload guard for the full-graph save endpoint.
MAX_BODY_BYTES = int(os.environ.get("MAX_BODY_BYTES", str(5 * 1024 * 1024)))
# Static frontend build produced by `pnpm build` inside ../frontend.
WEB_DIST = Path(os.environ.get("WEB_DIST", str(BASE_DIR.parent / "frontend" / "dist")))

256
backend/app/db.py 100644
View File

@ -0,0 +1,256 @@
"""SQLite access layer: connection factory, schema, and small shared helpers.
The project deliberately uses the standard library ``sqlite3`` instead of an ORM.
Every request gets its own short lived connection so the WAL journal can serve
readers while a writer is committing.
"""
from __future__ import annotations
import json
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timezone
from typing import Any, Iterable, Iterator
from . import config
SCHEMA = """
CREATE TABLE IF NOT EXISTS layers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
short_name TEXT NOT NULL DEFAULT '',
color TEXT NOT NULL DEFAULT '#0d9488',
description TEXT NOT NULL DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS systems (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
layer_id TEXT REFERENCES layers(id) ON DELETE SET NULL,
dept TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'unknown',
tech TEXT NOT NULL DEFAULT '',
url TEXT NOT NULL DEFAULT '',
domain TEXT NOT NULL DEFAULT '',
owner TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
tier INTEGER NOT NULL DEFAULT 2,
-- Manual position on the data-flow canvas; NULL means "let the layout engine place it".
flow_x REAL,
flow_y REAL,
-- When the system went live. Free form: '2024-06' and '2023 Q4 上线' are both valid.
impl_time TEXT NOT NULL DEFAULT '',
-- Whether the panorama overview offers a jump button for this system.
entry_enabled INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_systems_layer ON systems(layer_id);
CREATE TABLE IF NOT EXISTS flow_types (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
color TEXT NOT NULL DEFAULT '#64748b',
line_style TEXT NOT NULL DEFAULT 'solid',
default_interval INTEGER NOT NULL DEFAULT 3600,
description TEXT NOT NULL DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS data_flows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_key TEXT NOT NULL,
target_key TEXT NOT NULL,
flow_type_id TEXT NOT NULL REFERENCES flow_types(id) ON DELETE CASCADE,
label TEXT NOT NULL DEFAULT '',
payload TEXT NOT NULL DEFAULT '',
direction TEXT NOT NULL DEFAULT 'forward',
interval_sec INTEGER NOT NULL DEFAULT 3600,
records_per_batch INTEGER NOT NULL DEFAULT 1,
avg_payload_kb REAL NOT NULL DEFAULT 1.0,
latency_ms INTEGER NOT NULL DEFAULT 120,
reliability TEXT NOT NULL DEFAULT 'sync',
peak_hours TEXT NOT NULL DEFAULT '1,2,3,4,5,6,7,8',
enabled INTEGER NOT NULL DEFAULT 1,
note TEXT NOT NULL DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_flows_source ON data_flows(source_key);
CREATE INDEX IF NOT EXISTS idx_flows_target ON data_flows(target_key);
-- Hourly aggregate per flow. hour_bucket is a local date string 'YYYY-MM-DD'.
CREATE TABLE IF NOT EXISTS flow_metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
flow_id INTEGER NOT NULL REFERENCES data_flows(id) ON DELETE CASCADE,
day TEXT NOT NULL,
hour INTEGER NOT NULL,
batches INTEGER NOT NULL DEFAULT 0,
records INTEGER NOT NULL DEFAULT 0,
bytes INTEGER NOT NULL DEFAULT 0,
errors INTEGER NOT NULL DEFAULT 0,
latency_ms INTEGER NOT NULL DEFAULT 0,
UNIQUE(flow_id, day, hour)
);
CREATE INDEX IF NOT EXISTS idx_metrics_day ON flow_metrics(day);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS audit_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
actor TEXT NOT NULL DEFAULT '匿名',
entity TEXT NOT NULL,
entity_id TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL,
summary TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_logs(created_at);
"""
def utcnow() -> str:
return datetime.now(timezone.utc).astimezone().replace(microsecond=0).isoformat(sep=" ")
def connect() -> sqlite3.Connection:
# Resolved through the module (not a captured name) so a patched config takes effect
# for connections opened later, including tests that swap the database per case.
path = config.db_path()
path.parent.mkdir(parents=True, exist_ok=True)
# check_same_thread=False is required because FastAPI resolves sync dependencies and
# runs the endpoint body on different threadpool threads. Safety is preserved because
# every request gets its own connection and never shares it with another request.
conn = sqlite3.connect(path, timeout=15.0, isolation_level=None, check_same_thread=False)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute("PRAGMA foreign_keys=ON;")
conn.execute("PRAGMA busy_timeout=8000;")
return conn
# Columns added after the first release, backfilled on older database files.
MIGRATIONS: tuple[tuple[str, str, str], ...] = (
("systems", "flow_x", "REAL"),
("systems", "flow_y", "REAL"),
("systems", "impl_time", "TEXT NOT NULL DEFAULT ''"),
("systems", "entry_enabled", "INTEGER NOT NULL DEFAULT 1"),
)
def migrate(conn: sqlite3.Connection) -> None:
# The shape is read once per table so a migration can target any table, and a table
# that gains several columns at once is only queried once.
seen: dict[str, set[str]] = {}
for table, column, ddl in MIGRATIONS:
if table not in seen:
seen[table] = {row["name"] for row in conn.execute(f"PRAGMA table_info({table})")}
if column in seen[table]:
continue
try:
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}")
except sqlite3.OperationalError as exc:
# Two processes starting at the same instant both see the missing column;
# whichever loses the race has nothing left to add.
if "duplicate column name" not in str(exc):
raise
seen[table].add(column)
def init_db() -> None:
conn = connect()
try:
conn.executescript(SCHEMA)
migrate(conn)
finally:
conn.close()
@contextmanager
def transaction(conn: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
"""Explicit write transaction.
The connections run with ``isolation_level=None`` so reads stay autocommit, which
also means the bare ``with conn:`` idiom would silently provide no atomicity.
"""
conn.execute("BEGIN IMMEDIATE")
try:
yield conn
except BaseException:
conn.execute("ROLLBACK")
raise
else:
conn.execute("COMMIT")
def get_db() -> Iterator[sqlite3.Connection]:
"""FastAPI dependency handing out one connection per request."""
conn = connect()
try:
yield conn
finally:
conn.close()
# --------------------------------------------------------------------------
# Row helpers
# --------------------------------------------------------------------------
def rows_to_dicts(rows: Iterable[sqlite3.Row]) -> list[dict[str, Any]]:
return [dict(row) for row in rows]
def one(conn: sqlite3.Connection, sql: str, params: Iterable[Any] = ()) -> dict[str, Any] | None:
row = conn.execute(sql, tuple(params)).fetchone()
return dict(row) if row else None
def all_(conn: sqlite3.Connection, sql: str, params: Iterable[Any] = ()) -> list[dict[str, Any]]:
return rows_to_dicts(conn.execute(sql, tuple(params)).fetchall())
def json_dump(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
def setting(conn: sqlite3.Connection, key: str, default: Any = None) -> Any:
row = conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
if row is None:
return default
try:
return json.loads(row["value"])
except json.JSONDecodeError:
return default
def set_setting(conn: sqlite3.Connection, key: str, value: Any) -> None:
conn.execute(
"""INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at""",
(key, json_dump(value), utcnow()),
)
def log_audit(
conn: sqlite3.Connection,
*,
actor: str,
entity: str,
entity_id: Any = "",
action: str,
summary: str = "",
) -> None:
conn.execute(
"""INSERT INTO audit_logs (actor, entity, entity_id, action, summary, created_at)
VALUES (?, ?, ?, ?, ?, ?)""",
(actor[:40] or "匿名", entity, str(entity_id), action, summary[:300], utcnow()),
)

View File

@ -0,0 +1,41 @@
"""Shared request helpers."""
from __future__ import annotations
import sqlite3
from typing import Annotated
from urllib.parse import unquote
from fastapi import Depends, HTTPException, Request
from .db import get_db, setting
def ensure_editable(db: sqlite3.Connection, action: str = "修改") -> None:
"""Abort a content write while the platform is switched to read-only.
423 Locked says "this exists but cannot be edited right now", which is exactly what
the switch means, and the frontend turns it into a toast naming that switch. The
``/api/settings`` endpoints deliberately stay open: locking the platform must never
lock the page that unlocks it again.
"""
if setting(db, "editing_enabled", True) is False:
raise HTTPException(423, f"平台已锁定为只读,无法{action}。请在「系统配置 · 平台配置」打开「允许编辑」后重试。")
def require_editable(db: Annotated[sqlite3.Connection, Depends(get_db)]) -> None:
"""Route dependency form of :func:`ensure_editable` for plain content writes."""
ensure_editable(db)
def actor_from(request: Request) -> str:
"""Editing identity travels on a header so every write method can stay uniform.
Header values cannot carry Chinese text, so the client percent-encodes it and we
decode here. Anything that is not valid escape coding is kept as-is.
"""
raw = request.headers.get("X-Editor") or request.headers.get("X-Actor") or ""
try:
decoded = unquote(raw, errors="strict") # strict so malformed input falls back below
except (UnicodeDecodeError, ValueError):
decoded = raw
return decoded.strip()[:40] or "匿名"

108
backend/app/main.py 100644
View File

@ -0,0 +1,108 @@
"""FastAPI application: JSON API plus static hosting for the built frontend."""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from .config import MAX_BODY_BYTES, WEB_DIST
from . import config
from .db import init_db
from .routers import backup, content, flows, graph
from .seed import seed
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(name)s: %(message)s")
logger = logging.getLogger("it.panorama")
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
conn = None
from .db import connect
from .services import metrics
conn = connect()
try:
if seed(conn):
logger.info("数据库首次初始化完成,已写入内置系统清单与数据流。")
metrics.ensure_history(conn)
finally:
conn.close()
logger.info("SQLite: %s", config.db_path())
yield
app = FastAPI(
title="公司 IT 系统全景与数据流向平台",
version="1.0.0",
description="IT 系统清单、数据流向图与流量指标的统一可配置后端。",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def limit_body_size(request: Request, call_next):
"""Guard the import endpoint before the body is buffered in memory."""
declared = request.headers.get("content-length")
if declared and request.method in {"POST", "PUT", "PATCH"} and int(declared) > MAX_BODY_BYTES:
return JSONResponse({"detail": "请求体过大"}, status_code=413)
return await call_next(request)
app.include_router(content.router)
app.include_router(flows.router)
app.include_router(graph.router)
app.include_router(backup.router)
@app.get("/api/health")
def health() -> dict:
return {"ok": True, "db": str(config.db_path())}
# ---------------------------------------------------------------- static frontend
if WEB_DIST.is_dir():
app.mount("/assets", StaticFiles(directory=WEB_DIST / "assets"), name="assets")
@app.get("/favicon.ico", include_in_schema=False)
def favicon():
path = WEB_DIST / "favicon.ico"
return FileResponse(path) if path.is_file() else JSONResponse({}, status_code=404)
@app.get("/{full_path:path}", include_in_schema=False)
def spa(full_path: str):
"""History-mode routing means unknown paths must fall back to index.html."""
if full_path.startswith("api/"):
# A typo in an API path must not masquerade as a successful page load.
return JSONResponse({"detail": "接口不存在"}, status_code=404)
candidate = (WEB_DIST / full_path).resolve()
if full_path and candidate.is_file() and candidate.is_relative_to(WEB_DIST.resolve()):
return FileResponse(candidate)
return FileResponse(WEB_DIST / "index.html")
else:
@app.get("/", include_in_schema=False)
def missing_frontend() -> JSONResponse:
return JSONResponse(
{
"detail": "前端尚未构建。请在 ../frontend 执行 pnpm install && pnpm build,"
"或使用 pnpm dev(默认 http://localhost:5273,已代理 /api 到本服务)。"
},
status_code=200,
)

View File

@ -0,0 +1 @@
"""API routers."""

View File

@ -0,0 +1,173 @@
"""Whole-graph export/import so the platform stays as portable as the original page."""
from __future__ import annotations
import sqlite3
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Request
from ..db import all_, get_db, json_dump, log_audit, set_setting, transaction, utcnow
from ..deps import actor_from, ensure_editable
from ..schemas import BackupIn
router = APIRouter(prefix="/api", tags=["backup"])
DB = Annotated[sqlite3.Connection, Depends(get_db)]
TABLES = ("layers", "systems", "flow_types", "data_flows")
@router.get("/backup")
def export_backup(db: DB) -> dict:
payload: dict = {"schema_version": 1, "exported_at": utcnow()}
for table in TABLES:
rows = all_(db, f"SELECT * FROM {table}") # noqa: S608 - table names come from a fixed tuple
if table == "data_flows":
for row in rows:
row["peak_hours"] = _loads(row.get("peak_hours"))
payload[table] = rows
payload["settings"] = {
row["key"]: _maybe_json(row["value"]) for row in all_(db, "SELECT key, value FROM settings")
if row["key"] != "last_live_tick"
}
return payload
@router.post("/backup")
def import_backup(payload: BackupIn, db: DB, request: Request) -> dict:
ensure_editable(db, "导入配置")
if not any(getattr(payload, table) for table in TABLES):
raise HTTPException(400, "备份文件中没有可导入的数据")
errors: list[str] = []
imported = {table: 0 for table in TABLES}
actor = actor_from(request)
with transaction(db):
if payload.mode == "replace":
# Metrics depend on flow ids, so a full replace resets history too.
for table in reversed(TABLES):
db.execute(f"DELETE FROM {table}")
db.execute("DELETE FROM settings")
for layer in payload.layers:
if not _has(layer, "id", "name"):
errors.append("层级缺少 id 或 name,已跳过")
continue
db.execute(
"""INSERT INTO layers (id, name, short_name, color, description, sort_order)
VALUES (?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, short_name=excluded.short_name,
color=excluded.color, description=excluded.description, sort_order=excluded.sort_order""",
(layer["id"], layer["name"], layer.get("short_name", ""), layer.get("color", "#0d9488"),
layer.get("description", ""), int(layer.get("sort_order", 0))),
)
imported["layers"] += 1
for system in payload.systems:
if not _has(system, "key", "name"):
errors.append("系统缺少 key 或 name,已跳过")
continue
now = utcnow()
db.execute(
"""INSERT INTO systems (key, name, layer_id, dept, status, tech, url, domain, owner,
impl_time, entry_enabled, description, tier, flow_x, flow_y,
sort_order, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT(key) DO UPDATE SET name=excluded.name, layer_id=excluded.layer_id,
dept=excluded.dept, status=excluded.status, tech=excluded.tech, url=excluded.url,
domain=excluded.domain, owner=excluded.owner, impl_time=excluded.impl_time,
entry_enabled=excluded.entry_enabled, description=excluded.description,
tier=excluded.tier, flow_x=excluded.flow_x, flow_y=excluded.flow_y, sort_order=excluded.sort_order, updated_at=excluded.updated_at""",
(system["key"], system["name"], system.get("layer_id"), system.get("dept", ""),
system.get("status", "unknown"), system.get("tech", ""), system.get("url", ""),
system.get("domain", ""), system.get("owner", ""), system.get("impl_time", ""),
1 if system.get("entry_enabled", 1) else 0, system.get("description", ""),
int(system.get("tier", 2)), system.get("flow_x"), system.get("flow_y"),
int(system.get("sort_order", 0)), now, now),
)
imported["systems"] += 1
for flow_type in payload.flow_types:
if not _has(flow_type, "id", "name"):
errors.append("数据类型缺少 id 或 name,已跳过")
continue
db.execute(
"""INSERT INTO flow_types (id, name, color, line_style, default_interval, description, sort_order)
VALUES (?,?,?,?,?,?,?)
ON CONFLICT(id) DO UPDATE SET name=excluded.name, color=excluded.color,
line_style=excluded.line_style, default_interval=excluded.default_interval,
description=excluded.description, sort_order=excluded.sort_order""",
(flow_type["id"], flow_type["name"], flow_type.get("color", "#64748b"),
flow_type.get("line_style", "dashed"), int(flow_type.get("default_interval", 3600)),
flow_type.get("description", ""), int(flow_type.get("sort_order", 0))),
)
imported["flow_types"] += 1
known_systems = {row["key"] for row in all_(db, "SELECT key FROM systems")}
known_types = {row["id"] for row in all_(db, "SELECT id FROM flow_types")}
now = utcnow()
for flow in payload.data_flows:
source, target = flow.get("source_key"), flow.get("target_key")
type_id = flow.get("flow_type_id")
if source not in known_systems or target not in known_systems:
errors.append(f"数据流 {source} → {target} 的端点系统不存在,已跳过")
continue
if type_id not in known_types:
errors.append(f"数据流 {flow.get('label', '')} 的数据类型 {type_id} 不存在,已跳过")
continue
columns = ["source_key", "target_key", "flow_type_id", "label", "payload", "direction",
"interval_sec", "records_per_batch", "avg_payload_kb", "latency_ms",
"reliability", "peak_hours", "enabled", "note", "sort_order", "created_at", "updated_at"]
values: list = [source, target, type_id, flow.get("label", ""), flow.get("payload", ""),
flow.get("direction", "forward"), int(flow.get("interval_sec", 3600)),
int(flow.get("records_per_batch", 1)), float(flow.get("avg_payload_kb", 1.0)),
int(flow.get("latency_ms", 120)), flow.get("reliability", "async"),
json_dump(flow.get("peak_hours") or []), 1 if flow.get("enabled", True) else 0,
flow.get("note", ""), int(flow.get("sort_order", 0)), now, now]
# Keep the original id when the backup carries one, so re-importing updates in place
# and existing metrics stay attached to the same flow.
flow_id = flow.get("id")
if isinstance(flow_id, int):
columns.insert(0, "id")
values.insert(0, flow_id)
placeholders = ", ".join("?" for _ in values)
column_list = ", ".join(columns)
upsert = ", ".join(f"{column}=excluded.{column}" for column in columns if column != "id")
sql = (
f"INSERT INTO data_flows ({column_list}) VALUES ({placeholders}) "
f"ON CONFLICT(id) DO UPDATE SET {upsert}"
)
db.execute(sql, values)
imported["data_flows"] += 1
for key, value in (payload.settings or {}).items():
set_setting(db, key, value)
log_audit(db, actor=actor, entity="backup", action="import",
summary=f"{payload.mode} 导入:{imported['systems']} 系统 / {imported['data_flows']} 数据流")
return {"imported": imported, "errors": errors, "mode": payload.mode}
def _has(row: dict, *keys: str) -> bool:
return all(row.get(key) not in (None, "") for key in keys)
def _loads(raw) -> list[int]:
import json
try:
value = json.loads(raw or "[]")
except (TypeError, json.JSONDecodeError):
return []
return [int(v) for v in value] if isinstance(value, list) else []
def _maybe_json(raw: str):
import json
try:
return json.loads(raw)
except json.JSONDecodeError:
return raw

View File

@ -0,0 +1,252 @@
"""Layers, systems and flow types: the configurable vocabulary of the platform."""
from __future__ import annotations
import sqlite3
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Request
from ..db import all_, get_db, log_audit, one, set_setting, transaction, utcnow
from ..deps import actor_from, require_editable
from ..schemas import LayerIn, FlowTypeIn, SettingsIn, SystemIn, SystemPatch
router = APIRouter(prefix="/api", tags=["content"])
DB = Annotated[sqlite3.Connection, Depends(get_db)]
# ---------------------------------------------------------------- layers
@router.get("/layers")
def list_layers(db: DB) -> list[dict]:
return all_(db, """SELECT l.*, (SELECT COUNT(*) FROM systems s WHERE s.layer_id = l.id) AS system_count
FROM layers l ORDER BY l.sort_order, l.id""")
@router.post("/layers", status_code=201, dependencies=[Depends(require_editable)])
def create_layer(payload: LayerIn, db: DB, request: Request) -> dict:
if one(db, "SELECT id FROM layers WHERE id = ?", (payload.id,)):
raise HTTPException(409, "层级 ID 已存在")
with transaction(db):
db.execute(
"INSERT INTO layers (id, name, short_name, color, description, sort_order) VALUES (?,?,?,?,?,?)",
(payload.id, payload.name, payload.short_name, payload.color, payload.description, payload.sort_order),
)
log_audit(db, actor=actor_from(request), entity="layer", entity_id=payload.id,
action="create", summary=f"新增层级 {payload.name}")
return one(db, "SELECT * FROM layers WHERE id = ?", (payload.id,)) # type: ignore[return-value]
@router.put("/layers/{layer_id}", dependencies=[Depends(require_editable)])
def update_layer(layer_id: str, payload: LayerIn, db: DB, request: Request) -> dict:
if not one(db, "SELECT id FROM layers WHERE id = ?", (layer_id,)):
raise HTTPException(404, "层级不存在")
with transaction(db):
db.execute(
"""UPDATE layers SET name=?, short_name=?, color=?, description=?, sort_order=? WHERE id=?""",
(payload.name, payload.short_name, payload.color, payload.description, payload.sort_order, layer_id),
)
log_audit(db, actor=actor_from(request), entity="layer", entity_id=layer_id,
action="update", summary=f"更新层级 {payload.name}")
return one(db, "SELECT * FROM layers WHERE id = ?", (layer_id,)) # type: ignore[return-value]
@router.delete("/layers/{layer_id}", dependencies=[Depends(require_editable)])
def delete_layer(layer_id: str, db: DB, request: Request) -> dict:
row = one(db, "SELECT name FROM layers WHERE id = ?", (layer_id,))
if not row:
raise HTTPException(404, "层级不存在")
used = one(db, "SELECT COUNT(*) AS c FROM systems WHERE layer_id = ?", (layer_id,))
if used and used["c"]:
raise HTTPException(409, f"仍有 {used['c']} 个系统属于该层级,请先调整这些系统的层级归属")
with transaction(db):
db.execute("DELETE FROM layers WHERE id = ?", (layer_id,))
log_audit(db, actor=actor_from(request), entity="layer", entity_id=layer_id,
action="delete", summary=f"删除层级 {row['name']}")
return {"ok": True}
# ---------------------------------------------------------------- systems
SYSTEM_SELECT = """SELECT s.*, l.name AS layer_name, l.color AS layer_color
FROM systems s LEFT JOIN layers l ON l.id = s.layer_id"""
def _shape_system(row: dict | None) -> dict | None:
"""SQLite stores the jump switch as 0/1; the API promises a real boolean."""
if row is not None:
row["entry_enabled"] = bool(row.get("entry_enabled", 1))
return row
def _all_systems(db: sqlite3.Connection, sql: str, params: object = ()) -> list[dict]:
return [_shape_system(row) for row in all_(db, sql, params)]
@router.get("/systems")
def list_systems(db: DB, layer_id: str | None = None, status: str | None = None,
keyword: str | None = None) -> list[dict]:
sql, params = SYSTEM_SELECT, []
where = []
if layer_id:
where.append("s.layer_id = ?")
params.append(layer_id)
if status:
where.append("s.status = ?")
params.append(status)
if keyword:
where.append("(s.name LIKE ? OR s.dept LIKE ? OR s.tech LIKE ? OR s.description LIKE ?)")
params.extend([f"%{keyword}%"] * 4)
if where:
sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY COALESCE(l.sort_order, 99), s.sort_order, s.id"
return _all_systems(db, sql, params)
@router.get("/systems/{key}")
def get_system(key: str, db: DB) -> dict:
row = _shape_system(one(db, SYSTEM_SELECT + " WHERE s.key = ?", (key,)))
if not row:
raise HTTPException(404, "系统不存在")
return row
@router.post("/systems", status_code=201, dependencies=[Depends(require_editable)])
def create_system(payload: SystemIn, db: DB, request: Request) -> dict:
if one(db, "SELECT key FROM systems WHERE key = ?", (payload.key,)):
raise HTTPException(409, "系统标识已存在")
if payload.layer_id and not one(db, "SELECT id FROM layers WHERE id = ?", (payload.layer_id,)):
raise HTTPException(400, "所属层级不存在")
now = utcnow()
with transaction(db):
db.execute(
"""INSERT INTO systems (key, name, layer_id, dept, status, tech, url, domain, owner,
impl_time, entry_enabled, description, tier, flow_x, flow_y,
sort_order, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(payload.key, payload.name, payload.layer_id, payload.dept, payload.status, payload.tech,
payload.url, payload.domain, payload.owner, payload.impl_time,
1 if payload.entry_enabled else 0, payload.description, payload.tier,
payload.flow_x, payload.flow_y, payload.sort_order, now, now),
)
log_audit(db, actor=actor_from(request), entity="system", entity_id=payload.key,
action="create", summary=f"新增系统 {payload.name}")
return _shape_system(one(db, SYSTEM_SELECT + " WHERE s.key = ?", (payload.key,))) # type: ignore[return-value]
@router.patch("/systems/{key}", dependencies=[Depends(require_editable)])
def update_system(key: str, payload: SystemPatch, db: DB, request: Request) -> dict:
current = _shape_system(one(db, "SELECT * FROM systems WHERE key = ?", (key,)))
if not current:
raise HTTPException(404, "系统不存在")
changes = payload.model_dump(exclude_unset=True)
if not changes:
return current
if changes.get("layer_id") and not one(db, "SELECT id FROM layers WHERE id = ?", (changes["layer_id"],)):
raise HTTPException(400, "所属层级不存在")
if "impl_time" in changes:
changes["impl_time"] = (changes["impl_time"] or "").strip()[:120]
if "entry_enabled" in changes:
changes["entry_enabled"] = 1 if changes["entry_enabled"] else 0
changes["updated_at"] = utcnow()
assignments = ", ".join(f"{column} = ?" for column in changes)
with transaction(db):
db.execute(f"UPDATE systems SET {assignments} WHERE key = ?", [*changes.values(), key])
log_audit(db, actor=actor_from(request), entity="system", entity_id=key, action="update",
summary="更新字段:" + "、".join(k for k in changes if k != "updated_at"))
return _shape_system(one(db, SYSTEM_SELECT + " WHERE s.key = ?", (key,))) # type: ignore[return-value]
@router.delete("/systems/{key}", dependencies=[Depends(require_editable)])
def delete_system(key: str, db: DB, request: Request) -> dict:
if not one(db, "SELECT key FROM systems WHERE key = ?", (key,)):
raise HTTPException(404, "系统不存在")
flows = one(db, "SELECT COUNT(*) AS c FROM data_flows WHERE source_key = ? OR target_key = ?", (key, key))
with transaction(db):
db.execute("DELETE FROM systems WHERE key = ?", (key,))
log_audit(db, actor=actor_from(request), entity="system", entity_id=key, action="delete",
summary=f"删除系统,级联移除 {flows['c'] if flows else 0} 条数据流")
return {"ok": True, "removed_flows": flows["c"] if flows else 0}
# ---------------------------------------------------------------- flow types
@router.get("/flow-types")
def list_flow_types(db: DB) -> list[dict]:
return all_(db, """SELECT t.*, (SELECT COUNT(*) FROM data_flows f WHERE f.flow_type_id = t.id) AS flow_count
FROM flow_types t ORDER BY t.sort_order, t.id""")
@router.post("/flow-types", status_code=201, dependencies=[Depends(require_editable)])
def create_flow_type(payload: FlowTypeIn, db: DB, request: Request) -> dict:
if one(db, "SELECT id FROM flow_types WHERE id = ?", (payload.id,)):
raise HTTPException(409, "数据类型 ID 已存在")
with transaction(db):
db.execute(
"""INSERT INTO flow_types (id, name, color, line_style, default_interval, description, sort_order)
VALUES (?,?,?,?,?,?,?)""",
(payload.id, payload.name, payload.color, payload.line_style,
payload.default_interval, payload.description, payload.sort_order),
)
log_audit(db, actor=actor_from(request), entity="flow_type", entity_id=payload.id,
action="create", summary=f"新增数据类型 {payload.name}")
return one(db, "SELECT * FROM flow_types WHERE id = ?", (payload.id,)) # type: ignore[return-value]
@router.put("/flow-types/{type_id}", dependencies=[Depends(require_editable)])
def update_flow_type(type_id: str, payload: FlowTypeIn, db: DB, request: Request) -> dict:
if not one(db, "SELECT id FROM flow_types WHERE id = ?", (type_id,)):
raise HTTPException(404, "数据类型不存在")
with transaction(db):
db.execute(
"""UPDATE flow_types SET name=?, color=?, line_style=?, default_interval=?, description=?, sort_order=?
WHERE id=?""",
(payload.name, payload.color, payload.line_style, payload.default_interval,
payload.description, payload.sort_order, type_id),
)
log_audit(db, actor=actor_from(request), entity="flow_type", entity_id=type_id,
action="update", summary=f"更新数据类型 {payload.name}")
return one(db, "SELECT * FROM flow_types WHERE id = ?", (type_id,)) # type: ignore[return-value]
@router.delete("/flow-types/{type_id}", dependencies=[Depends(require_editable)])
def delete_flow_type(type_id: str, db: DB, request: Request) -> dict:
row = one(db, "SELECT name FROM flow_types WHERE id = ?", (type_id,))
if not row:
raise HTTPException(404, "数据类型不存在")
used = one(db, "SELECT COUNT(*) AS c FROM data_flows WHERE flow_type_id = ?", (type_id,))
if used and used["c"]:
raise HTTPException(409, f"仍有 {used['c']} 条数据流使用该类型,请先调整这些数据流")
with transaction(db):
db.execute("DELETE FROM flow_types WHERE id = ?", (type_id,))
log_audit(db, actor=actor_from(request), entity="flow_type", entity_id=type_id,
action="delete", summary=f"删除数据类型 {row['name']}")
return {"ok": True}
# ---------------------------------------------------------------- settings
@router.get("/settings")
def get_settings(db: DB) -> dict:
rows = all_(db, "SELECT key, value FROM settings")
import json
out: dict = {}
for row in rows:
try:
out[row["key"]] = json.loads(row["value"])
except json.JSONDecodeError:
out[row["key"]] = row["value"]
return out
@router.patch("/settings")
def patch_settings(payload: SettingsIn, db: DB, request: Request) -> dict:
changes = payload.model_dump(exclude_unset=True)
with transaction(db):
for key, value in changes.items():
set_setting(db, key, value)
log_audit(db, actor=actor_from(request), entity="settings", action="update",
summary="更新配置:" + "、".join(changes))
return get_settings(db)

View File

@ -0,0 +1,141 @@
"""Data flow CRUD: the edges that make up the data-flow graph."""
from __future__ import annotations
import json
import sqlite3
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Request
from ..db import all_, get_db, json_dump, log_audit, one, transaction, utcnow
from ..deps import actor_from, ensure_editable
from ..schemas import FlowIn, FlowPatch
router = APIRouter(prefix="/api/flows", tags=["flows"])
DB = Annotated[sqlite3.Connection, Depends(get_db)]
FLOW_SELECT = """SELECT f.*, t.name AS flow_type_name, t.color AS flow_type_color,
t.line_style AS flow_type_line_style,
s.name AS source_name, g.name AS target_name
FROM data_flows f
JOIN flow_types t ON t.id = f.flow_type_id
JOIN systems s ON s.key = f.source_key
JOIN systems g ON g.key = f.target_key"""
def _loads(raw) -> list[int]:
try:
value = json.loads(raw or "[]")
except (TypeError, json.JSONDecodeError):
return []
return sorted({int(v) for v in value if 0 <= int(v) <= 23}) if isinstance(value, list) else []
def _shape(row: dict | None) -> dict | None:
if row is None:
return None
row["peak_hours"] = _loads(row.get("peak_hours"))
row["enabled"] = bool(row.get("enabled"))
return row
def _validate_endpoints(db: sqlite3.Connection, source: str, target: str) -> None:
if source == target:
raise HTTPException(400, "起点与终点不能是同一个系统")
for key, role in ((source, "起点"), (target, "终点")):
if not one(db, "SELECT key FROM systems WHERE key = ?", (key,)):
raise HTTPException(400, f"{role}系统不存在:{key}")
@router.get("")
def list_flows(db: DB, flow_type_id: str | None = None, enabled: bool | None = None) -> list[dict]:
sql, params = FLOW_SELECT, []
where = []
if flow_type_id:
where.append("f.flow_type_id = ?")
params.append(flow_type_id)
if enabled is not None:
where.append("f.enabled = ?")
params.append(1 if enabled else 0)
if where:
sql += " WHERE " + " AND ".join(where)
sql += " ORDER BY f.sort_order, f.id"
return [_shape(row) for row in all_(db, sql, params)]
@router.get("/{flow_id}")
def get_flow(flow_id: int, db: DB) -> dict:
row = one(db, FLOW_SELECT + " WHERE f.id = ?", (flow_id,))
if not row:
raise HTTPException(404, "数据流不存在")
return _shape(row)
@router.post("", status_code=201)
def create_flow(payload: FlowIn, db: DB, request: Request) -> dict:
ensure_editable(db, "新增数据流")
_validate_endpoints(db, payload.source_key, payload.target_key)
if not one(db, "SELECT id FROM flow_types WHERE id = ?", (payload.flow_type_id,)):
raise HTTPException(400, "数据类型不存在")
clash = one(db, """SELECT id FROM data_flows WHERE source_key = ? AND target_key = ?
AND flow_type_id = ? AND label = ?""",
(payload.source_key, payload.target_key, payload.flow_type_id, payload.label))
if clash:
raise HTTPException(409, "相同起点、终点、类型与名称的数据流已存在")
now = utcnow()
with transaction(db):
db.execute(
"""INSERT INTO data_flows (source_key, target_key, flow_type_id, label, payload, direction,
interval_sec, records_per_batch, avg_payload_kb, latency_ms,
reliability, peak_hours, enabled, note, sort_order, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(payload.source_key, payload.target_key, payload.flow_type_id, payload.label, payload.payload,
payload.direction, payload.interval_sec, payload.records_per_batch, payload.avg_payload_kb,
payload.latency_ms, payload.reliability, json_dump(payload.peak_hours),
1 if payload.enabled else 0, payload.note, payload.sort_order, now, now),
)
log_audit(db, actor=actor_from(request), entity="flow", entity_id=payload.label,
action="create", summary=f"新增数据流 {payload.source_key} → {payload.target_key}")
return _shape(one(db, FLOW_SELECT + " WHERE f.id = (SELECT MAX(id) FROM data_flows)"))
@router.patch("/{flow_id}")
def update_flow(flow_id: int, payload: FlowPatch, db: DB, request: Request) -> dict:
ensure_editable(db, "修改数据流")
current = one(db, "SELECT * FROM data_flows WHERE id = ?", (flow_id,))
if not current:
raise HTTPException(404, "数据流不存在")
changes = payload.model_dump(exclude_unset=True)
if not changes:
return _shape(current)
source = changes.get("source_key", current["source_key"])
target = changes.get("target_key", current["target_key"])
_validate_endpoints(db, source, target)
if changes.get("flow_type_id") and not one(db, "SELECT id FROM flow_types WHERE id = ?", (changes["flow_type_id"],)):
raise HTTPException(400, "数据类型不存在")
if "peak_hours" in changes:
changes["peak_hours"] = json_dump(sorted({int(h) for h in changes["peak_hours"] or [] if 0 <= int(h) <= 23}))
if "enabled" in changes:
changes["enabled"] = 1 if changes["enabled"] else 0
changes["updated_at"] = utcnow()
assignments = ", ".join(f"{column} = ?" for column in changes)
with transaction(db):
db.execute(f"UPDATE data_flows SET {assignments} WHERE id = ?", [*changes.values(), flow_id])
log_audit(db, actor=actor_from(request), entity="flow", entity_id=flow_id, action="update",
summary="更新字段:" + "、".join(k for k in changes if k != "updated_at"))
return _shape(one(db, FLOW_SELECT + " WHERE f.id = ?", (flow_id,)))
@router.delete("/{flow_id}")
def delete_flow(flow_id: int, db: DB, request: Request) -> dict:
ensure_editable(db, "删除数据流")
current = one(db, "SELECT label FROM data_flows WHERE id = ?", (flow_id,))
if not current:
raise HTTPException(404, "数据流不存在")
with transaction(db):
db.execute("DELETE FROM data_flows WHERE id = ?", (flow_id,))
log_audit(db, actor=actor_from(request), entity="flow", entity_id=flow_id,
action="delete", summary=f"删除数据流 {current['label']}")
return {"ok": True}

View File

@ -0,0 +1,173 @@
"""Aggregated read models: the whole graph, KPI totals, live counters and audit trail."""
from __future__ import annotations
import sqlite3
from datetime import date, datetime, timedelta
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from ..db import all_, get_db, log_audit, one, transaction, utcnow
from ..deps import actor_from, ensure_editable
from ..schemas import LayoutIn
from ..services import metrics
from ..services.graph import build_graph, tier_label
router = APIRouter(prefix="/api", tags=["graph"])
DB = Annotated[sqlite3.Connection, Depends(get_db)]
@router.get("/graph")
def graph(db: DB, days: int = Query(7, ge=1, le=90), include_disabled: bool = False) -> dict:
return build_graph(db, days=days, include_disabled=include_disabled)
@router.put("/graph/layout")
def save_layout(payload: LayoutIn, db: DB, request: Request) -> dict:
"""Persist where the user dropped the cards on the data-flow canvas.
One request carries a whole drag gesture so the audit trail records "moved three cards"
instead of three entries per card. A coordinate sent as null puts that card back under
automatic placement.
"""
ensure_editable(db, "调整数据流向图布局")
now = utcnow()
placed = 0
cleared = 0
moved: list[str] = []
missing: list[str] = []
with transaction(db):
for item in payload.items:
row = one(db, "SELECT key, name, tier FROM systems WHERE key = ?", (item.key,))
if not row:
missing.append(item.key)
continue
given = item.model_fields_set
columns: dict[str, object] = {}
if "x" in given:
columns["flow_x"] = item.x
if "y" in given:
columns["flow_y"] = item.y
if columns:
if item.x is None and item.y is None:
cleared += 1
elif item.x is not None or item.y is not None:
placed += 1
if item.tier is not None and item.tier != row["tier"]:
columns["tier"] = item.tier
moved.append(f"{row['name']}→{tier_label(item.tier)}")
if not columns:
continue
columns["updated_at"] = now
assignments = ", ".join(f"{column} = ?" for column in columns)
db.execute(f"UPDATE systems SET {assignments} WHERE key = ?", [*columns.values(), item.key]) # noqa: S608
parts = []
if placed:
parts.append(f"手动摆放 {placed} 个系统")
if cleared:
parts.append(f"{cleared} 个恢复自动排列")
if moved:
parts.append("换列:" + "、".join(moved[:5]) + ("等" if len(moved) > 5 else ""))
summary = "数据流向图布局:" + ";".join(parts) if parts else ""
if summary:
log_audit(db, actor=actor_from(request), entity="layout", entity_id="flow_graph",
action="update", summary=summary)
return {"ok": True, "placed": placed, "cleared": cleared, "moved": len(moved), "missing": missing}
@router.post("/graph/layout/reset")
def reset_layout(db: DB, request: Request) -> dict:
"""Drop every manual position so the layout engine lays the graph out again."""
ensure_editable(db, "恢复自动排列")
with transaction(db):
cursor = db.execute(
"UPDATE systems SET flow_x = NULL, flow_y = NULL, updated_at = ? "
"WHERE flow_x IS NOT NULL OR flow_y IS NOT NULL",
(utcnow(),),
)
cleared = cursor.rowcount
if cleared:
log_audit(db, actor=actor_from(request), entity="layout", entity_id="flow_graph",
action="update", summary=f"数据流向图恢复自动排列({cleared} 个系统)")
return {"ok": True, "cleared": cleared}
@router.get("/metrics/summary")
def summary(db: DB, days: int = Query(7, ge=1, le=90)) -> dict:
totals = metrics.totals(db, days)
counts = one(db, """SELECT
(SELECT COUNT(*) FROM systems) AS systems,
(SELECT COUNT(*) FROM data_flows WHERE enabled = 1) AS flows,
(SELECT COUNT(*) FROM data_flows) AS flows_all,
(SELECT COUNT(*) FROM flow_types) AS flow_types,
(SELECT COUNT(*) FROM layers) AS layers""")
health = metrics.flow_health(db, days=days)
states = [h["health"] for h in health.values()]
return {
"range_days": days,
"totals": totals,
"counts": counts,
"health": {
"healthy": states.count("healthy"),
"watch": states.count("watch"),
"risk": states.count("risk"),
},
"generated_at": datetime.now().replace(microsecond=0).isoformat(),
}
@router.get("/metrics/hourly")
def hourly(db: DB, days: int = Query(3, ge=1, le=90)) -> dict:
"""Network-wide hourly curve plus a per-flow breakdown, for the trend charts."""
metrics.ensure_history(db)
start = (date.today() - timedelta(days=days - 1)).isoformat()
rows = all_(db, """SELECT m.day, m.hour, SUM(m.batches) AS batches, SUM(m.records) AS records,
SUM(m.bytes) AS bytes, SUM(m.errors) AS errors,
AVG(NULLIF(m.latency_ms,0)) AS latency
FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
WHERE f.enabled = 1 AND m.day >= ?
GROUP BY m.day, m.hour ORDER BY m.day, m.hour""", (start,))
return {"days": days, "start": start, "points": rows}
@router.get("/metrics/flows/{flow_id}")
def flow_series(flow_id: int, db: DB, days: int = Query(7, ge=1, le=90)) -> dict:
if not one(db, "SELECT id FROM data_flows WHERE id = ?", (flow_id,)):
raise HTTPException(404, "数据流不存在")
return {"flow_id": flow_id, "days": days, "points": metrics.hourly_series(db, flow_id, days)}
@router.get("/metrics/live")
def live(db: DB) -> dict:
"""Current-hour snapshot for every enabled flow; drives the animated graph."""
today = date.today().isoformat()
hour = datetime.now().hour
rows = all_(db, """SELECT f.id AS flow_id, f.source_key, f.target_key, f.flow_type_id, f.label,
f.direction, f.enabled, COALESCE(m.batches,0) AS batches,
COALESCE(m.records,0) AS records, COALESCE(m.bytes,0) AS bytes,
COALESCE(m.errors,0) AS errors, COALESCE(m.latency_ms,0) AS latency_ms
FROM data_flows f
LEFT JOIN flow_metrics m ON m.flow_id = f.id AND m.day = ? AND m.hour = ?
ORDER BY f.id""", (today, hour))
return {"day": today, "hour": hour, "flows": rows}
@router.post("/metrics/tick")
def tick(db: DB) -> dict:
return metrics.live_tick(db)
@router.get("/audit")
def audit(db: DB, limit: int = Query(50, ge=1, le=500), entity: str | None = None) -> list[dict]:
sql, params = "SELECT * FROM audit_logs", []
if entity:
sql += " WHERE entity = ?"
params.append(entity)
sql += " ORDER BY id DESC LIMIT ?"
params.append(limit)
return all_(db, sql, params)

View File

@ -0,0 +1,191 @@
"""Request/response models. Responses stay plain dicts straight from SQLite so the
API surface does not drift from what the frontend already receives."""
from __future__ import annotations
from typing import Literal
from pydantic import BaseModel, Field, field_validator
StatusKey = Literal["running", "improving", "dev", "unknown"]
Direction = Literal["forward", "backward", "bidirectional"]
Reliability = Literal["sync", "async"]
def _clean(value: str | None, limit: int = 500) -> str:
return (value or "").strip()[:limit]
class LayerIn(BaseModel):
id: str = Field(min_length=1, max_length=40)
name: str = Field(min_length=1, max_length=80)
short_name: str = ""
color: str = "#0d9488"
description: str = ""
sort_order: int = 0
@field_validator("id")
@classmethod
def _norm_id(cls, v: str) -> str:
return _clean(v, 40)
@field_validator("name")
@classmethod
def _norm_name(cls, v: str) -> str:
return _clean(v, 80)
class SystemIn(BaseModel):
key: str = Field(min_length=1, max_length=60)
name: str = Field(min_length=1, max_length=80)
layer_id: str | None = None
dept: str = ""
status: StatusKey = "unknown"
tech: str = ""
url: str = ""
domain: str = ""
owner: str = ""
impl_time: str = ""
entry_enabled: bool = True
description: str = ""
tier: int = Field(default=2, ge=0, le=9)
flow_x: float | None = Field(default=None, ge=-4000, le=8000)
flow_y: float | None = Field(default=None, ge=-4000, le=8000)
sort_order: int = 0
@field_validator("key")
@classmethod
def _norm_key(cls, v: str) -> str:
return _clean(v, 60)
@field_validator("name")
@classmethod
def _norm_name(cls, v: str) -> str:
return _clean(v, 80)
class SystemPatch(BaseModel):
name: str | None = None
layer_id: str | None = None
dept: str | None = None
status: StatusKey | None = None
tech: str | None = None
url: str | None = None
domain: str | None = None
owner: str | None = None
impl_time: str | None = None
entry_enabled: bool | None = None
description: str | None = None
tier: int | None = Field(default=None, ge=0, le=9)
flow_x: float | None = Field(default=None, ge=-4000, le=8000)
flow_y: float | None = Field(default=None, ge=-4000, le=8000)
sort_order: int | None = None
@field_validator("name")
@classmethod
def _norm_name(cls, v: str | None) -> str | None:
# Renaming later is an ordinary edit, but an empty name would blank out every card.
if v is None:
return None
cleaned = _clean(v, 80)
if not cleaned:
raise ValueError("系统名称不能为空")
return cleaned
class LayoutItem(BaseModel):
# One card on the data-flow canvas; a null coordinate means place it automatically.
key: str = Field(min_length=1, max_length=60)
x: float | None = Field(default=None, ge=-4000, le=8000)
y: float | None = Field(default=None, ge=-4000, le=8000)
tier: int | None = Field(default=None, ge=0, le=9)
class LayoutIn(BaseModel):
items: list[LayoutItem] = Field(default_factory=list, max_length=400)
class FlowTypeIn(BaseModel):
id: str = Field(min_length=1, max_length=40)
name: str = Field(min_length=1, max_length=60)
color: str = "#64748b"
# 线型是节奏的编码: 实线同步、虚线异步、点划线定时/人工、点线低频参考。
line_style: Literal["solid", "dashed", "dash-dot", "dotted"] = "dashed"
default_interval: int = Field(default=3600, ge=10, le=86400)
description: str = ""
sort_order: int = 0
class FlowIn(BaseModel):
source_key: str = Field(min_length=1, max_length=60)
target_key: str = Field(min_length=1, max_length=60)
flow_type_id: str
label: str = Field(min_length=1, max_length=80)
payload: str = ""
direction: Direction = "forward"
interval_sec: int = Field(default=3600, ge=10, le=86400)
records_per_batch: int = Field(default=1, ge=0, le=1_000_000)
avg_payload_kb: float = Field(default=1.0, ge=0, le=10_000_000)
latency_ms: int = Field(default=120, ge=0, le=600_000)
reliability: Reliability = "async"
peak_hours: list[int] = Field(default_factory=lambda: [9, 10, 11, 14, 15, 16, 17])
enabled: bool = True
note: str = ""
sort_order: int = 0
@field_validator("peak_hours")
@classmethod
def _hours(cls, v: list[int]) -> list[int]:
clean = sorted({int(h) for h in v if 0 <= int(h) <= 23})
return clean
@field_validator("label")
@classmethod
def _label(cls, v: str) -> str:
return _clean(v, 80)
class FlowPatch(BaseModel):
source_key: str | None = None
target_key: str | None = None
flow_type_id: str | None = None
label: str | None = None
payload: str | None = None
direction: Direction | None = None
interval_sec: int | None = Field(default=None, ge=10, le=86400)
records_per_batch: int | None = Field(default=None, ge=0, le=1_000_000)
avg_payload_kb: float | None = Field(default=None, ge=0, le=10_000_000)
latency_ms: int | None = Field(default=None, ge=0, le=600_000)
reliability: Reliability | None = None
peak_hours: list[int] | None = None
enabled: bool | None = None
note: str | None = None
sort_order: int | None = None
class Actor(BaseModel):
"""Optional editing identity carried on write requests."""
actor: str = "匿名"
class SettingsIn(BaseModel):
site_title: str | None = None
site_subtitle: str | None = None
editing_enabled: bool | None = None
animation_enabled: bool | None = None
animation_speed: float | None = Field(default=None, ge=0.1, le=5)
live_mode: bool | None = None
live_interval_sec: int | None = Field(default=None, ge=5, le=600)
default_range_days: int | None = Field(default=None, ge=1, le=90)
#: How links are drawn on the data-flow canvas: orthogonal, curved, or plain segments.
flow_route_style: Literal["elbow", "curve", "straight"] | None = None
class BackupIn(BaseModel):
layers: list[dict] = Field(default_factory=list)
systems: list[dict] = Field(default_factory=list)
flow_types: list[dict] = Field(default_factory=list)
data_flows: list[dict] = Field(default_factory=list)
settings: dict = Field(default_factory=dict)
mode: Literal["replace", "merge"] = "replace"

392
backend/app/seed.py 100644
View File

@ -0,0 +1,392 @@
"""Seed content: the IT system inventory plus the initial data-flow topology.
Everything here is editable through the API afterwards; seeding only runs when the
database is still empty so local edits are never overwritten.
"""
from __future__ import annotations
import sqlite3
from .db import json_dump, set_setting, transaction, utcnow
LAYERS = [
{
"id": "common",
"name": "通用系统(全公司使用)",
"short_name": "通用系统",
"color": "#0d9488",
"description": "面向全公司提供的通用办公与协同系统。",
"sort_order": 1,
},
{
"id": "dept",
"name": "各部门业务系统",
"short_name": "部门业务",
"color": "#2563eb",
"description": "由各业务部门主导建设、服务本部门主流程的系统。",
"sort_order": 2,
},
{
"id": "base",
"name": "底座(基础平台)",
"short_name": "底座",
"color": "#7c3aed",
"description": "为上层系统提供认证、算力、存储与组件复用能力的底座平台。",
"sort_order": 3,
},
]
# tier drives the column of a node inside the data-flow graph:
# 0 = 统一入口层, 1 = 审批中枢, 2 = 业务系统, 3 = 底座能力
SYSTEMS = [
# ---- 通用系统 ----
{
"key": "oa", "name": "OA(华智OA)", "layer_id": "common", "dept": "",
"status": "running", "tech": "Java / Spring Boot / MySQL",
"tier": 1,
"description": "统一办公自动化系统(华智OA),覆盖审批、流程、协同办公,全公司正常使用中,也是当前审批数据的主要产生源。",
},
{
"key": "finance-bot", "name": "财务数字助理", "layer_id": "common", "dept": "",
"status": "running", "tech": "Python / OCR / MySQL",
"tier": 2,
"description": "智能化财务辅助系统,承接 OA 报销单据做票据识别与入账处理,正常使用中。",
},
{
"key": "nas", "name": "NAS文件服务", "layer_id": "common", "dept": "",
"status": "running", "tech": "NAS / SMB",
"tier": 3,
"description": "网络文件存储与共享服务,承载盖章合同原件等归档文件,正常使用中。",
},
{
"key": "wecom", "name": "企业微信", "layer_id": "common", "dept": "",
"status": "running", "tech": "企业微信开放平台",
"tier": 0,
"description": "统一沟通与移动办公平台,移动端统一接入入口,负责备案发起与消息提醒回传;使用独立账号体系,不接入 UniHub SSO。",
},
{
"key": "ekb", "name": "ekb知识库", "layer_id": "common", "dept": "",
"status": "dev", "tech": "Java / Elasticsearch",
"tier": 3,
"description": "企业级知识库系统,目前开发完善中,上线后服务全公司知识管理与智能检索。",
},
{
"key": "unibot", "name": "unibot(智能体平台)", "layer_id": "common", "dept": "",
"status": "running", "tech": "Python / Agent / MCP",
"tier": 0,
"description": "公司级 AI 智能体平台,经 MCP 总线向业务系统取数做经营分析,算力经 UniTensor 中转。",
},
# ---- 各部门业务系统 ----
{
"key": "kingdee", "name": "金蝶", "layer_id": "dept", "dept": "经营管理中心",
"status": "running", "tech": "金蝶 ERP",
"tier": 2,
"description": "财务管理/ERP 系统,用于经营管理中心的财务与业务一体化管理,付款/报销/开票在此完成记账。",
},
{
"key": "edrs", "name": "EDRS日报系统", "layer_id": "dept", "dept": "经营管理中心",
"status": "improving", "tech": "Vue / Java / MySQL",
"tier": 2,
"description": "员工日报填报与汇总系统,支撑经营数据报送与追踪,经 MCP 接入 unibot 做交叉分析。",
},
{
"key": "pms", "name": "PMS四算", "layer_id": "dept", "dept": "方案系统事业部、协同营销事业部",
"status": "running", "tech": "Java / MySQL",
"tier": 2,
"description": "项目四算管理系统(估算/概算/预算/决算),在合同与付款前提供预算闸门校验。",
},
{
"key": "oms", "name": "OMS", "layer_id": "dept", "dept": "云智产品事业部",
"status": "improving", "tech": "Java / Spring Boot / MySQL",
"tier": 2,
"description": "订单/运营管理系统,云智产品事业部核心业务系统,驱动采购、付款、开票的履约链路。",
},
{
"key": "dms", "name": "DMS新光线", "layer_id": "dept", "dept": "软件开发事业部",
"status": "running", "tech": "Java / MySQL",
"tier": 2,
"description": "研发/项目管理系统,定制项目信息与华智 OA 双向同步;调用 UniTensor 算力,经 MCP 接入 unibot。",
},
{
"key": "docs", "name": "docs文档系统", "layer_id": "dept", "dept": "软件开发事业部",
"status": "running", "tech": "Node.js / MongoDB",
"tier": 2,
"description": "在线文档协作系统,用于研发知识沉淀与文档共享;调用 UniTensor 中转的大模型算力并统计 token 消耗。",
},
{
"key": "gitea", "name": "Gitea代码仓", "layer_id": "dept", "dept": "软件开发事业部",
"status": "running", "tech": "Gitea / Docker",
"tier": 2,
"description": "自建 Git 代码托管平台,承载全公司研发代码协作,正常使用中。",
},
{
"key": "scc", "name": "SCC", "layer_id": "dept", "dept": "云智销售部",
"status": "improving", "tech": "Vue / Java / MySQL",
"tier": 2,
"description": "云智销售部业务系统(商机/客户/销售过程),商机备案与费用出差备案由此发起,签单后转 OMS 订单。",
},
# ---- 底座 ----
{
"key": "unitensor", "name": "UniTensor", "layer_id": "base", "dept": "",
"status": "improving", "tech": "Python / GPU / 推理服务",
"tier": 3,
"description": "底层基础组件/大模型算力中转平台,作为 Agent 与各系统推理请求的统一中转站。",
},
{
"key": "unihub", "name": "UniHub统一认证平台", "layer_id": "base", "dept": "",
"status": "improving", "tech": "OAuth2 / OIDC",
"tier": 3,
"description": "全公司统一身份认证中心(SSO)与智能体统一接入监管平台,为各系统提供登录认证与权限基础。",
},
{
"key": "k3s", "name": "k3s基础服务", "layer_id": "base", "dept": "",
"status": "running", "tech": "k3s / minIO / Docker Registry",
"tier": 3,
"description": "容器化微服务运行底座,统一纳管 fileview 文件预览、OCR 文字提取、minIO 对象存储、Docker 镜像仓库。",
},
{
"key": "dsh", "name": "DSH组件市场", "layer_id": "base", "dept": "",
"status": "improving", "tech": "前端组件 / npm 私服",
"tier": 3,
"description": "公司级组件市场,统一沉淀、共享与复用公共组件与通用能力,支撑业务系统快速集成。",
},
]
FLOW_TYPES = [
{
"id": "core", "name": "核心业务链路", "color": "#1d4ed8", "line_style": "solid",
"default_interval": 1800, "sort_order": 1,
"description": "预算→合同→订单→签单→归档的主业务闭环数据。",
},
{
"id": "entry", "name": "移动端入口 / 消息", "color": "#16a34a", "line_style": "dashed",
"default_interval": 300, "sort_order": 2,
"description": "企业微信作为移动端统一入口发起备案,并回传消息与通知。",
},
{
"id": "mcp", "name": "MCP 取数(Agent)", "color": "#a855f7", "line_style": "dash-dot",
"default_interval": 3600, "sort_order": 3,
"description": "unibot 经 MCP 总线向业务系统读取结构化数据做智能分析。",
},
{
"id": "cap", "name": "底座能力调用", "color": "#0ea5e9", "line_style": "solid",
"default_interval": 900, "sort_order": 4,
"description": "业务系统调用底座能力:算力推理、对象存储、OCR、文件预览。",
},
{
"id": "auth", "name": "统一认证(SSO)", "color": "#7c3aed", "line_style": "solid",
"default_interval": 300, "sort_order": 5,
"description": "各系统跳转 UniHub 完成票据校验与登录态同步。",
},
{
"id": "archive", "name": "归档 / 知识沉淀", "color": "#64748b", "line_style": "dash-dot",
"default_interval": 3600, "sort_order": 6,
"description": "合同原件归档、文档知识沉淀等低频大批量数据传输。",
},
]
# interval_sec / records / kb / latency describe the steady state of each link.
# peak_hours are the local hours (0-23) when the link is busiest.
FLOWS = [
# ---------- 核心业务闭环 ----------
dict(source="pms", target="oa", type="core", label="预算闸门", payload="预算/概算可用额度校验结果",
direction="bidirectional", interval_sec=1800, records_per_batch=42, avg_payload_kb=64,
latency_ms=180, reliability="sync", peak_hours=[9, 10, 11, 14, 15, 16, 17],
note="合同/付款审批前调用 PMS 预算闸门,审批结果回写占用与执行数。"),
dict(source="oa", target="oms", type="core", label="合同→订单", payload="合同编号、金额、客户、履约条款",
interval_sec=1800, records_per_batch=26, avg_payload_kb=96, latency_ms=220,
reliability="sync", peak_hours=[10, 11, 14, 15, 16, 17, 18],
note="合同审批通过后由 OA 推送结构化数据到 OMS 转订单。"),
dict(source="oms", target="scc", type="core", label="订单/签单回填", payload="订单状态、交付节点",
interval_sec=3600, records_per_batch=18, avg_payload_kb=48, latency_ms=260,
reliability="async", peak_hours=[9, 10, 15, 16, 17], note=None),
dict(source="scc", target="oms", type="core", label="归档转订单", payload="签单归档信息、开票抬头",
interval_sec=3600, records_per_batch=12, avg_payload_kb=40, latency_ms=240,
reliability="async", peak_hours=[16, 17, 18], note=None),
dict(source="oa", target="finance-bot", type="core", label="报销单据", payload="报销单、发票影像、成本中心",
interval_sec=900, records_per_batch=58, avg_payload_kb=220, latency_ms=320,
reliability="sync", peak_hours=[11, 12, 16, 17, 18], note="费用报销审批完成后推送财务数字助理做票据识别。"),
dict(source="finance-bot", target="kingdee", type="core", label="记账凭证", payload="凭证分录、票据号、金额",
interval_sec=3600, records_per_batch=35, avg_payload_kb=52, latency_ms=420,
reliability="async", peak_hours=[9, 10, 15, 16, 17, 18], note="识别通过的单据由财务在金蝶完成记账。"),
dict(source="dms", target="oa", type="core", label="项目信息同步", payload="定制项目主数据、里程碑",
direction="bidirectional", interval_sec=3600, records_per_batch=30, avg_payload_kb=88,
latency_ms=280, reliability="sync", peak_hours=[10, 11, 14, 15, 16],
note="定制项目信息接口保留不变,双向同步。"),
# ---------- 企业微信入口 ----------
dict(source="oa", target="wecom", type="entry", label="待办/收款群通知", payload="审批待办卡片、收款群消息",
interval_sec=300, records_per_batch=120, avg_payload_kb=12, latency_ms=160,
reliability="async", peak_hours=[9, 10, 11, 14, 15, 16, 17, 18]),
dict(source="wecom", target="finance-bot", type="entry", label="导出PDF报销", payload="移动端报销 PDF、票据照片",
interval_sec=1800, records_per_batch=20, avg_payload_kb=480, latency_ms=620,
reliability="async", peak_hours=[12, 17, 18, 19], note="员工在企微端上传 PDF,由财务助理识别。"),
dict(source="scc", target="wecom", type="entry", label="商机备案", payload="商机备案表单、客户名称",
interval_sec=1800, records_per_batch=15, avg_payload_kb=24, latency_ms=200,
reliability="sync", peak_hours=[10, 11, 15, 16, 17]),
dict(source="pms", target="wecom", type="entry", label="概算备案", payload="概算编号、项目归属",
interval_sec=3600, records_per_batch=10, avg_payload_kb=18, latency_ms=190,
reliability="sync", peak_hours=[10, 11, 14, 15]),
dict(source="wecom", target="edrs", type="entry", label="填报提醒", payload="日报催办与填报回执",
interval_sec=3600, records_per_batch=90, avg_payload_kb=8, latency_ms=150,
reliability="async", peak_hours=[9, 18, 19, 20], note="早间提醒与日终催办。"),
# ---------- MCP 取数 ----------
dict(source="unibot", target="pms", type="mcp", label="MCP 取数", payload="四算执行进度、预算占用",
direction="bidirectional", interval_sec=3600, records_per_batch=200, avg_payload_kb=180,
latency_ms=520, reliability="sync", peak_hours=[9, 10, 14, 15, 16]),
dict(source="unibot", target="oms", type="mcp", label="MCP 取数", payload="订单履约与回款进度",
direction="bidirectional", interval_sec=3600, records_per_batch=220, avg_payload_kb=196,
latency_ms=540, reliability="sync", peak_hours=[9, 10, 14, 15, 16]),
dict(source="unibot", target="scc", type="mcp", label="MCP 取数", payload="商机漏斗与签单数据",
direction="bidirectional", interval_sec=3600, records_per_batch=160, avg_payload_kb=140,
latency_ms=500, reliability="sync", peak_hours=[9, 10, 15, 16, 17]),
dict(source="unibot", target="edrs", type="mcp", label="MCP 取数", payload="日报投入工时与经营口径数据",
direction="bidirectional", interval_sec=3600, records_per_batch=180, avg_payload_kb=120,
latency_ms=480, reliability="sync", peak_hours=[9, 18, 19]),
dict(source="unibot", target="unitensor", type="mcp", label="Agent 算力中转", payload="推理请求与返回 token",
direction="bidirectional", interval_sec=60, records_per_batch=480, avg_payload_kb=320,
latency_ms=900, reliability="sync", peak_hours=list(range(8, 21)),
note="Agent 推理全部经 UniTensor 中转站。"),
# ---------- 底座能力调用 ----------
dict(source="docs", target="unitensor", type="cap", label="调用算力·统计token", payload="文档摘要/问答推理请求",
interval_sec=300, records_per_batch=320, avg_payload_kb=260, latency_ms=760,
reliability="async", peak_hours=list(range(9, 19))),
dict(source="dms", target="unitensor", type="cap", label="调用算力", payload="代码辅助推理请求",
interval_sec=600, records_per_batch=200, avg_payload_kb=210, latency_ms=700,
reliability="async", peak_hours=[10, 11, 14, 15, 16, 17]),
dict(source="finance-bot", target="k3s", type="cap", label="文件预览/OCR/对象存储", payload="发票影像、识别中间件",
interval_sec=900, records_per_batch=90, avg_payload_kb=1500, latency_ms=520,
reliability="sync", peak_hours=[11, 12, 16, 17, 18]),
dict(source="scc", target="k3s", type="cap", label="对象存储", payload="商机附件、资质材料",
interval_sec=1800, records_per_batch=45, avg_payload_kb=2200, latency_ms=580,
reliability="async", peak_hours=[10, 11, 14, 15, 16]),
dict(source="docs", target="k3s", type="cap", label="文件预览", payload="文档预览渲染对象",
interval_sec=900, records_per_batch=150, avg_payload_kb=880, latency_ms=340,
reliability="async", peak_hours=list(range(9, 19))),
dict(source="dms", target="k3s", type="cap", label="镜像仓库", payload="构建镜像层",
interval_sec=3600, records_per_batch=12, avg_payload_kb=64000, latency_ms=1200,
reliability="async", peak_hours=[11, 17, 18], note="CI 构建推送镜像,单次体量大、频次低。"),
dict(source="dms", target="gitea", type="cap", label="CI 触发", payload="流水线触发与构建回调",
direction="bidirectional", interval_sec=600, records_per_batch=35, avg_payload_kb=36,
latency_ms=280, reliability="async", peak_hours=[10, 11, 14, 15, 16, 17]),
dict(source="dms", target="dsh", type="cap", label="组件发布/拉取", payload="公共组件包版本",
interval_sec=86400, records_per_batch=6, avg_payload_kb=12000, latency_ms=1500,
reliability="async", peak_hours=[15, 16, 17], note="组件市场发布节奏按工作日估算。"),
# ---------- 统一认证 ----------
dict(source="oa", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=300, records_per_batch=400, avg_payload_kb=4, latency_ms=90,
reliability="sync", peak_hours=[9, 10, 13, 14, 15, 16, 17]),
dict(source="pms", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=600, records_per_batch=120, avg_payload_kb=4, latency_ms=90,
reliability="sync", peak_hours=[9, 10, 14, 15, 16]),
dict(source="oms", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=600, records_per_batch=150, avg_payload_kb=4, latency_ms=95,
reliability="sync", peak_hours=[9, 10, 14, 15, 16, 17]),
dict(source="scc", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=600, records_per_batch=110, avg_payload_kb=4, latency_ms=92,
reliability="sync", peak_hours=[9, 10, 14, 15, 16, 17]),
dict(source="dms", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=600, records_per_batch=70, avg_payload_kb=4, latency_ms=88,
reliability="sync", peak_hours=[10, 11, 14, 15, 16]),
dict(source="docs", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=600, records_per_batch=95, avg_payload_kb=4, latency_ms=86,
reliability="sync", peak_hours=list(range(9, 19))),
dict(source="gitea", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=900, records_per_batch=60, avg_payload_kb=4, latency_ms=85,
reliability="sync", peak_hours=[10, 11, 14, 15, 16, 17]),
dict(source="ekb", target="unihub", type="auth", label="SSO 票据校验", payload="OIDC token 交换",
interval_sec=1800, records_per_batch=25, avg_payload_kb=4, latency_ms=90,
reliability="sync", peak_hours=[10, 11, 15, 16]),
# ---------- 归档 / 知识沉淀 ----------
dict(source="oa", target="nas", type="archive", label="盖章合同原件归档", payload="盖章合同 PDF 原件",
interval_sec=3600, records_per_batch=8, avg_payload_kb=24000, latency_ms=1800,
reliability="async", peak_hours=[16, 17, 18], note="流程走完后归档,单文件体量大。"),
dict(source="docs", target="ekb", type="archive", label="知识沉淀同步", payload="结项文档、方案模板",
interval_sec=3600, records_per_batch=22, avg_payload_kb=3600, latency_ms=900,
reliability="async", peak_hours=[17, 18, 19]),
dict(source="unibot", target="ekb", type="archive", label="企业知识检索", payload="RAG 检索与向量召回",
direction="bidirectional", interval_sec=600, records_per_batch=260, avg_payload_kb=640,
latency_ms=1100, reliability="sync", peak_hours=list(range(9, 19))),
]
DEFAULT_SETTINGS = {
"site_title": "公司 IT 系统全景与数据流向平台",
"site_subtitle": "① 系统全景总览 | ② 数据流向图(实时流动)",
"editing_enabled": True,
"animation_enabled": True,
"animation_speed": 1.0,
"live_mode": True,
"live_interval_sec": 15,
"default_range_days": 7,
"metric_seed": "it-panorama-seed-v1",
# 折线 (正交走线) reads best in a report, so it is the shipped default; 曲线 / 直线 stay one click away.
"flow_route_style": "elbow",
}
def already_seeded(conn: sqlite3.Connection) -> bool:
row = conn.execute("SELECT COUNT(*) AS c FROM systems").fetchone()
return bool(row and row["c"])
def seed(conn: sqlite3.Connection) -> bool:
"""Populate a fresh database. Returns True when seeding actually ran."""
if already_seeded(conn):
return False
now = utcnow()
with transaction(conn):
for layer in LAYERS:
conn.execute(
"INSERT INTO layers (id, name, short_name, color, description, sort_order) VALUES (?,?,?,?,?,?)",
(layer["id"], layer["name"], layer["short_name"], layer["color"], layer["description"], layer["sort_order"]),
)
for index, system in enumerate(SYSTEMS):
conn.execute(
"""INSERT INTO systems (key, name, layer_id, dept, status, tech, url, domain, owner,
description, tier, sort_order, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
system["key"], system["name"], system["layer_id"], system.get("dept", ""),
system["status"], system.get("tech", ""), system.get("url", ""), system.get("domain", ""),
system.get("owner", ""), system["description"], system["tier"], index, now, now,
),
)
for flow_type in FLOW_TYPES:
conn.execute(
"""INSERT INTO flow_types (id, name, color, line_style, default_interval, description, sort_order)
VALUES (?,?,?,?,?,?,?)""",
(
flow_type["id"], flow_type["name"], flow_type["color"], flow_type["line_style"],
flow_type["default_interval"], flow_type["description"], flow_type["sort_order"],
),
)
for index, flow in enumerate(FLOWS):
conn.execute(
"""INSERT INTO data_flows (source_key, target_key, flow_type_id, label, payload, direction,
interval_sec, records_per_batch, avg_payload_kb, latency_ms,
reliability, peak_hours, enabled, note, sort_order, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(
flow["source"], flow["target"], flow["type"], flow["label"], flow.get("payload") or "",
flow.get("direction") or "forward", flow["interval_sec"], flow["records_per_batch"],
flow["avg_payload_kb"], flow["latency_ms"], flow.get("reliability", "async"),
json_dump(flow["peak_hours"]), 1, flow.get("note") or "", index, now, now,
),
)
for key, value in DEFAULT_SETTINGS.items():
set_setting(conn, key, value)
return True
def ensure_graph_shape(conn: sqlite3.Connection) -> None:
"""Fill tier ranks derived from the flow graph when they look unset."""
rows = conn.execute("SELECT DISTINCT tier FROM systems").fetchall()
if len(rows) >= 2:
return
conn.executescript("UPDATE systems SET tier = 2;")

View File

@ -0,0 +1 @@
"""Domain services."""

View File

@ -0,0 +1,211 @@
"""Build the data-flow graph payload consumed by the frontend.
The frontend does no topology work of its own: it receives node ranks plus edge
endpoints, so the picture stays stable across reloads and both the web app and any
future client render exactly the same graph.
"""
from __future__ import annotations
import sqlite3
from collections import defaultdict, deque
from ..db import all_
from . import metrics
from .metrics import parse_peak_hours
# Column meaning inside the data-flow graph; mirrors TIER_LABELS in the frontend.
TIER_LABELS = ('统一入口层', '审批 / 流程中枢', '业务系统层', '底座能力层')
def tier_label(tier: int) -> str:
try:
return TIER_LABELS[tier]
except IndexError:
return f'第 {tier + 1} 层'
def load_systems(conn: sqlite3.Connection) -> list[dict]:
return all_(
conn,
"""SELECT s.*, l.name AS layer_name, l.short_name AS layer_short_name, l.color AS layer_color
FROM systems s LEFT JOIN layers l ON l.id = s.layer_id
ORDER BY s.sort_order, s.id""",
)
def load_flows(conn: sqlite3.Connection) -> list[dict]:
return all_(
conn,
"""SELECT f.*, t.name AS flow_type_name, t.color AS flow_type_color,
t.line_style AS flow_type_line_style, t.default_interval AS flow_type_default_interval,
s.name AS source_name, g.name AS target_name,
s.tier AS source_tier, g.tier AS target_tier
FROM data_flows f
JOIN flow_types t ON t.id = f.flow_type_id
JOIN systems s ON s.key = f.source_key
JOIN systems g ON g.key = f.target_key
ORDER BY f.sort_order, f.id""",
)
def compute_depth(systems: list[dict], flows: list[dict]) -> dict[str, int]:
"""Longest-path depth from any source node, used only as a layout hint.
Tiers stay authoritative for the visible columns; depth merely flags nodes whose
declared tier disagrees with the direction of their edges, which is what the
"layout suggestions" panel reports.
"""
adjacency: dict[str, list[str]] = defaultdict(list)
indegree: dict[str, int] = {s["key"]: 0 for s in systems}
for flow in flows:
if not flow["enabled"]:
continue
# Bidirectional links say nothing about ordering, so they must not push a
# node to the right; only strict one-way traffic implies a downstream rank.
if flow.get("direction") == "bidirectional":
continue
source, target = flow["source_key"], flow["target_key"]
if source not in indegree or target not in indegree:
continue
adjacency[source].append(target)
indegree[target] += 1
depth = dict.fromkeys(indegree, 0)
degrees = dict(indegree)
queue = deque(sorted(key for key, degree in degrees.items() if degree == 0))
while queue:
node = queue.popleft()
for nxt in adjacency[node]:
depth[nxt] = max(depth[nxt], depth[node] + 1)
degrees[nxt] -= 1
if degrees[nxt] == 0:
queue.append(nxt)
return depth
def layout_suggestions(systems: list[dict], depth: dict[str, int]) -> list[dict]:
"""Flag nodes whose declared tier trails the depth implied by their incoming edges."""
hints = []
for system in systems:
implied = depth.get(system["key"], 0)
declared = int(system["tier"])
if implied > declared:
hints.append({
"key": system["key"],
"name": system["name"],
"tier": declared,
"implied_depth": implied,
"reason": "上游链路深度大于当前层级,数据显示它可能应放在更靠右的列",
})
return hints
def build_graph(conn: sqlite3.Connection, *, days: int = 7, include_disabled: bool = False) -> dict:
metrics.ensure_history(conn)
systems = load_systems(conn)
flows = load_flows(conn)
health = metrics.flow_health(conn, days=days)
active = [f for f in flows if f["enabled"]] if not include_disabled else flows
depth = compute_depth(systems, active)
ranks = {s["key"]: int(s["tier"]) for s in systems}
degree: dict[str, int] = defaultdict(int)
for flow in active:
degree[flow["source_key"]] += 1
degree[flow["target_key"]] += 1
nodes = []
for system in systems:
key = system["key"]
node_health = [health.get(f["id"], {}).get("health") for f in active
if key in (f["source_key"], f["target_key"])]
nodes.append({
"key": key,
"name": system["name"],
"layer_id": system["layer_id"],
"layer_name": system["layer_name"],
"layer_color": system["layer_color"],
"dept": system["dept"],
"status": system["status"],
"tech": system["tech"],
"url": system["url"],
"domain": system["domain"],
"owner": system["owner"],
"impl_time": system.get("impl_time") or "",
"entry_enabled": bool(system.get("entry_enabled", 1)),
"description": system["description"],
"tier": int(system["tier"]),
"flow_x": system.get("flow_x"),
"flow_y": system.get("flow_y"),
"rank": ranks.get(key, int(system["tier"])),
"depth": depth.get(key, 0),
"degree": degree[key],
"out_count": sum(1 for f in active if f["source_key"] == key),
"in_count": sum(1 for f in active if f["target_key"] == key),
"health": (
"risk" if "risk" in node_health else
"watch" if "watch" in node_health else
"healthy" if node_health else "idle"
),
})
edges = []
for flow in flows:
if not include_disabled and not flow["enabled"]:
continue
h = health.get(flow["id"], {})
edges.append({
"id": flow["id"],
"source_key": flow["source_key"],
"target_key": flow["target_key"],
"source_name": flow["source_name"],
"target_name": flow["target_name"],
"flow_type_id": flow["flow_type_id"],
"flow_type_name": flow["flow_type_name"],
"color": flow["flow_type_color"],
"line_style": flow["flow_type_line_style"],
"label": flow["label"],
"payload": flow["payload"],
"direction": flow["direction"],
"interval_sec": flow["interval_sec"],
"records_per_batch": flow["records_per_batch"],
"avg_payload_kb": flow["avg_payload_kb"],
"latency_ms": flow["latency_ms"],
"reliability": flow["reliability"],
"peak_hours": sorted(parse_peak_hours(flow["peak_hours"])),
"enabled": bool(flow["enabled"]),
"note": flow["note"],
"throughput_rps": metrics.throughput_rps(flow, h),
"payload_mb_per_hour": metrics.payload_rps(flow),
"health": {
"batches": h.get("batches", 0),
"records": h.get("records", 0),
"bytes": h.get("bytes", 0),
"errors": h.get("errors", 0),
"error_rate": h.get("error_rate", 0),
"avg_latency_ms": h.get("avg_latency_ms", flow["latency_ms"]),
"peak_hour_records": h.get("peak_hour_records", 0),
"state": h.get("health", "idle"),
},
})
return {
"nodes": nodes,
"edges": edges,
"ranks": ranks,
"rank_count": (max(ranks.values()) + 1) if ranks else 0,
"suggestions": layout_suggestions(systems, depth),
# Topology counts belong to the graph itself, so the flow canvas needs no second
# request (and no traffic metrics) just to label its own header.
"counts": {
"systems": len(systems),
"layers": len({system["layer_id"] for system in systems if system["layer_id"]}),
"tiers": len({int(system["tier"]) for system in systems}),
"flows_total": len(flows),
"flows_enabled": sum(1 for flow in flows if flow["enabled"]),
"linked_systems": sum(1 for system in systems if degree[system["key"]]),
},
}

View File

@ -0,0 +1,288 @@
"""Flow metrics: deterministic history generation plus live increments.
Each flow row carries a steady-state cadence (interval, batch size, payload). The
hourly history is derived from that cadence with a seeded jitter so the graph has
real numbers to animate against, and re-generating the same day always yields the
same figures. The live tick then adds small increments on top so the picture moves
while somebody is watching it.
"""
from __future__ import annotations
import json
import random
import sqlite3
from datetime import date, datetime, timedelta
from ..db import all_, json_dump, setting, transaction, utcnow
# Weekday shape: the company works during business hours, quieter at night.
NIGHT_FACTOR = 0.06
WEEKEND_FACTOR = 0.18
PEAK_CURVE = {
0: 0.05, 1: 0.04, 2: 0.03, 3: 0.03, 4: 0.03, 5: 0.04,
6: 0.07, 7: 0.12, 8: 0.35, 9: 0.78, 10: 1.00, 11: 0.92,
12: 0.42, 13: 0.55, 14: 0.96, 15: 1.00, 16: 0.94, 17: 0.86,
18: 0.46, 19: 0.30, 20: 0.22, 21: 0.15, 22: 0.10, 23: 0.07,
}
def parse_peak_hours(raw) -> list[int]:
"""Accept either the stored JSON string or an already decoded list."""
if isinstance(raw, str):
try:
raw = json.loads(raw or "[]")
except json.JSONDecodeError:
return []
if not isinstance(raw, (list, tuple, set)):
return []
return {int(v) for v in raw if isinstance(v, (int, float)) and 0 <= int(v) <= 23}
def hour_weight(hour: int, peak_hours, reliability: str) -> float:
"""Relative activity for one hour, blending the global curve with flow peaks."""
peak_hours = parse_peak_hours(peak_hours)
base = PEAK_CURVE.get(hour, 0.1)
if hour in peak_hours:
base = max(base, 0.62 + 0.38 * PEAK_CURVE.get(hour, 0.1))
if reliability == "sync":
# Interactive links track head-office hours closely.
base *= 1.0
else:
# Batch jobs keep a low background trickle outside office hours.
base = max(base, 0.12)
return max(0.02, min(1.4, base))
def expected_batches(flow: dict, hour: int) -> float:
interval = max(30, int(flow["interval_sec"] or 3600))
capacity = 3600.0 / interval
return capacity * hour_weight(hour, flow["peak_hours"], flow["reliability"])
def _rng(seed: str, flow_id: int, day: str, hour: int) -> random.Random:
return random.Random(f"{seed}|{flow_id}|{day}|{hour}")
def day_is_weekend(day: date) -> bool:
return day.weekday() >= 5
def compute_bucket(flow: dict, day: date, hour: int, seed: str) -> dict:
"""Deterministic metric bucket for one flow/hour."""
rng = _rng(seed, flow["id"], day.isoformat(), hour)
weight = hour_weight(hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(day) else 1.0
expected = expected_batches(flow, hour) * factor
jitter = rng.uniform(0.72, 1.32)
batches = max(0, int(round(expected * jitter)))
if batches == 0 and rng.random() < 0.12 * weight:
batches = 1
per_batch = max(1, int(flow["records_per_batch"]))
records = int(round(batches * per_batch * rng.uniform(0.8, 1.24))) if batches else 0
kb = float(flow["avg_payload_kb"] or 1.0)
payload_bytes = int(round(batches * kb * 1024 * rng.uniform(0.78, 1.3)))
# Occasional degraded window on async links so the health view has variety.
error_rate = 0.004 if flow["reliability"] == "async" else 0.001
errors = int(round(records * error_rate * rng.choice([0, 0, 0, 1, 1, 2, 6])))
latency = int(round(int(flow["latency_ms"]) * rng.uniform(0.82, 1.45)))
return {
"day": day.isoformat(),
"hour": hour,
"batches": batches,
"records": records,
"bytes": payload_bytes,
"errors": errors,
"latency_ms": latency,
}
def upsert_bucket(conn: sqlite3.Connection, flow_id: int, bucket: dict) -> None:
conn.execute(
"""INSERT INTO flow_metrics (flow_id, day, hour, batches, records, bytes, errors, latency_ms)
VALUES (?,?,?,?,?,?,?,?)
ON CONFLICT(flow_id, day, hour) DO UPDATE SET
batches = excluded.batches,
records = excluded.records,
bytes = excluded.bytes,
errors = excluded.errors,
latency_ms = excluded.latency_ms""",
(
flow_id, bucket["day"], bucket["hour"], bucket["batches"],
bucket["records"], bucket["bytes"], bucket["errors"], bucket["latency_ms"],
),
)
def ensure_history(conn: sqlite3.Connection, days: int = 30) -> None:
"""Backfill hourly history for any flow that does not have its own rows yet.
Checked per flow rather than globally so links added after the first run still
get a believable history instead of rendering as dead edges.
"""
flows = all_(
conn,
"""SELECT f.* FROM data_flows f
WHERE NOT EXISTS (SELECT 1 FROM flow_metrics m WHERE m.flow_id = f.id)""",
)
if not flows:
return
seed = str(setting(conn, "metric_seed", "it-panorama-seed-v1"))
today = date.today()
with transaction(conn):
for flow in flows:
for offset in range(days, 0, -1):
day = today - timedelta(days=offset)
for hour in range(24):
upsert_bucket(conn, flow["id"], compute_bucket(flow, day, hour, seed))
# Today only up to the current hour so the graph never claims future traffic.
day = today
for hour in range(datetime.now().hour + 1):
upsert_bucket(conn, flow["id"], compute_bucket(flow, day, hour, seed))
def live_tick(conn: sqlite3.Connection) -> dict:
"""Advance the current hour by one live step. Returns a compact summary."""
seed = str(setting(conn, "metric_seed", "it-panorama-seed-v1"))
now = datetime.now()
today = now.date()
hour = now.hour
rng = random.Random(f"live|{seed}|{today.isoformat()}|{hour}|{int(now.timestamp() // 7)}")
flows = all_(conn, "SELECT * FROM data_flows WHERE enabled = 1")
touched = 0
with transaction(conn):
for flow in flows:
weight = hour_weight(hour, flow["peak_hours"], flow["reliability"])
probability = min(0.95, weight * 0.85)
if rng.random() > probability:
continue
expected = expected_batches(flow, hour) / 24.0
batches = max(1, int(round(expected * rng.uniform(0.6, 2.2))))
conn.execute(
"""INSERT INTO flow_metrics (flow_id, day, hour, batches, records, bytes, errors, latency_ms)
VALUES (?,?,?,?,?,?,?,?)
ON CONFLICT(flow_id, day, hour) DO UPDATE SET
batches = batches + excluded.batches,
records = records + excluded.records,
bytes = bytes + excluded.bytes,
errors = errors + excluded.errors,
latency_ms = (latency_ms * 3 + excluded.latency_ms) / 4""",
(
flow["id"], today.isoformat(), hour, batches,
int(round(batches * flow["records_per_batch"] * rng.uniform(0.85, 1.3))),
int(round(batches * float(flow["avg_payload_kb"]) * 1024 * rng.uniform(0.85, 1.25))),
1 if (flow["reliability"] == "async" and rng.random() < 0.05) else 0,
int(round(int(flow["latency_ms"]) * rng.uniform(0.85, 1.4))),
),
)
touched += 1
conn.execute("INSERT INTO settings (key, value, updated_at) VALUES ('last_live_tick', ?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
(json_dump(now.replace(microsecond=0).isoformat()), utcnow()))
return {"touched": touched, "at": now.replace(microsecond=0).isoformat()}
def totals(conn: sqlite3.Connection, days: int) -> dict:
"""Rolling totals used by the KPI cards."""
start = (date.today() - timedelta(days=days - 1)).isoformat()
row = conn.execute(
"""SELECT COALESCE(SUM(m.batches),0) AS batches, COALESCE(SUM(m.records),0) AS records,
COALESCE(SUM(m.bytes),0) AS bytes, COALESCE(SUM(m.errors),0) AS errors,
AVG(NULLIF(m.latency_ms,0)) AS avg_latency
FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
WHERE f.enabled = 1 AND m.day >= ?""",
(start,),
).fetchone()
active = conn.execute(
"""SELECT COUNT(*) AS c FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
WHERE f.enabled = 1 AND m.day >= ? AND m.records > 0""",
(start,),
).fetchone()
return {
"batches": int(row["batches"] or 0),
"records": int(row["records"] or 0),
"bytes": int(row["bytes"] or 0),
"errors": int(row["errors"] or 0),
"avg_latency_ms": int(round(row["avg_latency"] or 0)),
"active_buckets": int(active["c"] or 0),
}
def series_for_day(conn: sqlite3.Connection, day: str) -> list[dict]:
return all_(
conn,
"""SELECT flow_id, hour, batches, records, bytes, errors, latency_ms
FROM flow_metrics WHERE day = ? ORDER BY flow_id, hour""",
(day,),
)
def hourly_series(conn: sqlite3.Connection, flow_id: int, days: int) -> list[dict]:
start = (date.today() - timedelta(days=days - 1)).isoformat()
return all_(
conn,
"""SELECT day, hour, batches, records, bytes, errors, latency_ms FROM flow_metrics
WHERE flow_id = ? AND day >= ? ORDER BY day, hour""",
(flow_id, start),
)
def health_label(error_rate: float, latency_ms: int) -> str:
if error_rate >= 0.02:
return "risk"
if error_rate >= 0.005 or latency_ms >= 900:
return "watch"
return "healthy"
def flow_health(conn: sqlite3.Connection, days: int = 7) -> dict[int, dict]:
"""Per-flow aggregate health over the trailing window."""
start = (date.today() - timedelta(days=days - 1)).isoformat()
rows = all_(
conn,
"""SELECT flow_id, SUM(batches) AS batches, SUM(records) AS records, SUM(bytes) AS bytes,
SUM(errors) AS errors, AVG(NULLIF(latency_ms,0)) AS latency,
MAX(records) AS peak_records
FROM flow_metrics WHERE day >= ? GROUP BY flow_id""",
(start,),
)
out: dict[int, dict] = {}
for row in rows:
records = int(row["records"] or 0)
errors = int(row["errors"] or 0)
latency = int(round(row["latency"] or 0))
rate = (errors / records) if records else 0.0
out[int(row["flow_id"])] = {
"batches": int(row["batches"] or 0),
"records": records,
"bytes": int(row["bytes"] or 0),
"errors": errors,
"error_rate": round(rate, 5),
"avg_latency_ms": latency,
"peak_hour_records": int(row["peak_records"] or 0),
"health": health_label(rate, latency),
}
return out
def throughput_rps(flow: dict, health: dict | None) -> float:
"""Records per second used to drive particle density and speed on the client."""
interval = max(30, int(flow["interval_sec"] or 3600))
weight = hour_weight(datetime.now().hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(date.today()) else 1.0
per_hour = (3600.0 / interval) * weight * factor * int(flow["records_per_batch"])
return round(per_hour / 3600.0, 4)
def payload_rps(flow: dict) -> float:
interval = max(30, int(flow["interval_sec"] or 3600))
weight = hour_weight(datetime.now().hour, flow["peak_hours"], flow["reliability"])
factor = WEEKEND_FACTOR if day_is_weekend(date.today()) else 1.0
return round((3600.0 / interval) * weight * factor * float(flow["avg_payload_kb"]) / 1024.0, 4)
__all__ = [
"compute_bucket", "ensure_history", "live_tick", "totals", "series_for_day",
"hourly_series", "flow_health", "throughput_rps", "payload_rps", "hour_weight", "parse_peak_hours"
]

BIN
backend/panorama.db 100644

Binary file not shown.

View File

@ -0,0 +1,3 @@
-r requirements.txt
pytest>=8.0
httpx>=0.27

View File

@ -0,0 +1,3 @@
fastapi>=0.115
uvicorn[standard]>=0.30
pydantic>=2.7

13
backend/run.py 100644
View File

@ -0,0 +1,13 @@
"""Development entrypoint: python run.py"""
import os
import uvicorn
if __name__ == "__main__":
uvicorn.run(
"app.main:app",
host=os.environ.get("HOST", "0.0.0.0"),
port=int(os.environ.get("PORT", 8787)),
reload=bool(os.environ.get("RELOAD")),
)

View File

@ -0,0 +1,39 @@
"""Shared fixtures. Tests run against a throwaway database per test."""
from __future__ import annotations
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
class FakeRequest:
"""Minimal stand-in for starlette's Request: routers only read the editor header."""
def __init__(self, actor: str = "测试员") -> None:
self.headers = {"X-Editor": actor}
@pytest.fixture()
def db(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "test.db"))
from app import config
monkeypatch.setattr(config, "db_path", lambda: tmp_path / "test.db")
from app.db import connect, init_db
from app.seed import seed
init_db()
conn = connect()
seed(conn)
yield conn
conn.close()
@pytest.fixture()
def request_():
return FakeRequest()

View File

@ -0,0 +1,404 @@
"""End-to-end HTTP tests against the real ASGI app, including static hosting."""
from __future__ import annotations
import pytest
from fastapi.testclient import TestClient
@pytest.fixture()
def client(tmp_path, monkeypatch):
monkeypatch.setenv("DB_PATH", str(tmp_path / "api.db"))
from app import config
monkeypatch.setattr(config, "db_path", lambda: tmp_path / "api.db")
from app.main import app
with TestClient(app) as instance:
yield instance
# ------------------------------------------------------------------ read models
def test_health_and_seed(client):
assert client.get("/api/health").status_code == 200
assert client.get("/api/layers").json().__len__() == 3
assert len(client.get("/api/systems").json()) == 18
assert len(client.get("/api/flow-types").json()) == 6
assert len(client.get("/api/flows").json()) == 36
def test_graph_payload_is_animation_ready(client):
graph = client.get("/api/graph?days=7").json()
assert len(graph["nodes"]) == 18 and len(graph["edges"]) == 36
for edge in graph["edges"]:
# the frontend layout keys edges by endpoint key and animates on these numbers
assert edge["source_key"] and edge["target_key"]
assert edge["color"] and edge["line_style"]
assert edge["throughput_rps"] >= 0
assert edge["health"]["state"] in {"healthy", "watch", "risk", "idle"}
assert {node["rank"] for node in graph["nodes"]} == {node["tier"] for node in graph["nodes"]}
def test_metrics_endpoints_agree(client):
summary = client.get("/api/metrics/summary?days=7").json()
assert summary["totals"]["records"] > 0
hourly = client.get("/api/metrics/hourly?days=2").json()
assert hourly["points"], "hourly curve must not be empty"
live = client.get("/api/metrics/live").json()
assert len(live["flows"]) == 36
def test_flow_series_and_audit(client):
flow_id = client.get("/api/flows").json()[0]["id"]
series = client.get(f"/api/metrics/flows/{flow_id}?days=3").json()
assert series["points"]
assert client.get("/api/metrics/flows/999999").status_code == 404
assert isinstance(client.get("/api/audit?limit=10").json(), list)
# ------------------------------------------------------------------ writes over HTTP
def test_system_crud_and_validation_over_http(client):
created = client.post("/api/systems", json={"key": "http-demo", "name": "HTTP 系统", "layer_id": "base"})
assert created.status_code == 201
assert created.json()["layer_name"] == "底座(基础平台)"
assert client.post("/api/systems", json={"key": "http-demo", "name": "重复"}).status_code == 409
assert client.post("/api/systems", json={"key": "x", "name": "无层级", "layer_id": "ghost"}).status_code == 400
assert client.patch("/api/systems/http-demo", json={"status": "dev"}).json()["status"] == "dev"
assert client.patch("/api/systems/ghost", json={"status": "dev"}).status_code == 404
assert client.delete("/api/layers/base").status_code == 409, "层级仍被使用时不得删除"
assert client.delete("/api/systems/http-demo").json()["ok"] is True
def test_flow_guardrails_over_http(client):
base = {"source_key": "pms", "target_key": "kingdee", "flow_type_id": "core", "label": "HTTP 链路"}
created = client.post("/api/flows", json=base)
assert created.status_code == 201
assert created.json()["peak_hours"] == [9, 10, 11, 14, 15, 16, 17]
assert client.post("/api/flows", json=base).status_code == 409
assert client.post("/api/flows", json={**base, "target_key": "pms"}).status_code == 400
assert client.post("/api/flows", json={**base, "interval_sec": 1}).status_code == 422
flow_id = created.json()["id"]
assert client.patch(f"/api/flows/{flow_id}", json={"enabled": False}).json()["enabled"] is False
assert client.delete(f"/api/flows/{flow_id}").json()["ok"] is True
def test_editor_header_roundtrips_chinese_names(client):
"""The browser cannot put Chinese text in a header, so the client percent-encodes it."""
encoded = "%E5%BA%B7%E6%96%87%E6%99%B6"
client.post("/api/systems", json={"key": "hdr", "name": "请求头系统"}, headers={"X-Editor": encoded})
latest = client.get("/api/audit?limit=1").json()[0]
assert latest["actor"] == "康文晶"
def test_settings_patch_is_partial(client):
before = client.get("/api/settings").json()
updated = client.patch("/api/settings", json={"live_interval_sec": 30}).json()
assert updated["live_interval_sec"] == 30
assert updated["site_title"] == before["site_title"], "未提交的配置必须保留"
# ------------------------------------------------------------------ system fields
def test_impl_time_and_entry_flag_roundtrip(client):
"""实现时间 is free-form text and the jump switch decides who shows a shortcut."""
created = client.post(
"/api/systems",
json={"key": "entry-demo", "name": "入口系统", "url": "https://x.example.com",
"impl_time": "2024-06 上线", "entry_enabled": False},
)
assert created.status_code == 201
assert created.json()["impl_time"] == "2024-06 上线"
assert created.json()["entry_enabled"] is False
patched = client.patch("/api/systems/entry-demo", json={"entry_enabled": True}).json()
assert patched["entry_enabled"] is True
assert client.patch("/api/systems/entry-demo", json={"impl_time": " "}).json()["impl_time"] == ""
node = next(n for n in client.get("/api/graph").json()["nodes"] if n["key"] == "entry-demo")
assert node["impl_time"] == "" and node["entry_enabled"] is True
def test_seeded_systems_carry_the_new_fields(client):
for system in client.get("/api/systems").json():
assert system["impl_time"] == ""
assert system["entry_enabled"] is True, "默认所有系统都可以展示快捷入口"
def test_system_name_can_be_renamed_after_creation(client):
"""系统名称 is an ordinary field: the only rule is "not blank", the key never moves."""
renamed = client.patch("/api/systems/oa", json={"name": " OA(华智 OA · 新版) "})
assert renamed.status_code == 200
assert renamed.json()["name"] == "OA(华智 OA · 新版)"
assert renamed.json()["key"] == "oa", "改名不改主键"
assert client.patch("/api/systems/oa", json={"name": " "}).status_code == 422
# The flow read model carries its own copy of the name, so a rename has to reach it.
graph = client.get("/api/graph").json()
node = next(item for item in graph["nodes"] if item["key"] == "oa")
assert node["name"] == "OA(华智 OA · 新版)"
edge = next(item for item in graph["edges"] if item["source_key"] == "oa")
assert edge["source_name"] == "OA(华智 OA · 新版)"
audit = client.get("/api/audit?limit=5").json()
assert any("name" in entry["summary"] for entry in audit)
# Over-long names are cut rather than rejected; the field is capped, not precious.
assert len(client.patch("/api/systems/oa", json={"name": "x" * 200}).json()["name"]) == 80
# ------------------------------------------------------------------ read-only switch
def test_read_only_lock_blocks_content_writes(client):
assert client.patch("/api/settings", json={"editing_enabled": False}).json()["editing_enabled"] is False
blocked = [
client.post("/api/systems", json={"key": "locked", "name": "锁定测试"}),
client.patch("/api/systems/oa", json={"name": "改名"}),
client.delete("/api/systems/oa"),
client.post("/api/layers", json={"id": "locked", "name": "锁定层"}),
client.post("/api/flow-types", json={"id": "locked", "name": "锁定类型"}),
client.post("/api/flows", json={"source_key": "oa", "target_key": "oms",
"flow_type_id": "core", "label": "锁定链路"}),
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 10, "y": 10}]}),
]
assert [response.status_code for response in blocked] == [423] * len(blocked)
assert "只读" in blocked[0].json()["detail"]
assert client.get("/api/systems").json(), "读取不受开关影响"
assert client.patch("/api/systems/oa", json={"name": "改名"}).status_code == 423
assert next(s for s in client.get("/api/systems").json() if s["key"] == "oa")["name"] != "改名"
def test_read_only_switch_can_be_turned_back_off(client):
"""Locking the platform must never lock the page that unlocks it."""
client.patch("/api/settings", json={"editing_enabled": False})
assert client.patch("/api/settings", json={"editing_enabled": True}).json()["editing_enabled"] is True
assert client.post("/api/systems", json={"key": "after", "name": "解锁后"}).status_code == 201
# A locked import is refused before anything is written.
client.patch("/api/settings", json={"editing_enabled": False})
payload = client.get("/api/backup").json()
assert client.post("/api/backup", json={**payload, "mode": "replace"}).status_code == 423
assert len(client.get("/api/systems").json()) == 19, "被拒绝的导入不得改动数据"
def test_live_metrics_still_run_while_locked(client):
"""实时推进 is a display clock, not a user edit, so it keeps ticking in read-only."""
client.patch("/api/settings", json={"editing_enabled": False})
assert client.post("/api/metrics/tick").status_code == 200
def test_matrix_endpoint_is_gone(client):
assert client.get("/api/metrics/matrix?days=7").status_code == 404
# ------------------------------------------------------------------ backup
def test_backup_export_then_merge_is_idempotent(client):
payload = client.get("/api/backup").json()
assert payload["systems"] and payload["data_flows"] and payload["schema_version"] == 1
result = client.post("/api/backup", json={**payload, "mode": "merge"}).json()
assert result["errors"] == []
assert len(client.get("/api/systems").json()) == 18, "按 id 合并不应产生重复"
def test_backup_replace_drops_orphans(client):
payload = client.get("/api/backup").json()
payload["systems"] = [s for s in payload["systems"] if s["key"] in {"oa", "pms"}]
result = client.post("/api/backup", json={**payload, "mode": "replace"}).json()
assert len(client.get("/api/systems").json()) == 2
assert any("端点系统不存在" in message for message in result["errors"])
# The restored graph must still render, and only the link whose endpoints both
# survived may remain.
graph = client.get("/api/graph?days=7").json()
assert len(graph["nodes"]) == 2
assert [(e["source_key"], e["target_key"]) for e in graph["edges"]] == [("pms", "oa")]
# History for the restored flow is rebuilt from its cadence rather than left blank.
assert graph["edges"][0]["health"]["records"] > 0
def test_backup_rejects_empty_payload(client):
assert client.post("/api/backup", json={}).status_code == 400
# ------------------------------------------------------------------ routing
def test_unknown_api_path_returns_json_404_not_the_spa_shell(client):
response = client.get("/api/does-not-exist")
assert response.status_code == 404
assert response.json() == {"detail": "接口不存在"}
def test_spa_routes_serve_the_built_app(client):
from app.config import WEB_DIST
if not WEB_DIST.is_dir():
pytest.skip("前端尚未构建,跳过静态托管校验")
for path in ("/", "/flow", "/panorama", "/config"):
response = client.get(path)
assert response.status_code == 200, path
assert "text/html" in response.headers["content-type"]
assert client.get("/favicon.svg").status_code == 200
# ------------------------------------------------------------------ canvas layout
def _node(client, key):
return next(node for node in client.get("/api/graph").json()["nodes"] if node["key"] == key)
def test_seeded_nodes_start_on_automatic_placement(client):
for node in client.get("/api/graph").json()["nodes"]:
assert node["flow_x"] is None and node["flow_y"] is None
def test_layout_endpoint_persists_positions_and_tier(client):
response = client.put(
"/api/graph/layout",
json={"items": [{"key": "oa", "x": 421.5, "y": 260, "tier": 2}]},
headers={"X-Editor": "%E5%BC%A0%E5%B7%A5"},
)
assert response.status_code == 200
assert response.json() == {"ok": True, "placed": 1, "cleared": 0, "moved": 1, "missing": []}
node = _node(client, "oa")
assert (node["flow_x"], node["flow_y"], node["tier"]) == (421.5, 260.0, 2)
audit = client.get("/api/audit").json()
assert len(audit) == 1, "a whole drag gesture is one audit entry, not one per card"
assert audit[0]["actor"] == "张工"
assert "手动摆放 1 个系统" in audit[0]["summary"]
def test_layout_tier_change_alone_keeps_the_dropped_position(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 120, "y": 80}]})
client.put("/api/graph/layout", json={"items": [{"key": "oa", "tier": 3}]})
node = _node(client, "oa")
assert (node["flow_x"], node["flow_y"], node["tier"]) == (120.0, 80.0, 3)
def test_layout_null_coordinates_return_a_card_to_auto_placement(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 10, "y": 20}]})
response = client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": None, "y": None}]})
assert response.json()["cleared"] == 1
node = _node(client, "oa")
assert node["flow_x"] is None and node["flow_y"] is None
def test_layout_reset_clears_every_manual_position(client):
client.put("/api/graph/layout", json={"items": [
{"key": "oa", "x": 10, "y": 20}, {"key": "pms", "x": 30, "y": 40},
]})
assert client.post("/api/graph/layout/reset").json() == {"ok": True, "cleared": 2}
assert all(node["flow_x"] is None for node in client.get("/api/graph").json()["nodes"])
def test_layout_reports_unknown_keys_and_rejects_runaway_coordinates(client):
response = client.put("/api/graph/layout", json={"items": [{"key": "ghost", "x": 5, "y": 5}]})
assert response.json()["missing"] == ["ghost"]
assert client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 999999}]}).status_code == 422
assert client.put("/api/graph/layout", json={"items": [{"key": "oa", "tier": 99}]}).status_code == 422
def test_empty_layout_write_is_not_audited(client):
assert client.put("/api/graph/layout", json={"items": []}).status_code == 200
assert client.get("/api/audit").json() == []
def test_new_system_can_be_born_at_a_canvas_position(client):
created = client.post("/api/systems", json={
"key": "crm", "name": "CRM 客户管理", "layer_id": "dept", "dept": "云智销售部首",
"status": "dev", "tier": 2, "flow_x": 512, "flow_y": 640,
})
assert created.status_code == 201
node = _node(client, "crm")
assert (node["flow_x"], node["flow_y"]) == (512.0, 640.0)
def test_backup_round_trip_keeps_manual_positions(client):
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 333, "y": 444}]})
snapshot = client.get("/api/backup").json()
client.post("/api/graph/layout/reset")
assert _node(client, "oa")["flow_x"] is None
assert client.post("/api/backup", json={**snapshot, "mode": "replace"}).status_code == 200
assert _node(client, "oa")["flow_x"] == 333.0
def test_read_only_lock_blocks_layout_reset(client):
"""恢复自动排列 rewrites every card, so the switch has to cover it too."""
client.put("/api/graph/layout", json={"items": [{"key": "oa", "x": 210, "y": 260}]})
client.patch("/api/settings", json={"editing_enabled": False})
blocked = client.post("/api/graph/layout/reset")
assert blocked.status_code == 423
assert "只读" in blocked.json()["detail"]
assert _node(client, "oa")["flow_x"] == 210.0, "被拒绝的重置不得清空手动位置"
assert client.patch("/api/settings", json={"editing_enabled": True}).status_code == 200
assert client.post("/api/graph/layout/reset").json() == {"ok": True, "cleared": 1}
def test_graph_payload_carries_topology_counts(client):
"""The flow canvas reads its own header numbers from the graph, metrics-free."""
graph = client.get("/api/graph").json()
counts = graph["counts"]
systems = client.get("/api/systems").json()
flows = client.get("/api/flows").json()
assert counts["systems"] == len(systems) == len(graph["nodes"])
assert counts["flows_total"] == len(flows)
assert counts["flows_enabled"] == sum(1 for flow in flows if flow["enabled"])
assert counts["tiers"] == len({system["tier"] for system in systems})
assert counts["linked_systems"] == sum(1 for node in graph["nodes"] if node["degree"])
client.post("/api/systems", json={"key": "crm_new", "name": "CRM 客户管理"})
created = client.post("/api/flows", json={"source_key": "oa", "target_key": "crm_new",
"flow_type_id": "core", "label": "新链路"})
assert created.status_code == 201
after = client.get("/api/graph").json()["counts"]
assert after["flows_total"] == counts["flows_total"] + 1
assert after["flows_enabled"] == counts["flows_enabled"] + 1
@pytest.mark.parametrize("style", ["elbow", "curve", "straight"])
def test_flow_route_style_round_trips_through_settings(client, style):
"""线型是汇报现场的偏好,要跟着设置走,刷新和换设备都不能丢。"""
assert client.patch("/api/settings", json={"flow_route_style": style}).json()["flow_route_style"] == style
assert client.get("/api/settings").json()["flow_route_style"] == style
def test_flow_route_style_rejects_unknown_value(client):
"""一个认不出的线型会让画布退回默认走线,不如在入口就拒绝。"""
assert client.patch("/api/settings", json={"flow_route_style": "curve"}).status_code == 200
assert client.patch("/api/settings", json={"flow_route_style": "spaghetti"}).status_code == 422
assert client.get("/api/settings").json()["flow_route_style"] == "curve"
def test_flow_type_accepts_dash_dot_line_style(client):
"""点划线 carries 定时任务 / 人工 in the legend, so both ends have to accept it."""
created = client.post(
"/api/flow-types", json={"id": "nightly", "name": "夜间批处理", "line_style": "dash-dot"}
)
assert created.status_code == 201
assert created.json()["line_style"] == "dash-dot"
payload = created.json() | {"name": "夜间批处理", "line_style": "solid"}
assert client.put("/api/flow-types/nightly", json=payload).json()["line_style"] == "solid"
def test_shipped_flow_types_follow_the_colour_legend(client):
"""图例承诺"蓝=调用、紫=鉴权取数、绿=消息、灰=定时、红=人工",种子数据必须真的这么画。"""
types = {item["id"]: item for item in client.get("/api/flow-types").json()}
assert types["core"]["color"].startswith("#1") and types["core"]["line_style"] == "solid"
assert types["cap"]["line_style"] == "solid", "底座能力调用是同步调用"
assert types["entry"]["line_style"] == "dashed", "消息推送是异步"
assert types["mcp"]["line_style"] == "dash-dot", "MCP 取数是定时"
assert types["archive"]["line_style"] == "dash-dot", "归档沉淀是定时"
assert types["auth"]["color"] == "#7c3aed" and types["core"]["color"] != types["cap"]["color"]

View File

@ -0,0 +1,431 @@
"""Backend behaviour: seeding, metrics, CRUD guards, and backup round-trips."""
from __future__ import annotations
from datetime import date, datetime
import pytest
from fastapi import HTTPException
from conftest import FakeRequest
from app.routers import backup as backup_api
from app.routers import content, flows
from app.schemas import BackupIn, FlowIn, FlowPatch, FlowTypeIn, LayerIn, SettingsIn, SystemIn, SystemPatch
from app.seed import FLOWS, SYSTEMS, seed
from app.services import metrics
from app.services.graph import build_graph
# ------------------------------------------------------------------ seeding
def test_seed_is_idempotent(db):
assert seed(db) is False
assert db.execute("SELECT COUNT(*) AS c FROM systems").fetchone()["c"] == len(SYSTEMS)
def test_every_flow_endpoint_resolves(db):
rows = db.execute("SELECT * FROM data_flows").fetchall()
keys = {r["key"] for r in db.execute("SELECT key FROM systems").fetchall()}
assert len(rows) == len(FLOWS)
for row in rows:
assert row["source_key"] in keys and row["target_key"] in keys
assert row["source_key"] != row["target_key"]
def test_tiers_are_contiguous_and_layered(db):
tiers = {r["tier"] for r in db.execute("SELECT tier FROM systems").fetchall()}
assert min(tiers) == 0 and tiers == set(range(min(tiers), max(tiers) + 1))
# ------------------------------------------------------------------ metrics
def test_history_backfills_only_flows_without_rows(db):
metrics.ensure_history(db)
first = db.execute("SELECT COUNT(*) AS c FROM flow_metrics").fetchone()["c"]
metrics.ensure_history(db)
assert db.execute("SELECT COUNT(*) AS c FROM flow_metrics").fetchone()["c"] == first
assert first > 0
# A newly added link gets its own history rather than rendering dead.
created = flows.create_flow(
FlowIn(source_key="pms", target_key="kingdee", flow_type_id="core", label="新增测试链路"),
db,
FakeRequest(),
)
metrics.ensure_history(db)
own = db.execute("SELECT COUNT(*) AS c FROM flow_metrics WHERE flow_id = ?", (created["id"],)).fetchone()["c"]
assert own == 24 * 30 + datetime.now().hour + 1
def test_bucket_generation_is_deterministic(db):
metrics.ensure_history(db)
flow = db.execute("SELECT * FROM data_flows WHERE enabled = 1 LIMIT 1").fetchone()
today = date.today()
a = metrics.compute_bucket(dict(flow), today, 10, "seed-x")
b = metrics.compute_bucket(dict(flow), today, 10, "seed-x")
assert a == b
assert metrics.compute_bucket(dict(flow), today, 3, "seed-x")["batches"] <= a["batches"] + 1
def test_live_tick_advances_current_hour(db):
metrics.ensure_history(db)
today = date.today().isoformat()
before = db.execute(
"SELECT COALESCE(SUM(records),0) AS r FROM flow_metrics WHERE day = ?", (today,)
).fetchone()["r"]
result = metrics.live_tick(db)
after = db.execute(
"SELECT COALESCE(SUM(records),0) AS r FROM flow_metrics WHERE day = ?", (today,)
).fetchone()["r"]
assert result["touched"] > 0
assert after > before
def test_totals_and_health_shape(db):
metrics.ensure_history(db)
totals = metrics.totals(db, 7)
assert totals["records"] > 0 and totals["avg_latency_ms"] > 0
health = metrics.flow_health(db, days=7)
assert health and all(h["health"] in {"healthy", "watch", "risk"} for h in health.values())
# ------------------------------------------------------------------ graph
def test_graph_uses_declared_tiers_as_ranks(db):
metrics.ensure_history(db)
graph = build_graph(db, days=7)
by_key = {n["key"]: n for n in graph["nodes"]}
assert by_key["wecom"]["rank"] == 0, "统一入口层必须留在最左列"
assert all(n["rank"] == n["tier"] for n in graph["nodes"])
assert {n["health"] for n in graph["nodes"]} <= {"healthy", "watch", "risk", "idle"}
def test_graph_edges_carry_animation_inputs(db):
metrics.ensure_history(db)
graph = build_graph(db, days=7)
assert len(graph["edges"]) == len(FLOWS)
for edge in graph["edges"]:
assert edge["color"] and edge["throughput_rps"] >= 0 and edge["payload_mb_per_hour"] >= 0
assert edge["health"]["state"] in {"healthy", "watch", "risk", "idle"}
def test_disabled_flows_are_hidden_by_default(db):
metrics.ensure_history(db)
target = db.execute("SELECT id FROM data_flows LIMIT 1").fetchone()["id"]
flows.update_flow(target, FlowPatch(enabled=False), db, FakeRequest())
assert len(build_graph(db, days=7)["edges"]) == len(FLOWS) - 1
assert len(build_graph(db, days=7, include_disabled=True)["edges"]) == len(FLOWS)
# ------------------------------------------------------------------ CRUD guards
def test_system_crud_roundtrip(db):
created = content.create_system(SystemIn(key="demo", name="演示系统", layer_id="base", tier=3), db, FakeRequest())
assert created["layer_name"] == "底座(基础平台)"
updated = content.update_system("demo", SystemPatch(status="dev", tech="Python"), db, FakeRequest())
assert updated["status"] == "dev" and updated["tech"] == "Python"
assert content.get_system("demo", db)["name"] == "演示系统"
assert content.delete_system("demo", db, FakeRequest())["ok"] is True
with pytest.raises(HTTPException) as exc:
content.get_system("demo", db)
assert exc.value.status_code == 404
def test_system_validation_rejects_unknown_layer(db):
with pytest.raises(HTTPException) as exc:
content.create_system(SystemIn(key="x1", name="X", layer_id="nope"), db, FakeRequest())
assert exc.value.status_code == 400
def test_layer_delete_blocked_while_in_use(db):
with pytest.raises(HTTPException) as exc:
content.delete_layer("base", db, FakeRequest())
assert exc.value.status_code == 409
def test_layer_delete_allowed_once_empty(db):
content.create_layer(LayerIn(id="tmp", name="临时层"), db, FakeRequest())
assert content.delete_layer("tmp", db, FakeRequest())["ok"] is True
def test_duplicate_layer_id_rejected(db):
content.create_layer(LayerIn(id="tmp2", name="临时层2"), db, FakeRequest())
with pytest.raises(HTTPException) as exc:
content.create_layer(LayerIn(id="tmp2", name="重名"), db, FakeRequest())
assert exc.value.status_code == 409
def test_flow_rejects_self_loop_and_missing_endpoints(db):
base = dict(flow_type_id="core", label="测试")
with pytest.raises(HTTPException) as exc:
flows.create_flow(FlowIn(source_key="oa", target_key="oa", **base), db, FakeRequest())
assert exc.value.status_code == 400
with pytest.raises(HTTPException):
flows.create_flow(FlowIn(source_key="oa", target_key="ghost", **base), db, FakeRequest())
def test_flow_duplicate_rejected(db):
payload = FlowIn(source_key="pms", target_key="kingdee", flow_type_id="core", label="唯一测试链路")
flows.create_flow(payload, db, FakeRequest())
with pytest.raises(HTTPException) as exc:
flows.create_flow(payload, db, FakeRequest())
assert exc.value.status_code == 409
def test_flow_patch_normalizes_peak_hours_and_enabled(db):
created = flows.create_flow(
FlowIn(source_key="pms", target_key="nas", flow_type_id="archive", label="测试归档",
peak_hours=[30, 9, 9, 8]),
db, FakeRequest(),
)
assert created["peak_hours"] == [8, 9]
patched = flows.update_flow(created["id"], FlowPatch(enabled=False, peak_hours=[25, 7]), db, FakeRequest())
assert patched["enabled"] is False and patched["peak_hours"] == [7]
def test_flow_type_delete_blocked_while_in_use(db):
with pytest.raises(HTTPException) as exc:
content.delete_flow_type("core", db, FakeRequest())
assert exc.value.status_code == 409
def test_flow_type_crud(db):
content.create_flow_type(FlowTypeIn(id="batch", name="批处理", line_style="dotted"), db, FakeRequest())
row = content.update_flow_type("batch", FlowTypeIn(id="batch", name="批处理2"), db, FakeRequest())
assert row["name"] == "批处理2"
assert content.delete_flow_type("batch", db, FakeRequest())["ok"] is True
def test_settings_patch_partial(db):
updated = content.patch_settings(SettingsIn(site_title="新标题"), db, FakeRequest())
assert updated["site_title"] == "新标题"
assert "animation_speed" in updated, "未提交的配置项必须保留"
def test_audit_records_editor_identity(db):
content.create_system(SystemIn(key="audited", name="审计系统"), db, FakeRequest())
logs = db.execute("SELECT * FROM audit_logs ORDER BY id DESC LIMIT 1").fetchone()
assert logs["actor"] == "测试员" and logs["action"] == "create"
# ------------------------------------------------------------------ backup
def test_backup_roundtrip_preserves_counts(db):
metrics.ensure_history(db)
payload = backup_api.export_backup(db)
assert payload["systems"] and payload["data_flows"]
imported = backup_api.import_backup(
BackupIn(**{**payload, "mode": "merge"}), db, FakeRequest()
)
assert imported["errors"] == []
assert imported["imported"]["systems"] == len(SYSTEMS)
# Merging the same ids must not duplicate rows.
assert db.execute("SELECT COUNT(*) AS c FROM data_flows").fetchone()["c"] == len(FLOWS)
# Metrics stay attached because the ids were preserved.
assert db.execute("SELECT COUNT(*) AS c FROM flow_metrics").fetchone()["c"] > 0
def test_backup_replace_wipes_and_restores(db):
payload = backup_api.export_backup(db)
payload["systems"] = [s for s in payload["systems"] if s["key"] in {"oa", "pms"}]
result = backup_api.import_backup(BackupIn(**{**payload, "mode": "replace"}), db, FakeRequest())
assert db.execute("SELECT COUNT(*) AS c FROM systems").fetchone()["c"] == 2
# Only the link whose endpoints both survived is restored; the rest are rejected
# rather than silently imported against missing systems.
surviving = db.execute("SELECT source_key, target_key FROM data_flows").fetchall()
assert [(r["source_key"], r["target_key"]) for r in surviving] == [("pms", "oa")]
assert any("端点系统不存在" in e for e in result["errors"])
# A replace wipes history too, so metrics are rebuilt from the restored cadence.
metrics.ensure_history(db)
assert db.execute("SELECT COUNT(*) AS c FROM flow_metrics").fetchone()["c"] == 24 * 30 + datetime.now().hour + 1
def test_backup_rejects_empty_payload(db):
with pytest.raises(HTTPException) as exc:
backup_api.import_backup(BackupIn(), db, FakeRequest())
assert exc.value.status_code == 400
# ------------------------------------------------------------------ threading
def test_request_connection_works_across_threadpool_threads(tmp_path, monkeypatch):
"""FastAPI resolves a sync dependency on one threadpool worker and runs the
endpoint body on another. The request-scoped connection is created in the
dependency, so it must tolerate being used from a different thread; sqlite's
default same-thread guard otherwise raises ProgrammingError on every request.
"""
import threading
monkeypatch.setenv("DB_PATH", str(tmp_path / "thread.db"))
from app import config
monkeypatch.setattr(config, "db_path", lambda: tmp_path / "thread.db")
from app.db import connect, init_db, get_db
from app.seed import seed
init_db()
bootstrap = connect()
seed(bootstrap)
bootstrap.close()
# The dependency yields the connection. Keep a reference to the generator itself,
# otherwise it is finalized immediately and closes the connection underneath us.
dependency = get_db()
connection = next(dependency)
errors: list[BaseException] = []
done = threading.Event()
# ...and the endpoint body consumes it on a foreign thread.
def worker():
try:
assert connection.execute("SELECT COUNT(*) AS c FROM systems").fetchone()["c"] == len(SYSTEMS)
except BaseException as exc: # noqa: BLE001 - surfaced below as a test failure
errors.append(exc)
finally:
done.set()
thread = threading.Thread(target=worker)
thread.start()
thread.join(timeout=10)
assert done.is_set(), "worker thread did not finish"
assert not errors, f"connection rejected on foreign thread: {errors!r}"
next(dependency, None)
# ------------------------------------------------------------------ actor header
def test_actor_header_is_percent_decoded():
"""HTTP headers cannot carry Chinese text, so the client percent-encodes the
editor name; the audit trail must still record the readable name."""
from app.deps import actor_from
class Headers:
def __init__(self, value):
self._value = value
def get(self, key, default=""):
return self._value if key.lower() in ("x-editor", "x-actor") else default
assert actor_from(type("R", (), {"headers": Headers("%E5%BA%B7%E6%96%87%E6%99%B6")})()) == "康文晶"
assert actor_from(type("R", (), {"headers": Headers("alice")})()) == "alice"
assert actor_from(type("R", (), {"headers": Headers("")})()) == "匿名"
# Malformed escapes decode leniently rather than raising.
assert actor_from(type("R", (), {"headers": Headers("%%%E4%B8%AD")})()) == "%%中"
# Invalid UTF-8 byte escapes fall back to the raw header instead of 500ing.
assert actor_from(type("R", (), {"headers": Headers("%FF%FE")})()) == "%FF%FE"
def test_impl_time_and_entry_flag_survive_backup_roundtrip(db):
metrics.ensure_history(db)
content.update_system(
"oa",
SystemPatch(impl_time="2024-06 上线", entry_enabled=False, url="https://oa.example.com"),
db,
FakeRequest(),
)
payload = backup_api.export_backup(db)
db.execute("UPDATE systems SET impl_time = '', entry_enabled = 1, url = '' WHERE key = 'oa'")
backup_api.import_backup(BackupIn(**{**payload, "mode": "merge"}), db, FakeRequest())
row = db.execute("SELECT impl_time, entry_enabled, url FROM systems WHERE key = 'oa'").fetchone()
assert (row["impl_time"], row["entry_enabled"], row["url"]) == ("2024-06 上线", 0, "https://oa.example.com")
def test_graph_nodes_expose_impl_time_and_entry_flag(db):
content.update_system("oa", SystemPatch(impl_time="2023 Q4 立项", entry_enabled=False), db, FakeRequest())
node = next(n for n in build_graph(db)["nodes"] if n["key"] == "oa")
assert node["impl_time"] == "2023 Q4 立项"
assert node["entry_enabled"] is False
def test_read_only_lock_blocks_service_level_writes(db):
"""The same switch guards the service functions, not only the HTTP layer."""
from app.deps import ensure_editable
from app.schemas import SettingsIn
content.patch_settings(SettingsIn(editing_enabled=False), db, FakeRequest())
with pytest.raises(HTTPException) as exc:
ensure_editable(db, "新增系统")
assert exc.value.status_code == 423 and "只读" in exc.value.detail
content.patch_settings(SettingsIn(editing_enabled=True), db, FakeRequest())
ensure_editable(db) # must not raise
def test_manual_layout_columns_are_added_to_older_databases(tmp_path, monkeypatch):
"""flow_x/flow_y arrived after the first release; old files must gain them in place."""
import sqlite3
from app import config
from app.db import init_db
path = tmp_path / "legacy.db"
legacy = sqlite3.connect(path)
legacy.executescript(
"""
CREATE TABLE systems (
id INTEGER PRIMARY KEY AUTOINCREMENT, key TEXT NOT NULL UNIQUE, name TEXT NOT NULL,
layer_id TEXT, dept TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'unknown',
tech TEXT NOT NULL DEFAULT '', url TEXT NOT NULL DEFAULT '', domain TEXT NOT NULL DEFAULT '',
owner TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '',
tier INTEGER NOT NULL DEFAULT 2, sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT ''
);
INSERT INTO systems (key, name) VALUES ('oa', 'OA');
"""
)
legacy.commit()
legacy.close()
monkeypatch.setenv("DB_PATH", str(path))
monkeypatch.setattr(config, "db_path", lambda: path)
init_db()
init_db() # migrating twice must not fail
conn = sqlite3.connect(path)
columns = {row[1] for row in conn.execute("PRAGMA table_info(systems)")}
assert {"flow_x", "flow_y", "impl_time", "entry_enabled"} <= columns
assert conn.execute("SELECT COUNT(*) FROM systems").fetchone()[0] == 1
conn.close()
def test_tier_label_covers_every_configured_column():
from app.services.graph import TIER_LABELS, tier_label
assert len(TIER_LABELS) == 4
assert tier_label(0) == "统一入口层"
assert tier_label(7).startswith("第 8 层")
def test_migrate_survives_losing_an_add_column_race(tmp_path, monkeypatch):
"""Two processes boot at once; the one that loses the ALTER must still start.
That is exactly what happened when both servers came up against the same file: the
losing connection still saw the column as missing, then hit `duplicate column name`.
"""
import sqlite3
path = tmp_path / "race.db"
monkeypatch.setenv("DB_PATH", str(path))
from app import config
monkeypatch.setattr(config, "db_path", lambda: path)
from app.db import init_db, migrate
init_db()
class Blind:
"""Connection view frozen before the other process added the columns."""
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
def execute(self, sql: str):
if sql.startswith("PRAGMA table_info"):
return iter(())
return self.conn.execute(sql)
conn = sqlite3.connect(path)
migrate(Blind(conn)) # must not raise
conn.close()

18
dev.sh 100755
View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# 开发模式:后端 8787(热重载)+ 前端 5273(HMR,已代理 /api 到后端)。
set -euo pipefail
cd "$(dirname "$0")"
export DB_PATH="${DB_PATH:-$PWD/backend/panorama.db}"
export RELOAD=1
cleanup() { kill 0 2>/dev/null || true; }
trap cleanup EXIT INT TERM
echo "==> 后端 http://localhost:8787 (API 文档 /docs)"
(cd backend && python3 -m uvicorn app.main:app --host 0.0.0.0 --port 8787 --reload) &
[ -d frontend/node_modules ] || (cd frontend && npm install --no-audit --no-fund)
echo "==> 前端 http://localhost:5273"
(cd frontend && npm run dev)

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>公司 IT 系统全景与数据流向平台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1
frontend/node_modules/.bin/autoprefixer generated vendored 120000
View File

@ -0,0 +1 @@
../autoprefixer/bin/autoprefixer

View File

@ -0,0 +1 @@
../baseline-browser-mapping/dist/cli.cjs

1
frontend/node_modules/.bin/browserslist generated vendored 120000
View File

@ -0,0 +1 @@
../browserslist/cli.js

1
frontend/node_modules/.bin/cssesc generated vendored 120000
View File

@ -0,0 +1 @@
../cssesc/bin/cssesc

1
frontend/node_modules/.bin/esbuild generated vendored 120000
View File

@ -0,0 +1 @@
../esbuild/bin/esbuild

1
frontend/node_modules/.bin/he generated vendored 120000
View File

@ -0,0 +1 @@
../he/bin/he

1
frontend/node_modules/.bin/jiti generated vendored 120000
View File

@ -0,0 +1 @@
../jiti/bin/jiti.js

1
frontend/node_modules/.bin/nanoid generated vendored 120000
View File

@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
frontend/node_modules/.bin/parser generated vendored 120000
View File

@ -0,0 +1 @@
../@babel/parser/bin/babel-parser.js

1
frontend/node_modules/.bin/resolve generated vendored 120000
View File

@ -0,0 +1 @@
../resolve/bin/resolve

1
frontend/node_modules/.bin/rollup generated vendored 120000
View File

@ -0,0 +1 @@
../rollup/dist/bin/rollup

1
frontend/node_modules/.bin/sucrase generated vendored 120000
View File

@ -0,0 +1 @@
../sucrase/bin/sucrase

1
frontend/node_modules/.bin/sucrase-node generated vendored 120000
View File

@ -0,0 +1 @@
../sucrase/bin/sucrase-node

1
frontend/node_modules/.bin/tailwind generated vendored 120000
View File

@ -0,0 +1 @@
../tailwindcss/lib/cli.js

1
frontend/node_modules/.bin/tailwindcss generated vendored 120000
View File

@ -0,0 +1 @@
../tailwindcss/lib/cli.js

1
frontend/node_modules/.bin/tsc generated vendored 120000
View File

@ -0,0 +1 @@
../typescript/bin/tsc

1
frontend/node_modules/.bin/tsserver generated vendored 120000
View File

@ -0,0 +1 @@
../typescript/bin/tsserver

View File

@ -0,0 +1 @@
../update-browserslist-db/cli.js

1
frontend/node_modules/.bin/vite generated vendored 120000
View File

@ -0,0 +1 @@
../vite/bin/vite.js

1
frontend/node_modules/.bin/vue-demi-fix generated vendored 120000
View File

@ -0,0 +1 @@
../vue-demi/bin/vue-demi-fix.js

1
frontend/node_modules/.bin/vue-demi-switch generated vendored 120000
View File

@ -0,0 +1 @@
../vue-demi/bin/vue-demi-switch.js

1
frontend/node_modules/.bin/vue-tsc generated vendored 120000
View File

@ -0,0 +1 @@
../vue-tsc/bin/vue-tsc.js

2950
frontend/node_modules/.package-lock.json generated vendored 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
{
"hash": "6e5cdcad",
"configHash": "5676f1d7",
"lockfileHash": "b8fc5ddb",
"browserHash": "ba239a32",
"optimized": {
"axios": {
"src": "../../axios/index.js",
"file": "axios.js",
"fileHash": "0eabf0a3",
"needsInterop": false
},
"pinia": {
"src": "../../pinia/dist/pinia.mjs",
"file": "pinia.js",
"fileHash": "86193d4d",
"needsInterop": false
},
"vue": {
"src": "../../vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "40f4b8ab",
"needsInterop": false
},
"vue-router": {
"src": "../../vue-router/dist/vue-router.mjs",
"file": "vue-router.js",
"fileHash": "4a9239aa",
"needsInterop": false
}
},
"chunks": {
"chunk-YFT6OQ5R": {
"file": "chunk-YFT6OQ5R.js"
},
"chunk-GKNS7JV4": {
"file": "chunk-GKNS7JV4.js"
},
"chunk-PZ5AY32C": {
"file": "chunk-PZ5AY32C.js"
}
}
}

3804
frontend/node_modules/.vite/deps/axios.js generated vendored 100644

File diff suppressed because it is too large Load Diff

7
frontend/node_modules/.vite/deps/axios.js.map generated vendored 100644

File diff suppressed because one or more lines are too long

13339
frontend/node_modules/.vite/deps/chunk-GKNS7JV4.js generated vendored 100644

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,10 @@
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
export {
__export
};
//# sourceMappingURL=chunk-PZ5AY32C.js.map

View File

@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}

View File

@ -0,0 +1,162 @@
// node_modules/@vue/devtools-api/lib/esm/env.js
function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
function getTarget() {
return typeof navigator !== "undefined" && typeof window !== "undefined" ? window : typeof globalThis !== "undefined" ? globalThis : {};
}
var isProxyAvailable = typeof Proxy === "function";
// node_modules/@vue/devtools-api/lib/esm/const.js
var HOOK_SETUP = "devtools-plugin:setup";
var HOOK_PLUGIN_SETTINGS_SET = "plugin:settings:set";
// node_modules/@vue/devtools-api/lib/esm/time.js
var supported;
var perf;
function isPerformanceSupported() {
var _a;
if (supported !== void 0) {
return supported;
}
if (typeof window !== "undefined" && window.performance) {
supported = true;
perf = window.performance;
} else if (typeof globalThis !== "undefined" && ((_a = globalThis.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
supported = true;
perf = globalThis.perf_hooks.performance;
} else {
supported = false;
}
return supported;
}
function now() {
return isPerformanceSupported() ? perf.now() : Date.now();
}
// node_modules/@vue/devtools-api/lib/esm/proxy.js
var ApiProxy = class {
constructor(plugin, hook) {
this.target = null;
this.targetQueue = [];
this.onQueue = [];
this.plugin = plugin;
this.hook = hook;
const defaultSettings = {};
if (plugin.settings) {
for (const id in plugin.settings) {
const item = plugin.settings[id];
defaultSettings[id] = item.defaultValue;
}
}
const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
let currentSettings = Object.assign({}, defaultSettings);
try {
const raw = localStorage.getItem(localSettingsSaveId);
const data = JSON.parse(raw);
Object.assign(currentSettings, data);
} catch (e) {
}
this.fallbacks = {
getSettings() {
return currentSettings;
},
setSettings(value) {
try {
localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
} catch (e) {
}
currentSettings = value;
},
now() {
return now();
}
};
if (hook) {
hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
if (pluginId === this.plugin.id) {
this.fallbacks.setSettings(value);
}
});
}
this.proxiedOn = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target.on[prop];
} else {
return (...args) => {
this.onQueue.push({
method: prop,
args
});
};
}
}
});
this.proxiedTarget = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target[prop];
} else if (prop === "on") {
return this.proxiedOn;
} else if (Object.keys(this.fallbacks).includes(prop)) {
return (...args) => {
this.targetQueue.push({
method: prop,
args,
resolve: () => {
}
});
return this.fallbacks[prop](...args);
};
} else {
return (...args) => {
return new Promise((resolve) => {
this.targetQueue.push({
method: prop,
args,
resolve
});
});
};
}
}
});
}
async setRealTarget(target) {
this.target = target;
for (const item of this.onQueue) {
this.target.on[item.method](...item.args);
}
for (const item of this.targetQueue) {
item.resolve(await this.target[item.method](...item.args));
}
}
};
// node_modules/@vue/devtools-api/lib/esm/index.js
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const descriptor = pluginDescriptor;
const target = getTarget();
const hook = getDevtoolsGlobalHook();
const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
} else {
const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor: descriptor,
setupFn,
proxy
});
if (proxy) {
setupFn(proxy.proxiedTarget);
}
}
}
export {
setupDevtoolsPlugin
};
//# sourceMappingURL=chunk-YFT6OQ5R.js.map

File diff suppressed because one or more lines are too long

3
frontend/node_modules/.vite/deps/package.json generated vendored 100644
View File

@ -0,0 +1,3 @@
{
"type": "module"
}

1561
frontend/node_modules/.vite/deps/pinia.js generated vendored 100644

File diff suppressed because it is too large Load Diff

7
frontend/node_modules/.vite/deps/pinia.js.map generated vendored 100644

File diff suppressed because one or more lines are too long

2247
frontend/node_modules/.vite/deps/vue-router.js generated vendored 100644

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

348
frontend/node_modules/.vite/deps/vue.js generated vendored 100644
View File

@ -0,0 +1,348 @@
import {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBaseVNode,
createBlock,
createCommentVNode,
createElementBlock,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
nodeOps,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
patchProp,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
} from "./chunk-GKNS7JV4.js";
import "./chunk-PZ5AY32C.js";
export {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBlock,
createCommentVNode,
createElementBlock,
createBaseVNode as createElementVNode,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
nodeOps,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
patchProp,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
};
//# sourceMappingURL=vue.js.map

7
frontend/node_modules/.vite/deps/vue.js.map generated vendored 100644
View File

@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}

View File

@ -0,0 +1,118 @@
// @ts-nocheck
export {};
; declare global {
const __VLS_intrinsicElements: __VLS_IntrinsicElements;
const __VLS_directiveBindingRestFields: { instance: null, oldValue: null, modifiers: any, dir: any };
const __VLS_unref: typeof import('vue').unref;
const __VLS_placeholder: any;
type __VLS_NativeElements = __VLS_SpreadMerge<SVGElementTagNameMap, HTMLElementTagNameMap>;
type __VLS_IntrinsicElements = import('vue/jsx-runtime').JSX.IntrinsicElements;
type __VLS_Element = import('vue/jsx-runtime').JSX.Element;
type __VLS_GlobalComponents = import('vue').GlobalComponents;
type __VLS_GlobalDirectives = import('vue').GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_SpreadMerge<A, B> = Omit<A, keyof B> & B;
type __VLS_WithComponent<N0 extends string, LocalComponents, Self, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } :
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } :
Self extends object ? { [K in N0]: Self } :
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } :
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
{ [K in N0]: unknown };
type __VLS_FunctionalComponentProps<T, K> =
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P :
{};
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
? false
: true
: false
: false;
type __VLS_NormalizeComponentEvent<Props, Events, onEvent extends keyof Props, Event extends keyof Events, CamelizedEvent extends keyof Events> = (
__VLS_IsFunction<Props, onEvent> extends true
? Props
: __VLS_IsFunction<Events, Event> extends true
? { [K in onEvent]?: Events[Event] }
: __VLS_IsFunction<Events, CamelizedEvent> extends true
? { [K in onEvent]?: Events[CamelizedEvent] }
: Props
) & Record<string, unknown>;
// fix https://github.com/vuejs/language-tools/issues/926
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never;
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R
? U extends T
? never
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R)
: never;
type __VLS_OverloadUnion<T> = Exclude<
__VLS_OverloadUnionInner<(() => never) & T>,
T extends () => never ? never : () => never
>;
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F
? F extends (event: infer E, ...args: infer A) => any
? { [K in E & string]: (...args: A) => void; }
: never
: never;
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never
}
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>>;
type __VLS_UseTemplateRef<T> = Readonly<import('vue').ShallowRef<T | null>>;
function __VLS_getVForSourceType<T extends number | string | any[] | Iterable<any>>(source: T): [
item: T extends number ? number
: T extends string ? string
: T extends any[] ? T[number]
: T extends Iterable<infer T1> ? T1
: any,
index: number,
][];
function __VLS_getVForSourceType<T>(source: T): [
item: T[keyof T],
key: keyof T,
index: number,
][];
// @ts-ignore
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
// @ts-ignore
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
function __VLS_asFunctionalDirective<T>(dir: T): T extends import('vue').ObjectDirective
? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
: T extends (...args: any) => any
? T
: (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
T extends new (...args: any) => any
? (props: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>, ctx?: any) => __VLS_Element & {
__ctx?: {
attrs?: any;
slots?: K extends { $slots: infer Slots } ? Slots : any;
emit?: K extends { $emit: infer Emit } ? Emit : any;
expose?(exposed: K): void;
props?: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>;
}
}
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {} & Record<string, unknown>, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {} & Record<string, unknown> } };
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : [];
function __VLS_asFunctionalElement<T>(tag: T, endTag?: T): (attrs: T & Record<string, unknown>) => void;
function __VLS_asFunctionalSlot<S>(slot: S): S extends () => infer R ? (props: {}) => R : NonNullable<S>;
function __VLS_tryAsConstant<const T>(t: T): T;
}

View File

@ -0,0 +1,144 @@
declare namespace QuickLRU {
interface Options<KeyType, ValueType> {
/**
The maximum number of milliseconds an item should remain in the cache.
@default Infinity
By default, `maxAge` will be `Infinity`, which means that items will never expire.
Lazy expiration upon the next write or read call.
Individual expiration of an item can be specified by the `set(key, value, maxAge)` method.
*/
readonly maxAge?: number;
/**
The target maximum number of items before evicting the least recently used items.
The dual-cache algorithm may physically retain up to twice `maxSize` entries for performance reasons, even though the reported cache size does not exceed `maxSize`.
*/
readonly maxSize: number;
/**
Called right before an item is evicted from the cache due to capacity pressure or TTL expiration.
Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`).
This callback is not called for manual removals via `delete()` or `clear()`.
*/
onEviction?: (key: KeyType, value: ValueType) => void;
}
}
declare class QuickLRU<KeyType, ValueType>
implements Iterable<[KeyType, ValueType]> {
/**
The stored item count.
*/
readonly size: number;
/**
Simple ["Least Recently Used" (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29).
The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.
@example
```
import QuickLRU = require('@alloc/quick-lru');
const lru = new QuickLRU({maxSize: 1000});
lru.set('🦄', '🌈');
lru.has('🦄');
//=> true
lru.get('🦄');
//=> '🌈'
```
*/
constructor(options: QuickLRU.Options<KeyType, ValueType>);
[Symbol.iterator](): IterableIterator<[KeyType, ValueType]>;
/**
Set an item. Returns the instance.
Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified in the constructor, otherwise the item will never expire.
@returns The list instance.
*/
set(key: KeyType, value: ValueType, options?: {maxAge?: number}): this;
/**
Get an item.
@returns The stored item or `undefined`.
*/
get(key: KeyType): ValueType | undefined;
/**
Check if an item exists.
*/
has(key: KeyType): boolean;
/**
Get an item without marking it as recently used.
@returns The stored item or `undefined`.
*/
peek(key: KeyType): ValueType | undefined;
/**
Get the remaining time to live (in milliseconds) for the given item, or `undefined` when the item is not in the cache.
- Does not mark the item as recently used.
- Does not trigger lazy expiration or remove the entry when it is expired.
- Returns `Infinity` if the item has no expiration.
- May return a negative number if the item is already expired but not yet lazily removed.
@returns Remaining time to live in milliseconds when set, `Infinity` when there is no expiration, or `undefined` when the item does not exist.
*/
expiresIn(key: KeyType): number | undefined;
/**
Delete an item.
@returns `true` if the item is removed or `false` if the item doesn't exist.
*/
delete(key: KeyType): boolean;
/**
Delete all items.
*/
clear(): void;
/**
Update the `maxSize` in-place, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee.
Useful for on-the-fly tuning of cache sizes in live systems.
*/
resize(maxSize: number): void;
/**
Iterable for all the keys.
*/
keys(): IterableIterator<KeyType>;
/**
Iterable for all the values.
*/
values(): IterableIterator<ValueType>;
/**
Iterable for all entries, starting with the oldest (ascending in recency).
*/
entriesAscending(): IterableIterator<[KeyType, ValueType]>;
/**
Iterable for all entries, starting with the newest (descending in recency).
*/
entriesDescending(): IterableIterator<[KeyType, ValueType]>;
}
export = QuickLRU;

276
frontend/node_modules/@alloc/quick-lru/index.js generated vendored 100644
View File

@ -0,0 +1,276 @@
'use strict';
class QuickLRU {
constructor(options = {}) {
if (!(options.maxSize && options.maxSize > 0)) {
throw new TypeError('`maxSize` must be a number greater than 0');
}
if (typeof options.maxAge === 'number' && options.maxAge === 0) {
throw new TypeError('`maxAge` must be a number greater than 0');
}
this.maxSize = options.maxSize;
this.maxAge = options.maxAge || Infinity;
this.onEviction = options.onEviction;
this.cache = new Map();
this.oldCache = new Map();
this._size = 0;
}
_emitEvictions(cache) {
if (typeof this.onEviction !== 'function') {
return;
}
for (const [key, item] of cache) {
this.onEviction(key, item.value);
}
}
_deleteIfExpired(key, item) {
if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {
if (typeof this.onEviction === 'function') {
this.onEviction(key, item.value);
}
return this.delete(key);
}
return false;
}
_getOrDeleteIfExpired(key, item) {
const deleted = this._deleteIfExpired(key, item);
if (deleted === false) {
return item.value;
}
}
_getItemValue(key, item) {
return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;
}
_peek(key, cache) {
const item = cache.get(key);
return this._getItemValue(key, item);
}
_set(key, value) {
this.cache.set(key, value);
this._size++;
if (this._size >= this.maxSize) {
this._size = 0;
this._emitEvictions(this.oldCache);
this.oldCache = this.cache;
this.cache = new Map();
}
}
_moveToRecent(key, item) {
this.oldCache.delete(key);
this._set(key, item);
}
* _entriesAscending() {
for (const item of this.oldCache) {
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield item;
}
}
}
for (const item of this.cache) {
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield item;
}
}
}
get(key) {
if (this.cache.has(key)) {
const item = this.cache.get(key);
return this._getItemValue(key, item);
}
if (this.oldCache.has(key)) {
const item = this.oldCache.get(key);
if (this._deleteIfExpired(key, item) === false) {
this._moveToRecent(key, item);
return item.value;
}
}
}
set(key, value, {maxAge = this.maxAge} = {}) {
const expiry =
typeof maxAge === 'number' && maxAge !== Infinity ?
Date.now() + maxAge :
undefined;
if (this.cache.has(key)) {
this.cache.set(key, {
value,
expiry
});
} else {
this._set(key, {value, expiry});
}
return this;
}
has(key) {
if (this.cache.has(key)) {
return !this._deleteIfExpired(key, this.cache.get(key));
}
if (this.oldCache.has(key)) {
return !this._deleteIfExpired(key, this.oldCache.get(key));
}
return false;
}
peek(key) {
if (this.cache.has(key)) {
return this._peek(key, this.cache);
}
if (this.oldCache.has(key)) {
return this._peek(key, this.oldCache);
}
}
expiresIn(key) {
const item = this.cache.get(key) || this.oldCache.get(key);
if (item) {
return item.expiry ? item.expiry - Date.now() : Infinity;
}
}
delete(key) {
const deleted = this.cache.delete(key);
if (deleted) {
this._size--;
}
return this.oldCache.delete(key) || deleted;
}
clear() {
this.cache.clear();
this.oldCache.clear();
this._size = 0;
}
resize(newSize) {
if (!(newSize && newSize > 0)) {
throw new TypeError('`maxSize` must be a number greater than 0');
}
const items = [...this._entriesAscending()];
const removeCount = items.length - newSize;
if (removeCount < 0) {
this.cache = new Map(items);
this.oldCache = new Map();
this._size = items.length;
} else {
if (removeCount > 0) {
this._emitEvictions(items.slice(0, removeCount));
}
this.oldCache = new Map(items.slice(removeCount));
this.cache = new Map();
this._size = 0;
}
this.maxSize = newSize;
}
* keys() {
for (const [key] of this) {
yield key;
}
}
* values() {
for (const [, value] of this) {
yield value;
}
}
* [Symbol.iterator]() {
for (const item of this.cache) {
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
for (const item of this.oldCache) {
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
}
}
* entriesDescending() {
let items = [...this.cache];
for (let i = items.length - 1; i >= 0; --i) {
const item = items[i];
const [key, value] = item;
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
items = [...this.oldCache];
for (let i = items.length - 1; i >= 0; --i) {
const item = items[i];
const [key, value] = item;
if (!this.cache.has(key)) {
const deleted = this._deleteIfExpired(key, value);
if (deleted === false) {
yield [key, value.value];
}
}
}
}
* entriesAscending() {
for (const [key, value] of this._entriesAscending()) {
yield [key, value.value];
}
}
get size() {
if (!this._size) {
return this.oldCache.size;
}
let oldCacheSize = 0;
for (const key of this.oldCache.keys()) {
if (!this.cache.has(key)) {
oldCacheSize++;
}
}
return Math.min(this._size + oldCacheSize, this.maxSize);
}
}
module.exports = QuickLRU;

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,43 @@
{
"name": "@alloc/quick-lru",
"version": "5.3.0",
"description": "Simple “Least Recently Used” (LRU) cache",
"license": "MIT",
"repository": "https://github.com/aleclarson/quick-lru",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && nyc ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"lru",
"quick",
"cache",
"caching",
"least",
"recently",
"used",
"fast",
"map",
"hash",
"buffer"
],
"devDependencies": {
"ava": "^2.0.0",
"coveralls": "^3.0.3",
"nyc": "^15.0.0",
"tsd": "^0.11.0",
"xo": "^0.26.0"
}
}

160
frontend/node_modules/@alloc/quick-lru/readme.md generated vendored 100644
View File

@ -0,0 +1,160 @@
# @alloc/quick-lru [![Build Status](https://travis-ci.org/aleclarson/quick-lru.svg?branch=master)](https://travis-ci.org/aleclarson/quick-lru) [![Coverage Status](https://coveralls.io/repos/github/aleclarson/quick-lru/badge.svg?branch=master)](https://coveralls.io/github/aleclarson/quick-lru?branch=master)
> Simple [“Least Recently Used” (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29)
This is a CommonJS-only fork of [`quick-lru`](https://github.com/sindresorhus/quick-lru).
Useful when you need to cache something and limit memory usage.
See the [algorithm section](#algorithm) for implementation details.
## Install
```
$ npm install @alloc/quick-lru
```
## Usage
```js
const QuickLRU = require('@alloc/quick-lru');
const lru = new QuickLRU({maxSize: 1000});
lru.set('🦄', '🌈');
lru.has('🦄');
//=> true
lru.get('🦄');
//=> '🌈'
```
## API
### new QuickLRU(options?)
Returns a new instance.
### options
Type: `object`
#### maxSize
*Required*\
Type: `number`
The target maximum number of items before evicting the least recently used items.
> **Note:** The dual-cache algorithm may physically retain up to twice `maxSize` entries for performance reasons, even though the reported cache size does not exceed `maxSize`.
#### maxAge
Type: `number`\
Default: `Infinity`
The maximum number of milliseconds an item should remain in cache.
By default maxAge will be Infinity, which means that items will never expire.
Lazy expiration happens upon the next `write` or `read` call.
Individual expiration of an item can be specified by the `set(key, value, options)` method.
#### onEviction
*Optional*\
Type: `(key, value) => void`
Called right before an item is evicted from the cache due to capacity pressure or TTL expiration.
Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`).
This callback is not called for manual removals via `delete()` or `clear()`.
### Instance
The instance is [`iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) so you can use it directly in a [`for…of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.
Both `key` and `value` can be of any type.
#### .set(key, value, options?)
Set an item. Returns the instance.
Individual expiration of an item can be specified with the `maxAge` option. If not specified, the global `maxAge` value will be used in case it is specified on the constructor, otherwise the item will never expire.
#### .get(key)
Get an item.
#### .has(key)
Check if an item exists.
#### .peek(key)
Get an item without marking it as recently used.
#### .expiresIn(key)
Get the remaining time to live (in milliseconds) for the given item, or `undefined` if the item is not in the cache.
- Does not mark the item as recently used.
- Does not trigger lazy expiration or remove the entry when it is expired.
- Returns `Infinity` if the item has no expiration.
- May return a negative number if the item has already expired but has not yet been lazily removed.
#### .delete(key)
Delete an item.
Returns `true` if the item is removed or `false` if the item doesn't exist.
#### .clear()
Delete all items.
#### .resize(maxSize)
Update the `maxSize`, discarding items as necessary. Insertion order is mostly preserved, though this is not a strong guarantee.
Useful for on-the-fly tuning of cache sizes in live systems.
#### .keys()
Iterable for all the keys.
#### .values()
Iterable for all the values.
#### .entriesAscending()
Iterable for all entries, starting with the oldest (ascending in recency).
#### .entriesDescending()
Iterable for all entries, starting with the newest (descending in recency).
#### .size
The stored item count.
## Algorithm
This library implements a variant of the [`hashlru` algorithm](https://github.com/dominictarr/hashlru#algorithm) using two [`Map`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map) objects. One map holds recently added or accessed entries, while the other holds older entries. When the recent map reaches `maxSize`, it replaces the older map and a new recent map is created.
This avoids the frequent delete operations required by a traditional linked-list LRU and supports keys of any type and `undefined` values. The tradeoff is that the two maps may physically retain up to twice the target `maxSize` between rotations. Use a strict-size cache when that temporary memory overhead is unacceptable.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-quick-lru?utm_source=npm-quick-lru&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,19 @@
# @babel/helper-string-parser
> A utility package to parse strings
See our website [@babel/helper-string-parser](https://babeljs.io/docs/babel-helper-string-parser) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-string-parser
```
or using yarn:
```sh
yarn add @babel/helper-string-parser
```

View File

@ -0,0 +1,31 @@
{
"name": "@babel/helper-string-parser",
"version": "7.29.7",
"description": "A utility package to parse strings",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-string-parser"
},
"homepage": "https://babel.dev/docs/en/next/babel-helper-string-parser",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"devDependencies": {
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"author": "The Babel Team (https://babel.dev/team)",
"exports": {
".": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./package.json": "./package.json"
},
"type": "commonjs"
}

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,19 @@
# @babel/helper-validator-identifier
> Validate identifier/keywords name
See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/babel-helper-validator-identifier) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-validator-identifier
```
or using yarn:
```sh
yarn add @babel/helper-validator-identifier
```

View File

@ -0,0 +1,31 @@
{
"name": "@babel/helper-validator-identifier",
"version": "7.29.7",
"description": "Validate identifier/keywords name",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-helper-validator-identifier"
},
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "./lib/index.js",
"exports": {
".": {
"types": "./lib/index.d.ts",
"default": "./lib/index.js"
},
"./package.json": "./package.json"
},
"devDependencies": {
"@unicode/unicode-17.0.0": "^1.6.10",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.9.0"
},
"author": "The Babel Team (https://babel.dev/team)",
"type": "commonjs"
}

1073
frontend/node_modules/@babel/parser/CHANGELOG.md generated vendored 100644

File diff suppressed because it is too large Load Diff

19
frontend/node_modules/@babel/parser/LICENSE generated vendored 100644
View File

@ -0,0 +1,19 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

19
frontend/node_modules/@babel/parser/README.md generated vendored 100644
View File

@ -0,0 +1,19 @@
# @babel/parser
> A JavaScript parser
See our website [@babel/parser](https://babeljs.io/docs/babel-parser) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20parser%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/parser
```
or using yarn:
```sh
yarn add @babel/parser --dev
```

View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
/* eslint-disable no-var, unicorn/prefer-node-protocol */
var parser = require("..");
var fs = require("fs");
var filename = process.argv[2];
if (!filename) {
console.error("no filename specified");
} else {
var file = fs.readFileSync(filename, "utf8");
var ast = parser.parse(file);
console.log(JSON.stringify(ast, null, " "));
}

View File

@ -0,0 +1,50 @@
{
"name": "@babel/parser",
"version": "7.29.9",
"description": "A JavaScript parser",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-parser",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A+parser+%28babylon%29%22+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"keywords": [
"babel",
"javascript",
"parser",
"tc39",
"ecmascript",
"@babel/parser"
],
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-parser"
},
"main": "./lib/index.js",
"types": "./typings/babel-parser.d.ts",
"files": [
"bin",
"lib",
"typings/babel-parser.d.ts",
"index.cjs"
],
"engines": {
"node": ">=6.0.0"
},
"# dependencies": "This package doesn't actually have runtime dependencies. @babel/types is only needed for type definitions.",
"dependencies": {
"@babel/types": "^7.29.8"
},
"devDependencies": {
"@babel/code-frame": "^7.29.7",
"@babel/helper-check-duplicate-nodes": "^7.29.7",
"@babel/helper-fixtures": "^7.29.7",
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7",
"charcodes": "^0.2.0"
},
"bin": "./bin/babel-parser.js",
"type": "commonjs"
}

View File

@ -0,0 +1,262 @@
// This file is auto-generated! Do not modify it directly.
// Run `yarn gulp bundle-dts` to re-generate it.
/* eslint-disable @typescript-eslint/consistent-type-imports, @typescript-eslint/no-redundant-type-constituents */
import { File, Expression } from '@babel/types';
declare class Position {
line: number;
column: number;
index: number;
constructor(line: number, col: number, index: number);
}
type SyntaxPlugin = "flow" | "typescript" | "jsx" | "functionBind" | "pipelineOperator" | "placeholders";
type ParseErrorCode = "BABEL_PARSER_SYNTAX_ERROR" | "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED";
interface ParseErrorSpecification<ErrorDetails> {
code: ParseErrorCode;
reasonCode: string;
syntaxPlugin?: SyntaxPlugin;
missingPlugin?: string | string[];
loc: Position;
details: ErrorDetails;
pos: number;
}
type ParseError$1<ErrorDetails> = SyntaxError & ParseErrorSpecification<ErrorDetails>;
type BABEL_8_BREAKING = false;
type IF_BABEL_7<V> = false extends BABEL_8_BREAKING ? V : never;
type Plugin$1 =
| "asyncDoExpressions"
| IF_BABEL_7<"asyncGenerators">
| IF_BABEL_7<"bigInt">
| IF_BABEL_7<"classPrivateMethods">
| IF_BABEL_7<"classPrivateProperties">
| IF_BABEL_7<"classProperties">
| IF_BABEL_7<"classStaticBlock">
| IF_BABEL_7<"decimal">
| "decorators-legacy"
| "deferredImportEvaluation"
| "decoratorAutoAccessors"
| "destructuringPrivate"
| IF_BABEL_7<"deprecatedImportAssert">
| "doExpressions"
| IF_BABEL_7<"dynamicImport">
| IF_BABEL_7<"explicitResourceManagement">
| "exportDefaultFrom"
| IF_BABEL_7<"exportNamespaceFrom">
| "flow"
| "flowComments"
| "functionBind"
| "functionSent"
| "importMeta"
| "jsx"
| IF_BABEL_7<"jsonStrings">
| IF_BABEL_7<"logicalAssignment">
| IF_BABEL_7<"importAssertions">
| IF_BABEL_7<"importReflection">
| "moduleBlocks"
| IF_BABEL_7<"moduleStringNames">
| IF_BABEL_7<"nullishCoalescingOperator">
| IF_BABEL_7<"numericSeparator">
| IF_BABEL_7<"objectRestSpread">
| IF_BABEL_7<"optionalCatchBinding">
| IF_BABEL_7<"optionalChaining">
| "partialApplication"
| "placeholders"
| IF_BABEL_7<"privateIn">
| IF_BABEL_7<"regexpUnicodeSets">
| "sourcePhaseImports"
| "throwExpressions"
| IF_BABEL_7<"topLevelAwait">
| "v8intrinsic"
| ParserPluginWithOptions[0];
type ParserPluginWithOptions =
| ["decorators", DecoratorsPluginOptions]
| ["discardBinding", { syntaxType: "void" }]
| ["estree", { classFeatures?: boolean }]
| IF_BABEL_7<["importAttributes", { deprecatedAssertSyntax: boolean }]>
| IF_BABEL_7<["moduleAttributes", { version: "may-2020" }]>
| ["optionalChainingAssign", { version: "2023-07" }]
| ["pipelineOperator", PipelineOperatorPluginOptions]
| ["recordAndTuple", RecordAndTuplePluginOptions]
| ["flow", FlowPluginOptions]
| ["typescript", TypeScriptPluginOptions];
type PluginConfig = Plugin$1 | ParserPluginWithOptions;
interface DecoratorsPluginOptions {
decoratorsBeforeExport?: boolean;
allowCallParenthesized?: boolean;
}
interface PipelineOperatorPluginOptions {
proposal: BABEL_8_BREAKING extends false
? "minimal" | "fsharp" | "hack" | "smart"
: "fsharp" | "hack";
topicToken?: "%" | "#" | "@@" | "^^" | "^";
}
interface RecordAndTuplePluginOptions {
syntaxType: "bar" | "hash";
}
type FlowPluginOptions = BABEL_8_BREAKING extends true
? {
all?: boolean;
enums?: boolean;
}
: {
all?: boolean;
};
interface TypeScriptPluginOptions {
dts?: boolean;
disallowAmbiguousJSXLike?: boolean;
}
type Plugin = PluginConfig;
type SourceType = "script" | "commonjs" | "module" | "unambiguous";
interface Options {
/**
* By default, import and export declarations can only appear at a program's top level.
* Setting this option to true allows them anywhere where a statement is allowed.
*/
allowImportExportEverywhere?: boolean;
/**
* By default, await use is not allowed outside of an async function.
* Set this to true to accept such code.
*/
allowAwaitOutsideFunction?: boolean;
/**
* By default, a return statement at the top level raises an error.
* Set this to true to accept such code.
*/
allowReturnOutsideFunction?: boolean;
/**
* By default, new.target use is not allowed outside of a function or class.
* Set this to true to accept such code.
*/
allowNewTargetOutsideFunction?: boolean;
/**
* By default, super calls are not allowed outside of a method.
* Set this to true to accept such code.
*/
allowSuperOutsideMethod?: boolean;
/**
* By default, exported identifiers must refer to a declared variable.
* Set this to true to allow export statements to reference undeclared variables.
*/
allowUndeclaredExports?: boolean;
/**
* By default, yield use is not allowed outside of a generator function.
* Set this to true to accept such code.
*/
allowYieldOutsideFunction?: boolean;
/**
* By default, Babel parser JavaScript code according to Annex B syntax.
* Set this to `false` to disable such behavior.
*/
annexB?: boolean;
/**
* By default, Babel attaches comments to adjacent AST nodes.
* When this option is set to false, comments are not attached.
* It can provide up to 30% performance improvement when the input code has many comments.
* @babel/eslint-parser will set it for you.
* It is not recommended to use attachComment: false with Babel transform,
* as doing so removes all the comments in output code, and renders annotations such as
* /* istanbul ignore next *\/ nonfunctional.
*/
attachComment?: boolean;
/**
* By default, Babel always throws an error when it finds some invalid code.
* When this option is set to true, it will store the parsing error and
* try to continue parsing the invalid input file.
*/
errorRecovery?: boolean;
/**
* Indicate the mode the code should be parsed in.
* Can be one of "script", "commonjs", "module", or "unambiguous". Defaults to "script".
* "unambiguous" will make @babel/parser attempt to guess, based on the presence
* of ES6 import or export statements.
* Files with ES6 imports and exports are considered "module" and are otherwise "script".
*
* Use "commonjs" to parse code that is intended to be run in a CommonJS environment such as Node.js.
*/
sourceType?: SourceType;
/**
* Correlate output AST nodes with their source filename.
* Useful when generating code and source maps from the ASTs of multiple input files.
*/
sourceFilename?: string;
/**
* By default, all source indexes start from 0.
* You can provide a start index to alternatively start with.
* Useful for integration with other source tools.
*/
startIndex?: number;
/**
* By default, the first line of code parsed is treated as line 1.
* You can provide a line number to alternatively start with.
* Useful for integration with other source tools.
*/
startLine?: number;
/**
* By default, the parsed code is treated as if it starts from line 1, column 0.
* You can provide a column number to alternatively start with.
* Useful for integration with other source tools.
*/
startColumn?: number;
/**
* Array containing the plugins that you want to enable.
*/
plugins?: Plugin[];
/**
* Should the parser work in strict mode.
* Defaults to true if sourceType === 'module'. Otherwise, false.
*/
strictMode?: boolean;
/**
* Adds a ranges property to each node: [node.start, node.end]
*/
ranges?: boolean;
/**
* Adds all parsed tokens to a tokens property on the File node.
*/
tokens?: boolean;
/**
* By default, the parser adds information about parentheses by setting
* `extra.parenthesized` to `true` as needed.
* When this option is `true` the parser creates `ParenthesizedExpression`
* AST nodes instead of using the `extra` property.
*/
createParenthesizedExpressions?: boolean;
/**
* The default is false in Babel 7 and true in Babel 8
* Set this to true to parse it as an `ImportExpression` node.
* Otherwise `import(foo)` is parsed as `CallExpression(Import, [Identifier(foo)])`.
*/
createImportExpressions?: boolean;
}
type ParserOptions = Partial<Options>;
type ParseError = ParseError$1<object>;
type ParseResult<Result extends File | Expression = File> = Result & {
comments: File["comments"];
errors: null | ParseError[];
tokens?: File["tokens"];
};
/**
* Parse the provided code as an entire ECMAScript program.
*/
declare function parse(input: string, options?: ParserOptions): ParseResult<File>;
declare function parseExpression(input: string, options?: ParserOptions): ParseResult<Expression>;
declare const tokTypes: {
// todo(flow->ts) real token type
[name: string]: any;
};
export { DecoratorsPluginOptions, FlowPluginOptions, ParseError, ParseResult, ParserOptions, PluginConfig as ParserPlugin, ParserPluginWithOptions, PipelineOperatorPluginOptions, RecordAndTuplePluginOptions, TypeScriptPluginOptions, parse, parseExpression, tokTypes };

22
frontend/node_modules/@babel/types/LICENSE generated vendored 100644
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

19
frontend/node_modules/@babel/types/README.md generated vendored 100644
View File

@ -0,0 +1,19 @@
# @babel/types
> Babel Types is a Lodash-esque utility library for AST nodes
See our website [@babel/types](https://babeljs.io/docs/babel-types) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20types%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/types
```
or using yarn:
```sh
yarn add @babel/types --dev
```

View File

@ -0,0 +1,39 @@
{
"name": "@babel/types",
"version": "7.29.8",
"description": "Babel Types is a Lodash-esque utility library for AST nodes",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-types",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20types%22+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-types"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"devDependencies": {
"@babel/generator": "^7.29.8",
"@babel/helper-fixtures": "^7.29.7",
"@babel/parser": "^7.29.8"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs",
"types": "./lib/index-legacy.d.ts",
"typesVersions": {
">=4.1": {
"lib/index-legacy.d.ts": [
"lib/index.d.ts"
]
}
}
}

View File

@ -0,0 +1,3 @@
# esbuild
This is the macOS ARM 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

Binary file not shown.

View File

@ -0,0 +1,20 @@
{
"name": "@esbuild/darwin-arm64",
"version": "0.21.5",
"description": "The macOS ARM 64-bit binary for esbuild, a JavaScript bundler.",
"repository": {
"type": "git",
"url": "git+https://github.com/evanw/esbuild.git"
},
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=12"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
]
}

View File

@ -0,0 +1,19 @@
Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,227 @@
# @jridgewell/gen-mapping
> Generate source maps
`gen-mapping` allows you to generate a source map during transpilation or minification.
With a source map, you're able to trace the original location in the source file, either in Chrome's
DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping].
You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This
provides the same `addMapping` and `setSourceContent` API.
## Installation
```sh
npm install @jridgewell/gen-mapping
```
## Usage
```typescript
import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping';
const map = new GenMapping({
file: 'output.js',
sourceRoot: 'https://example.com/',
});
setSourceContent(map, 'input.js', `function foo() {}`);
addMapping(map, {
// Lines start at line 1, columns at column 0.
generated: { line: 1, column: 0 },
source: 'input.js',
original: { line: 1, column: 0 },
});
addMapping(map, {
generated: { line: 1, column: 9 },
source: 'input.js',
original: { line: 1, column: 9 },
name: 'foo',
});
assert.deepEqual(toDecodedMap(map), {
version: 3,
file: 'output.js',
names: ['foo'],
sourceRoot: 'https://example.com/',
sources: ['input.js'],
sourcesContent: ['function foo() {}'],
mappings: [
[ [0, 0, 0, 0], [9, 0, 0, 9, 0] ]
],
});
assert.deepEqual(toEncodedMap(map), {
version: 3,
file: 'output.js',
names: ['foo'],
sourceRoot: 'https://example.com/',
sources: ['input.js'],
sourcesContent: ['function foo() {}'],
mappings: 'AAAA,SAASA',
});
```
### Smaller Sourcemaps
Not everything needs to be added to a sourcemap, and needless markings can cause signficantly
larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will
intelligently determine if this marking adds useful information. If not, the marking will be
skipped.
```typescript
import { maybeAddMapping } from '@jridgewell/gen-mapping';
const map = new GenMapping();
// Adding a sourceless marking at the beginning of a line isn't useful.
maybeAddMapping(map, {
generated: { line: 1, column: 0 },
});
// Adding a new source marking is useful.
maybeAddMapping(map, {
generated: { line: 1, column: 0 },
source: 'input.js',
original: { line: 1, column: 0 },
});
// But adding another marking pointing to the exact same original location isn't, even if the
// generated column changed.
maybeAddMapping(map, {
generated: { line: 1, column: 9 },
source: 'input.js',
original: { line: 1, column: 0 },
});
assert.deepEqual(toEncodedMap(map), {
version: 3,
names: [],
sources: ['input.js'],
sourcesContent: [null],
mappings: 'AAAA',
});
```
## Benchmarks
```
node v18.0.0
amp.js.map
Memory Usage:
gen-mapping: addSegment 5852872 bytes
gen-mapping: addMapping 7716042 bytes
source-map-js 6143250 bytes
source-map-0.6.1 6124102 bytes
source-map-0.8.0 6121173 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled)
gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled)
source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled)
source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled)
source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled)
gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled)
source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled)
source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled)
source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled)
Fastest is gen-mapping: decoded output
***
babel.min.js.map
Memory Usage:
gen-mapping: addSegment 37578063 bytes
gen-mapping: addMapping 37212897 bytes
source-map-js 47638527 bytes
source-map-0.6.1 47690503 bytes
source-map-0.8.0 47470188 bytes
Smallest memory usage is gen-mapping: addMapping
Adding speed:
gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled)
gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled)
source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled)
source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled)
source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled)
gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled)
source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled)
source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled)
source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled)
Fastest is gen-mapping: decoded output
***
preact.js.map
Memory Usage:
gen-mapping: addSegment 416247 bytes
gen-mapping: addMapping 419824 bytes
source-map-js 1024619 bytes
source-map-0.6.1 1146004 bytes
source-map-0.8.0 1113250 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled)
gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled)
source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled)
source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled)
source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled)
gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled)
source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled)
source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled)
source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled)
Fastest is gen-mapping: decoded output
***
react.js.map
Memory Usage:
gen-mapping: addSegment 975096 bytes
gen-mapping: addMapping 1102981 bytes
source-map-js 2918836 bytes
source-map-0.6.1 2885435 bytes
source-map-0.8.0 2874336 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled)
gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled)
source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled)
source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled)
source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled)
gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled)
source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled)
source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled)
source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled)
Fastest is gen-mapping: decoded output
```
[source-map]: https://www.npmjs.com/package/source-map
[trace-mapping]: https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping

View File

@ -0,0 +1,67 @@
{
"name": "@jridgewell/gen-mapping",
"version": "0.3.13",
"description": "Generate source maps",
"keywords": [
"source",
"map"
],
"main": "dist/gen-mapping.umd.js",
"module": "dist/gen-mapping.mjs",
"types": "types/gen-mapping.d.cts",
"files": [
"dist",
"src",
"types"
],
"exports": {
".": [
{
"import": {
"types": "./types/gen-mapping.d.mts",
"default": "./dist/gen-mapping.mjs"
},
"default": {
"types": "./types/gen-mapping.d.cts",
"default": "./dist/gen-mapping.umd.js"
}
},
"./dist/gen-mapping.umd.js"
],
"./package.json": "./package.json"
},
"scripts": {
"benchmark": "run-s build:code benchmark:*",
"benchmark:install": "cd benchmark && npm install",
"benchmark:only": "node --expose-gc benchmark/index.js",
"build": "run-s -n build:code build:types",
"build:code": "node ../../esbuild.mjs gen-mapping.ts",
"build:types": "run-s build:types:force build:types:emit build:types:mts",
"build:types:force": "rimraf tsconfig.build.tsbuildinfo",
"build:types:emit": "tsc --project tsconfig.build.json",
"build:types:mts": "node ../../mts-types.mjs",
"clean": "run-s -n clean:code clean:types",
"clean:code": "tsc --build --clean tsconfig.build.json",
"clean:types": "rimraf dist types",
"test": "run-s -n test:types test:only test:format",
"test:format": "prettier --check '{src,test}/**/*.ts'",
"test:only": "mocha",
"test:types": "eslint '{src,test}/**/*.ts'",
"lint": "run-s -n lint:types lint:format",
"lint:format": "npm run test:format -- --write",
"lint:types": "npm run test:types -- --fix",
"prepublishOnly": "npm run-s -n build test"
},
"homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/gen-mapping",
"repository": {
"type": "git",
"url": "git+https://github.com/jridgewell/sourcemaps.git",
"directory": "packages/gen-mapping"
},
"author": "Justin Ridgewell <justin@ridgewell.name>",
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
}

View File

@ -0,0 +1,614 @@
import { SetArray, put, remove } from './set-array';
import {
encode,
// encodeGeneratedRanges,
// encodeOriginalScopes
} from '@jridgewell/sourcemap-codec';
import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';
import {
COLUMN,
SOURCES_INDEX,
SOURCE_LINE,
SOURCE_COLUMN,
NAMES_INDEX,
} from './sourcemap-segment';
import type { SourceMapInput } from '@jridgewell/trace-mapping';
// import type { OriginalScope, GeneratedRange } from '@jridgewell/sourcemap-codec';
import type { SourceMapSegment } from './sourcemap-segment';
import type {
DecodedSourceMap,
EncodedSourceMap,
Pos,
Mapping,
// BindingExpressionRange,
// OriginalPos,
// OriginalScopeInfo,
// GeneratedRangeInfo,
} from './types';
export type { DecodedSourceMap, EncodedSourceMap, Mapping };
export type Options = {
file?: string | null;
sourceRoot?: string | null;
};
const NO_NAME = -1;
/**
* Provides the state to generate a sourcemap.
*/
export class GenMapping {
declare private _names: SetArray<string>;
declare private _sources: SetArray<string>;
declare private _sourcesContent: (string | null)[];
declare private _mappings: SourceMapSegment[][];
// private declare _originalScopes: OriginalScope[][];
// private declare _generatedRanges: GeneratedRange[];
declare private _ignoreList: SetArray<number>;
declare file: string | null | undefined;
declare sourceRoot: string | null | undefined;
constructor({ file, sourceRoot }: Options = {}) {
this._names = new SetArray();
this._sources = new SetArray();
this._sourcesContent = [];
this._mappings = [];
// this._originalScopes = [];
// this._generatedRanges = [];
this.file = file;
this.sourceRoot = sourceRoot;
this._ignoreList = new SetArray();
}
}
interface PublicMap {
_names: GenMapping['_names'];
_sources: GenMapping['_sources'];
_sourcesContent: GenMapping['_sourcesContent'];
_mappings: GenMapping['_mappings'];
// _originalScopes: GenMapping['_originalScopes'];
// _generatedRanges: GenMapping['_generatedRanges'];
_ignoreList: GenMapping['_ignoreList'];
}
/**
* Typescript doesn't allow friend access to private fields, so this just casts the map into a type
* with public access modifiers.
*/
function cast(map: unknown): PublicMap {
return map as any;
}
/**
* A low-level API to associate a generated position with an original source position. Line and
* column here are 0-based, unlike `addMapping`.
*/
export function addSegment(
map: GenMapping,
genLine: number,
genColumn: number,
source?: null,
sourceLine?: null,
sourceColumn?: null,
name?: null,
content?: null,
): void;
export function addSegment(
map: GenMapping,
genLine: number,
genColumn: number,
source: string,
sourceLine: number,
sourceColumn: number,
name?: null,
content?: string | null,
): void;
export function addSegment(
map: GenMapping,
genLine: number,
genColumn: number,
source: string,
sourceLine: number,
sourceColumn: number,
name: string,
content?: string | null,
): void;
export function addSegment(
map: GenMapping,
genLine: number,
genColumn: number,
source?: string | null,
sourceLine?: number | null,
sourceColumn?: number | null,
name?: string | null,
content?: string | null,
): void {
return addSegmentInternal(
false,
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content,
);
}
/**
* A high-level API to associate a generated position with an original source position. Line is
* 1-based, but column is 0-based, due to legacy behavior in `source-map` library.
*/
export function addMapping(
map: GenMapping,
mapping: {
generated: Pos;
source?: null;
original?: null;
name?: null;
content?: null;
},
): void;
export function addMapping(
map: GenMapping,
mapping: {
generated: Pos;
source: string;
original: Pos;
name?: null;
content?: string | null;
},
): void;
export function addMapping(
map: GenMapping,
mapping: {
generated: Pos;
source: string;
original: Pos;
name: string;
content?: string | null;
},
): void;
export function addMapping(
map: GenMapping,
mapping: {
generated: Pos;
source?: string | null;
original?: Pos | null;
name?: string | null;
content?: string | null;
},
): void {
return addMappingInternal(false, map, mapping as Parameters<typeof addMappingInternal>[2]);
}
/**
* Same as `addSegment`, but will only add the segment if it generates useful information in the
* resulting map. This only works correctly if segments are added **in order**, meaning you should
* not add a segment with a lower generated line/column than one that came before.
*/
export const maybeAddSegment: typeof addSegment = (
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content,
) => {
return addSegmentInternal(
true,
map,
genLine,
genColumn,
source,
sourceLine,
sourceColumn,
name,
content,
);
};
/**
* Same as `addMapping`, but will only add the mapping if it generates useful information in the
* resulting map. This only works correctly if mappings are added **in order**, meaning you should
* not add a mapping with a lower generated line/column than one that came before.
*/
export const maybeAddMapping: typeof addMapping = (map, mapping) => {
return addMappingInternal(true, map, mapping as Parameters<typeof addMappingInternal>[2]);
};
/**
* Adds/removes the content of the source file to the source map.
*/
export function setSourceContent(map: GenMapping, source: string, content: string | null): void {
const {
_sources: sources,
_sourcesContent: sourcesContent,
// _originalScopes: originalScopes,
} = cast(map);
const index = put(sources, source);
sourcesContent[index] = content;
// if (index === originalScopes.length) originalScopes[index] = [];
}
export function setIgnore(map: GenMapping, source: string, ignore = true) {
const {
_sources: sources,
_sourcesContent: sourcesContent,
_ignoreList: ignoreList,
// _originalScopes: originalScopes,
} = cast(map);
const index = put(sources, source);
if (index === sourcesContent.length) sourcesContent[index] = null;
// if (index === originalScopes.length) originalScopes[index] = [];
if (ignore) put(ignoreList, index);
else remove(ignoreList, index);
}
/**
* Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
* a sourcemap, or to JSON.stringify.
*/
export function toDecodedMap(map: GenMapping): DecodedSourceMap {
const {
_mappings: mappings,
_sources: sources,
_sourcesContent: sourcesContent,
_names: names,
_ignoreList: ignoreList,
// _originalScopes: originalScopes,
// _generatedRanges: generatedRanges,
} = cast(map);
removeEmptyFinalLines(mappings);
return {
version: 3,
file: map.file || undefined,
names: names.array,
sourceRoot: map.sourceRoot || undefined,
sources: sources.array,
sourcesContent,
mappings,
// originalScopes,
// generatedRanges,
ignoreList: ignoreList.array,
};
}
/**
* Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
* a sourcemap, or to JSON.stringify.
*/
export function toEncodedMap(map: GenMapping): EncodedSourceMap {
const decoded = toDecodedMap(map);
return Object.assign({}, decoded, {
// originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)),
// generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]),
mappings: encode(decoded.mappings as SourceMapSegment[][]),
});
}
/**
* Constructs a new GenMapping, using the already present mappings of the input.
*/
export function fromMap(input: SourceMapInput): GenMapping {
const map = new TraceMap(input);
const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
putAll(cast(gen)._names, map.names);
putAll(cast(gen)._sources, map.sources as string[]);
cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null);
cast(gen)._mappings = decodedMappings(map) as GenMapping['_mappings'];
// TODO: implement originalScopes/generatedRanges
if (map.ignoreList) putAll(cast(gen)._ignoreList, map.ignoreList);
return gen;
}
/**
* Returns an array of high-level mapping objects for every recorded segment, which could then be
* passed to the `source-map` library.
*/
export function allMappings(map: GenMapping): Mapping[] {
const out: Mapping[] = [];
const { _mappings: mappings, _sources: sources, _names: names } = cast(map);
for (let i = 0; i < mappings.length; i++) {
const line = mappings[i];
for (let j = 0; j < line.length; j++) {
const seg = line[j];
const generated = { line: i + 1, column: seg[COLUMN] };
let source: string | undefined = undefined;
let original: Pos | undefined = undefined;
let name: string | undefined = undefined;
if (seg.length !== 1) {
source = sources.array[seg[SOURCES_INDEX]];
original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];
}
out.push({ generated, source, original, name } as Mapping);
}
}
return out;
}
// This split declaration is only so that terser can elminiate the static initialization block.
function addSegmentInternal<S extends string | null | undefined>(
skipable: boolean,
map: GenMapping,
genLine: number,
genColumn: number,
source: S,
sourceLine: S extends string ? number : null | undefined,
sourceColumn: S extends string ? number : null | undefined,
name: S extends string ? string | null | undefined : null | undefined,
content: S extends string ? string | null | undefined : null | undefined,
): void {
const {
_mappings: mappings,
_sources: sources,
_sourcesContent: sourcesContent,
_names: names,
// _originalScopes: originalScopes,
} = cast(map);
const line = getIndex(mappings, genLine);
const index = getColumnIndex(line, genColumn);
if (!source) {
if (skipable && skipSourceless(line, index)) return;
return insert(line, index, [genColumn]);
}
// Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source
// isn't nullish.
assert<number>(sourceLine);
assert<number>(sourceColumn);
const sourcesIndex = put(sources, source);
const namesIndex = name ? put(names, name) : NO_NAME;
if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;
// if (sourcesIndex === originalScopes.length) originalScopes[sourcesIndex] = [];
if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
return;
}
return insert(
line,
index,
name
? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
: [genColumn, sourcesIndex, sourceLine, sourceColumn],
);
}
function assert<T>(_val: unknown): asserts _val is T {
// noop.
}
function getIndex<T>(arr: T[][], index: number): T[] {
for (let i = arr.length; i <= index; i++) {
arr[i] = [];
}
return arr[index];
}
function getColumnIndex(line: SourceMapSegment[], genColumn: number): number {
let index = line.length;
for (let i = index - 1; i >= 0; index = i--) {
const current = line[i];
if (genColumn >= current[COLUMN]) break;
}
return index;
}
function insert<T>(array: T[], index: number, value: T) {
for (let i = array.length; i > index; i--) {
array[i] = array[i - 1];
}
array[index] = value;
}
function removeEmptyFinalLines(mappings: SourceMapSegment[][]) {
const { length } = mappings;
let len = length;
for (let i = len - 1; i >= 0; len = i, i--) {
if (mappings[i].length > 0) break;
}
if (len < length) mappings.length = len;
}
function putAll<T extends string | number>(setarr: SetArray<T>, array: T[]) {
for (let i = 0; i < array.length; i++) put(setarr, array[i]);
}
function skipSourceless(line: SourceMapSegment[], index: number): boolean {
// The start of a line is already sourceless, so adding a sourceless segment to the beginning
// doesn't generate any useful information.
if (index === 0) return true;
const prev = line[index - 1];
// If the previous segment is also sourceless, then adding another sourceless segment doesn't
// genrate any new information. Else, this segment will end the source/named segment and point to
// a sourceless position, which is useful.
return prev.length === 1;
}
function skipSource(
line: SourceMapSegment[],
index: number,
sourcesIndex: number,
sourceLine: number,
sourceColumn: number,
namesIndex: number,
): boolean {
// A source/named segment at the start of a line gives position at that genColumn
if (index === 0) return false;
const prev = line[index - 1];
// If the previous segment is sourceless, then we're transitioning to a source.
if (prev.length === 1) return false;
// If the previous segment maps to the exact same source position, then this segment doesn't
// provide any new position information.
return (
sourcesIndex === prev[SOURCES_INDEX] &&
sourceLine === prev[SOURCE_LINE] &&
sourceColumn === prev[SOURCE_COLUMN] &&
namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)
);
}
function addMappingInternal<S extends string | null | undefined>(
skipable: boolean,
map: GenMapping,
mapping: {
generated: Pos;
source: S;
original: S extends string ? Pos : null | undefined;
name: S extends string ? string | null | undefined : null | undefined;
content: S extends string ? string | null | undefined : null | undefined;
},
) {
const { generated, source, original, name, content } = mapping;
if (!source) {
return addSegmentInternal(
skipable,
map,
generated.line - 1,
generated.column,
null,
null,
null,
null,
null,
);
}
assert<Pos>(original);
return addSegmentInternal(
skipable,
map,
generated.line - 1,
generated.column,
source as string,
original.line - 1,
original.column,
name,
content,
);
}
/*
export function addOriginalScope(
map: GenMapping,
data: {
start: Pos;
end: Pos;
source: string;
kind: string;
name?: string;
variables?: string[];
},
): OriginalScopeInfo {
const { start, end, source, kind, name, variables } = data;
const {
_sources: sources,
_sourcesContent: sourcesContent,
_originalScopes: originalScopes,
_names: names,
} = cast(map);
const index = put(sources, source);
if (index === sourcesContent.length) sourcesContent[index] = null;
if (index === originalScopes.length) originalScopes[index] = [];
const kindIndex = put(names, kind);
const scope: OriginalScope = name
? [start.line - 1, start.column, end.line - 1, end.column, kindIndex, put(names, name)]
: [start.line - 1, start.column, end.line - 1, end.column, kindIndex];
if (variables) {
scope.vars = variables.map((v) => put(names, v));
}
const len = originalScopes[index].push(scope);
return [index, len - 1, variables];
}
*/
// Generated Ranges
/*
export function addGeneratedRange(
map: GenMapping,
data: {
start: Pos;
isScope: boolean;
originalScope?: OriginalScopeInfo;
callsite?: OriginalPos;
},
): GeneratedRangeInfo {
const { start, isScope, originalScope, callsite } = data;
const {
_originalScopes: originalScopes,
_sources: sources,
_sourcesContent: sourcesContent,
_generatedRanges: generatedRanges,
} = cast(map);
const range: GeneratedRange = [
start.line - 1,
start.column,
0,
0,
originalScope ? originalScope[0] : -1,
originalScope ? originalScope[1] : -1,
];
if (originalScope?.[2]) {
range.bindings = originalScope[2].map(() => [[-1]]);
}
if (callsite) {
const index = put(sources, callsite.source);
if (index === sourcesContent.length) sourcesContent[index] = null;
if (index === originalScopes.length) originalScopes[index] = [];
range.callsite = [index, callsite.line - 1, callsite.column];
}
if (isScope) range.isScope = true;
generatedRanges.push(range);
return [range, originalScope?.[2]];
}
export function setEndPosition(range: GeneratedRangeInfo, pos: Pos) {
range[0][2] = pos.line - 1;
range[0][3] = pos.column;
}
export function addBinding(
map: GenMapping,
range: GeneratedRangeInfo,
variable: string,
expression: string | BindingExpressionRange,
) {
const { _names: names } = cast(map);
const bindings = (range[0].bindings ||= []);
const vars = range[1];
const index = vars!.indexOf(variable);
const binding = getIndex(bindings, index);
if (typeof expression === 'string') binding[0] = [put(names, expression)];
else {
const { start } = expression;
binding.push([put(names, expression.expression), start.line - 1, start.column]);
}
}
*/

View File

@ -0,0 +1,82 @@
type Key = string | number | symbol;
/**
* SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
* index of the `key` in the backing array.
*
* This is designed to allow synchronizing a second array with the contents of the backing array,
* like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
* and there are never duplicates.
*/
export class SetArray<T extends Key = Key> {
declare private _indexes: Record<T, number | undefined>;
declare array: readonly T[];
constructor() {
this._indexes = { __proto__: null } as any;
this.array = [];
}
}
interface PublicSet<T extends Key> {
array: T[];
_indexes: SetArray<T>['_indexes'];
}
/**
* Typescript doesn't allow friend access to private fields, so this just casts the set into a type
* with public access modifiers.
*/
function cast<T extends Key>(set: SetArray<T>): PublicSet<T> {
return set as any;
}
/**
* Gets the index associated with `key` in the backing array, if it is already present.
*/
export function get<T extends Key>(setarr: SetArray<T>, key: T): number | undefined {
return cast(setarr)._indexes[key];
}
/**
* Puts `key` into the backing array, if it is not already present. Returns
* the index of the `key` in the backing array.
*/
export function put<T extends Key>(setarr: SetArray<T>, key: T): number {
// The key may or may not be present. If it is present, it's a number.
const index = get(setarr, key);
if (index !== undefined) return index;
const { array, _indexes: indexes } = cast(setarr);
const length = array.push(key);
return (indexes[key] = length - 1);
}
/**
* Pops the last added item out of the SetArray.
*/
export function pop<T extends Key>(setarr: SetArray<T>): void {
const { array, _indexes: indexes } = cast(setarr);
if (array.length === 0) return;
const last = array.pop()!;
indexes[last] = undefined;
}
/**
* Removes the key, if it exists in the set.
*/
export function remove<T extends Key>(setarr: SetArray<T>, key: T): void {
const index = get(setarr, key);
if (index === undefined) return;
const { array, _indexes: indexes } = cast(setarr);
for (let i = index + 1; i < array.length; i++) {
const k = array[i];
array[i - 1] = k;
indexes[k]!--;
}
indexes[key] = undefined;
array.pop();
}

Some files were not shown because too many files have changed in this diff Show More