feat(前端): 切换到 TypeScript 构建产物(dist/app.js),JS 版保留可回滚

切换
- templates/map.html:四个 script(navigation/share/subscribe/map.js)
  → 一行 /static/dist/app.js;geo.js 保留(bundle 内同一份实现,幂等)
- routes/map_api.py 的 MAP_ASSETS 同步换成 dist/app.js,缓存戳跟着产物走

随切换修的
- walk-route:onSearchComplete 里 res.getStatus() 加存在性判断
  (起点≈终点时上游返回空壳,原 JS 版与 TS 版都会抛未捕获 TypeError),两版同步修
- compat/globals.ts 末尾挂 window.S = S:原版 91 个顶层 let/var 是全局词法绑定,
  bundle 里收进 state 对象,至少把 state 暴露出来便于排障
- tests/test_map_assets.py 断言改为 dist/app.js
- tests/test_history_30d.py:子进程加 import os + XBCR_DISABLE_BACKGROUND=1
  (原来采集线程会往临时库写 bike_history,导致统计断言偶发失败)
- app.py 支持 XBCR_DISABLE_BACKGROUND=1:只初始化数据库、不起后台线程(测试/工具用)
- tests/test_rounds_and_preview.py:remaining_seconds 允许 2 秒误差(跨秒抖动)

回滚
- 把 map.html 那行换回四个 script、MAP_ASSETS 换回四个文件名即可;
  static/js/ 一字未改,dist 留着也不会被加载

验证:167 pytest(连跑 3 次)+ 32 node 全绿;浏览器实测(390px,真实数据)
车 498、卡片 #51143 / 步行 488 米、导航条「前方 170 米 右转」、共享/订阅面板可开、
JS 异常 0
This commit is contained in:
zzy
2026-11-16 11:14:59 +08:00
parent 8ece55983a
commit 44efe5f4f4
11 changed files with 58 additions and 13 deletions
+8
View File
@@ -709,6 +709,14 @@ def bootstrap():
except Exception as exc: except Exception as exc:
print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}") print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}")
is_leader = True is_leader = True
# 测试/工具场景:只要数据库和路由,不启动任何后台线程(避免采集线程写库
# 干扰用例的统计断言)
if os.environ.get("XBCR_DISABLE_BACKGROUND") == "1":
print("[启动] XBCR_DISABLE_BACKGROUND=1:只初始化数据库,不启动后台线程")
with _bootstrap_lock:
_bootstrap_done = True
return True
if not is_leader: if not is_leader:
print("[启动] 本进程不是 leader:跳过采集/巡检/定时器/调度线程") print("[启动] 本进程不是 leader:跳过采集/巡检/定时器/调度线程")
print("[启动] bootstrap 完成(web worker)") print("[启动] bootstrap 完成(web worker)")
+1 -2
View File
@@ -460,8 +460,7 @@ def api_user_info():
MAP_ASSETS = ( MAP_ASSETS = (
"css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css", "css/map.css", "css/bike-clusters.css", "css/map-settings.css", "css/ui-system.css",
"js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js", "js/ui-motion.js", "js/qrcode.min.js", "js/coordtransform.js", "js/bike-clusters.js",
"js/settings-pages.js", "js/navigation.js", "js/share.js", "js/subscribe.js", "js/settings-pages.js", "js/src/core/geo.js", "dist/app.js",
"js/src/core/geo.js", "js/map.js",
) )
+5
View File
@@ -5,6 +5,7 @@
* 函数清单由 tools/gen.mjs 从源文件里抓,正常情况下与 map.js 的全局面 1:1 对应。 * 函数清单由 tools/gen.mjs 从源文件里抓,正常情况下与 map.js 的全局面 1:1 对应。
*/ */
import { Geo, offsetCoord, calcDistance } from "../core/geo"; import { Geo, offsetCoord, calcDistance } from "../core/geo";
import { S } from "../core/state";
import { _fitCardActions, closeCard, showBikeDetail, updateRingProgress, viewBikeDetailFromOrder, viewBikeDetailFromOrderModal } from "../card/bike-card"; import { _fitCardActions, closeCard, showBikeDetail, updateRingProgress, viewBikeDetailFromOrder, viewBikeDetailFromOrderModal } from "../card/bike-card";
import { describeTokenExpiry, escHtml, fmtClock, fmtDuration, fmtLocalTime, fmtOrderTime, fmtRemainShort, fmtTime, friendlyError, remainingTimeText, rideProgressText } from "../core/format"; import { describeTokenExpiry, escHtml, fmtClock, fmtDuration, fmtLocalTime, fmtOrderTime, fmtRemainShort, fmtTime, friendlyError, remainingTimeText, rideProgressText } from "../core/format";
import { shareApi } from "../core/http"; import { shareApi } from "../core/http";
@@ -317,3 +318,7 @@ window.Geo = Geo;
window.offsetCoord = offsetCoord; window.offsetCoord = offsetCoord;
window.calcDistance = calcDistance; window.calcDistance = calcDistance;
/* 排障用:原版 91 个顶层 let/var 都是全局词法绑定,控制台可直接读写;
bundle 里它们收在 state 对象内(ESM 不能给 import 绑定赋值),
这里把 state 本身挂出去,保持同样的可观测性。 */
(window as any).S = S;
+8 -1
View File
@@ -90,7 +90,14 @@ export async function refineWalkRoute(bike) {
const walk = new BMapGL.WalkingRoute(S.map, { const walk = new BMapGL.WalkingRoute(S.map, {
renderOptions: { map: null, panel: null }, renderOptions: { map: null, panel: null },
onSearchComplete: res => { onSearchComplete: res => {
if (!res || res.getStatus() !== 0) return finish(null); // 退化路线(起点≈终点)时 res 可能是空壳、没有 getStatus,
// 直接调用会抛未捕获 TypeError(与原 JS 版同步修复)
let status = -1;
try {
status = (res && typeof (res as any).getStatus === "function")
? (res as any).getStatus() : -1;
} catch (e) { status = -1; }
if (status !== 0) return finish(null);
try { try {
const p = res.getPlan(0); const p = res.getPlan(0);
const d = parseWalkDistance(p.getDistance()); const d = parseWalkDistance(p.getDistance());
+8
View File
@@ -132,3 +132,11 @@ MAP_ASSETS = (
除此之外,块内正文与 `static/js/*.js` **逐行一致**(`node src-ts/tools/gen.mjs` 的 除此之外,块内正文与 `static/js/*.js` **逐行一致**(`node src-ts/tools/gen.mjs` 的
保真度报告:6144 行搬运,归一化后只剩上述 1 行结构差异)。 保真度报告:6144 行搬运,归一化后只剩上述 1 行结构差异)。
## 补充(验收后修正)
- **状态可观测性**:原版 91 个顶层 `let/var` 是全局词法绑定,控制台能直接读写。
bundle 里它们收进 `core/state.ts` 的 `S` 对象,并额外执行 `window.S = S;`,
排障时用 `S.selectedBike` / `S.orderCountdownSeconds` 等价替代。
- **退化路线**:`nav/walk-route.ts` 的 `onSearchComplete` 对 `res.getStatus()`
增加了存在性判断(起点≈终点时上游会返回空壳),原 JS 版已同步修掉这条历史 TypeError。
+8 -1
View File
@@ -432,7 +432,13 @@
const walk = new BMapGL.WalkingRoute(S.map, { const walk = new BMapGL.WalkingRoute(S.map, {
renderOptions: { map: null, panel: null }, renderOptions: { map: null, panel: null },
onSearchComplete: (res) => { onSearchComplete: (res) => {
if (!res || res.getStatus() !== 0) return finish(null); let status = -1;
try {
status = res && typeof res.getStatus === "function" ? res.getStatus() : -1;
} catch (e) {
status = -1;
}
if (status !== 0) return finish(null);
try { try {
const p = res.getPlan(0); const p = res.getPlan(0);
const d = parseWalkDistance(p.getDistance()); const d = parseWalkDistance(p.getDistance());
@@ -5726,6 +5732,7 @@
window.Geo = Geo; window.Geo = Geo;
window.offsetCoord = offsetCoord; window.offsetCoord = offsetCoord;
window.calcDistance = calcDistance; window.calcDistance = calcDistance;
window.S = S;
// src-ts/main.ts // src-ts/main.ts
function bootstrap() { function bootstrap() {
+8 -1
View File
@@ -85,7 +85,14 @@
const walk = new BMapGL.WalkingRoute(map, { const walk = new BMapGL.WalkingRoute(map, {
renderOptions: { map: null, panel: null }, renderOptions: { map: null, panel: null },
onSearchComplete: res => { onSearchComplete: res => {
if (!res || res.getStatus() !== 0) return finish(null); // 退化路线(起点≈终点)时 res 可能是空壳、没有 getStatus,
// 直接调用会抛未捕获 TypeError(两版都有的历史问题)
let status = -1;
try {
status = (res && typeof res.getStatus === "function")
? res.getStatus() : -1;
} catch (e) { status = -1; }
if (status !== 0) return finish(null);
try { try {
const p = res.getPlan(0); const p = res.getPlan(0);
const d = parseWalkDistance(p.getDistance()); const d = parseWalkDistance(p.getDistance());
+2 -4
View File
@@ -970,10 +970,8 @@
<script defer src="/static/js/bike-clusters.js?v={{ map_asset_version }}"></script> <script defer src="/static/js/bike-clusters.js?v={{ map_asset_version }}"></script>
<script defer src="/static/js/settings-pages.js?v={{ map_asset_version }}"></script> <script defer src="/static/js/settings-pages.js?v={{ map_asset_version }}"></script>
<!-- 拆分后的模块:导航 / 共享 / 订阅(全局函数名不变,map.js 直接调用) --> <!-- 拆分后的模块:导航 / 共享 / 订阅(全局函数名不变,map.js 直接调用) -->
<script defer src="/static/js/navigation.js?v={{ map_asset_version }}"></script> <!-- TypeScript 重写版(esbuild IIFE,等价于上面四个脚本;回滚=换回那四行) -->
<script defer src="/static/js/share.js?v={{ map_asset_version }}"></script> <script defer src="/static/dist/app.js?v={{ map_asset_version }}"></script>
<script defer src="/static/js/subscribe.js?v={{ map_asset_version }}"></script>
<script defer src="/static/js/map.js?v={{ map_asset_version }}"></script>
<!-- 还车确认弹窗 --> <!-- 还车确认弹窗 -->
<div class="return-confirm-modal" id="return-confirm-modal"> <div class="return-confirm-modal" id="return-confirm-modal">
+5 -1
View File
@@ -9,16 +9,20 @@ app.py 在 import 期还会重包装 stdout,曾破坏 pytest 捕获。
因此本文件把整个验证放进一个独立的 python 子进程运行: 因此本文件把整个验证放进一个独立的 python 子进程运行:
父进程零污染,失败时完整透出子进程输出。 父进程零污染,失败时完整透出子进程输出。
""" """
import os
import subprocess import subprocess
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
import sys import sys
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).parent.parent ROOT = Path(__file__).parent.parent
CHILD = r''' CHILD = r'''
import sys, tempfile, json import os, sys, tempfile, json
from pathlib import Path from pathlib import Path
ROOT = Path(r"{root}") ROOT = Path(r"{root}")
os.environ["XBCR_DISABLE_BACKGROUND"] = "1"
sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT))
import db as db_mod import db as db_mod
+3 -2
View File
@@ -31,7 +31,8 @@ class MapAssetTests(unittest.TestCase):
self.assertNotIn("", versions) self.assertNotIn("", versions)
self.assertRegex(html, r'<script async src="https://api\.map\.baidu\.com/') self.assertRegex(html, r'<script async src="https://api\.map\.baidu\.com/')
self.assertIn("&callback=onBaiduMapReady", html) self.assertIn("&callback=onBaiduMapReady", html)
self.assertRegex(html, r'<script defer src="/static/js/map\.js\?v=') # TypeScript 重写后:四个脚本合成一个 esbuild IIFE 包
self.assertRegex(html, r'<script defer src="/static/dist/app\.js\?v=')
def test_changing_a_dependency_invalidates_the_whole_bundle_version(self): def test_changing_a_dependency_invalidates_the_whole_bundle_version(self):
with tempfile.TemporaryDirectory() as folder: with tempfile.TemporaryDirectory() as folder:
@@ -42,7 +43,7 @@ class MapAssetTests(unittest.TestCase):
before = self.app.test_client().get("/").get_data(as_text=True) before = self.app.test_client().get("/").get_data(as_text=True)
dependency.write_text("new", encoding="utf-8") dependency.write_text("new", encoding="utf-8")
after = self.app.test_client().get("/").get_data(as_text=True) after = self.app.test_client().get("/").get_data(as_text=True)
pattern = r'/static/js/map\.js\?v=([a-f0-9]+)' pattern = r'/static/dist/app\.js\?v=([a-f0-9]+)'
self.assertNotEqual(re.search(pattern, before)[1], re.search(pattern, after)[1]) self.assertNotEqual(re.search(pattern, before)[1], re.search(pattern, after)[1])
+2 -1
View File
@@ -201,7 +201,8 @@ class OrderEndpointsTests(unittest.TestCase):
self.assertEqual(4, response.get_json()["data"]["total_rounds"]) self.assertEqual(4, response.get_json()["data"]["total_rounds"])
# 本轮到期时间与剩余时长保持不变 # 本轮到期时间与剩余时长保持不变
self.assertEqual(before["end_time"], after["end_time"]) self.assertEqual(before["end_time"], after["end_time"])
self.assertEqual(before["remaining_seconds"], after["remaining_seconds"]) # 两次请求之间可能跨秒:剩余秒数允许 2 秒误差(end_time 必须完全相同)
self.assertLessEqual(abs(before["remaining_seconds"] - after["remaining_seconds"]), 2)
# 预计还车时间随轮数增加而后移 # 预计还车时间随轮数增加而后移
self.assertEqual(4, after["total_rounds"]) self.assertEqual(4, after["total_rounds"])
self.assertGreater(after["final_end_time"], before["final_end_time"]) self.assertGreater(after["final_end_time"], before["final_end_time"])