feat(前端): TypeScript 重写版(esbuild IIFE 产物,暂不接管线上)

- 新增 src-ts/(22 个 .ts / 7792 行):按 core / map / card / order / nav / share /
  subscribe / ui / compat 分层,types 里有 BMapGL 与 API 响应声明
- compat/globals.ts 是唯一挂 window 的地方(292 个),覆盖模板 139 处内联事件
- esbuild 产出 static/dist/app.js(226.6 KiB,IIFE,es2019)+ README(构建/切换/回滚)
- 构建可复现:node esbuild.config.mjs、node --check、npx tsc --noEmit 均通过
- .gitignore 增加 node_modules/ 与 static/dist/*.map(sourcemap 可重生成,不入库)
- 暂不改 templates/map.html 与 MAP_ASSETS:等独立核对通过再切换,回滚=换回四个 script
This commit is contained in:
zzy
2026-11-16 10:44:11 +08:00
parent f8db1240b1
commit 8ece55983a
32 changed files with 16155 additions and 0 deletions
+848
View File
@@ -0,0 +1,848 @@
#!/usr/bin/env node
/* 迁移工具(**不是**构建的一部分,只用来生成 src-ts/ 的初稿)
*
* 作用:把 static/js/{navigation,share,subscribe,map}.js 这些**经典脚本**里的
* 顶层「函数声明 / 变量声明 / 顶层语句」逐块切出来,按 MODULES 表分派到 src-ts/
* 各模块,代码正文逐字搬运(只去掉 4 空格缩进),并自动生成 import 头。
*
* 唯一会改写正文的地方:原先靠「全局词法绑定」跨模块共享的可变状态(map /
* selectedBike / currentOrder / authToken …),在 bundle 里集中到 core/state.ts
* 的 S 对象上,正文里的裸标识符改写为 S.xxx(ES 模块不允许改 import 进来的绑定)。
*
* 用法:
* node src-ts/tools/gen.mjs --analyze # 只打印分析结果
* node src-ts/tools/gen.mjs # 生成 / 覆盖 src-ts/**\/*.ts
*/
import fs from "node:fs";
import path from "node:path";
import vm from "node:vm";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, "..", "..");
const SRC_TS = path.resolve(HERE, "..");
const ANALYZE_ONLY = process.argv.includes("--analyze");
const SOURCES = [
{ id: "navigation", file: "static/js/navigation.js" },
{ id: "share", file: "static/js/share.js" },
{ id: "subscribe", file: "static/js/subscribe.js" },
{ id: "map", file: "static/js/map.js" },
];
/* ---------------- 1. 遮罩(注释 / 字符串字面量 / 模板字面量的**文本部分** / 正则 → 空格)
* 注意:模板里的 `${ ... }` 是**代码**,必须保持原样,否则 ${authToken} 这类
* 表达式里的标识符会被当成字符串内容漏掉。这里用状态栈递归处理。 */
function mask(text) {
const out = text.split("");
const n = text.length;
const blank = (a, b) => { for (let k = a; k < b; k++) if (out[k] !== "\n") out[k] = " "; };
const stack = [{ type: "code", depth: 0 }];
let prev = "";
let i = 0;
const top = () => stack[stack.length - 1];
const wordBefore = (at) => {
let j = at - 1;
while (j >= 0 && /\s/.test(text[j])) j--;
const end = j + 1;
while (j >= 0 && /[\w$]/.test(text[j])) j--;
return text.slice(j + 1, end);
};
while (i < n) {
const cur = top();
const c = text[i], c2 = text[i + 1];
if (cur.type === "tpl") {
if (c === "\\") { blank(i, i + 2); i += 2; continue; }
if (c === "`") { blank(i, i + 1); stack.pop(); i++; prev = "str"; continue; }
if (c === "$" && c2 === "{") { stack.push({ type: "code", depth: 0 }); i += 2; prev = "{"; continue; }
blank(i, i + 1); i++;
continue;
}
/* code 帧 */
if (c === "}" && stack.length > 1 && cur.depth === 0) { stack.pop(); i++; prev = "}"; continue; }
if (c === "/" && c2 === "/") { let j = text.indexOf("\n", i); if (j < 0) j = n; blank(i, j); i = j; continue; }
if (c === "/" && c2 === "*") { let j = text.indexOf("*/", i + 2); j = j < 0 ? n : j + 2; blank(i, j); i = j; continue; }
if (c === '"' || c === "'") {
let j = i + 1;
while (j < n) {
if (text[j] === "\\") { j += 2; continue; }
if (text[j] === c) { j++; break; }
if (text[j] === "\n") break;
j++;
}
blank(i + 1, Math.max(i + 1, j - 1));
i = j; prev = "str";
continue;
}
if (c === "`") { stack.push({ type: "tpl" }); blank(i, i + 1); i++; continue; }
if (c === "/") {
const ok = prev === "" || /[=(,:;[{!&|?+\-*%~^<>]/.test(prev) ||
/\b(?:return|typeof|case|in|of|new|delete|void|instanceof)$/.test(wordBefore(i));
if (ok) {
let j = i + 1, cls = false;
while (j < n) {
const ch = text[j];
if (ch === "\\") { j += 2; continue; }
if (ch === "[") cls = true;
else if (ch === "]") cls = false;
else if (ch === "/" && !cls) { j++; break; }
else if (ch === "\n") break;
j++;
}
blank(i + 1, Math.max(i + 1, j - 1));
i = j; prev = "regex";
continue;
}
prev = c; i++; continue;
}
if (c === "{") cur.depth++;
else if (c === "}") cur.depth--;
if (!/\s/.test(c)) prev = c;
i++;
}
return out.join("");
}
/* ---------------- 2. 切块 ---------------- */
const OPEN = new Set(["{", "(", "["]);
const CLOSE = new Set(["}", ")", "]"]);
const CONT_END = /(?:=|=>|\+|-|\*|\/|%|&&|\|\||\?|:|,|\.|\(|\[|\{|<|>|&|\||!|~|\^)\s*$/;
const CONT_START = /^(\?|:|\.|\+|-|\*|\/|%|&&|\|\||&|\||=|<|>|,)$/;
function splitBlocks(file, text) {
const masked = mask(text);
const lines = text.split("\n");
const mLines = masked.split("\n");
if (lines.length !== mLines.length) throw new Error("mask 长度不一致: " + file);
const depthStart = new Array(lines.length);
let depth = 0;
for (let li = 0; li < lines.length; li++) {
depthStart[li] = depth;
const m = mLines[li];
for (let k = 0; k < m.length; k++) {
const ch = m[k];
if (OPEN.has(ch)) depth++;
else if (CLOSE.has(ch)) depth--;
}
}
if (depth !== 0) throw new Error(`${file}: 括号不平衡(残留 ${depth})`);
const starts = [];
for (let li = 0; li < lines.length; li++) {
const m = mLines[li];
const t = m.trim();
if (!t) continue;
const indent = m.length - m.replace(/^ +/, "").length;
if (indent !== 4) continue;
if (depthStart[li] !== 0) continue;
if (CONT_START.test(t)) continue;
if (starts.length) {
let p = li - 1;
while (p >= 0 && !mLines[p].trim()) p--;
if (p >= 0 && CONT_END.test(mLines[p])) continue;
}
starts.push(li);
}
const blocks = [];
for (let s = 0; s < starts.length; s++) {
const from = starts[s];
let to = (s + 1 < starts.length ? starts[s + 1] : lines.length) - 1;
while (to > from && !lines[to].trim()) to--;
const body = lines.slice(from, to + 1).map((l) => l.replace(/^ {4}/, "")).join("\n");
const mbody = mLines.slice(from, to + 1).map((l) => l.replace(/^ {4}/, "")).join("\n");
blocks.push({ file, from: from + 1, to: to + 1, body, masked: mbody });
}
return blocks;
}
function classify(block) {
const t = (block.masked.split("\n").find((l) => l.trim()) || "").trim();
let m = /^(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/.exec(t);
if (m) return { kind: "function", name: m[1] };
m = /^(?:let|const|var)\s+([A-Za-z_$][\w$]*)/.exec(t);
if (m) {
const declKind = /^const/.test(t) ? "const" : "let";
if (!/^const/.test(t) && /,/.test(t.split(";")[0]) && m[1]) {
/* 多声明符很少见,提示一下 */
}
return { kind: "var", name: m[1], declKind };
}
return { kind: "stmt", name: null };
}
/* ---------------- 3. 分派表 ---------------- */
const MODULES = {
"core/http.ts": ["shareApi"],
"core/format.ts": [
"escHtml", "fmtTime", "fmtLocalTime", "describeTokenExpiry", "fmtRemainShort",
"fmtDuration", "fmtOrderTime", "fmtClock", "friendlyError", "rideProgressText", "remainingTimeText",
],
"map/icons.ts": [
"iconCache", "ICON_CACHE_MAX", "BASE_ICON_COLORS", "prebuiltIcons", "createFullIcon",
"preloadBaseIcons", "makeIconDataURI", "RED_BIKE_COLOR", "getBikeKind", "getBikeIcon", "getBikeState",
],
"map/core.ts": [
"BAIDU_AK", "INIT_OFFSET_EXTRA", "INIT_OFFSET_EAST", "mapInitializationStarted", "initMap",
"initMapCore", "updateMapStyle", "mapRequest", "mapRefreshTimer", "renderedMapSnapshot",
"mapRefreshFailed", "scheduleMapRefresh", "loadMapData", "refreshMap", "mapSnapshotNow",
"updateMapFreshnessBadge", "updateTime", "showFreshnessDetail", "locateMe", "findNearestBikeManual",
"showMyLocation", "createAutoLocationIcon", "updateAutoLocation", "startAutoLocation",
"stopAutoLocation", "findNearestBike",
],
"map/markers.ts": [
"findMarkerById", "bringMarkerToTop", "setHighlight", "clearHighlight", "bindMarkerDomTouch",
"bindMarkerTap", "renderMap", "setupClusterListener", "rebuildMarkersForZoom", "bikeBubbleLayer",
],
"card/bike-card.ts": [
"showBikeDetail", "closeCard", "_fitCardActions", "_fitCardTimer", "_cardZoomTimer",
"viewBikeDetailFromOrder", "viewBikeDetailFromOrderModal", "updateRingProgress",
],
"order/status.ts": [
"currentOrder", "checkOrderStatus", "showOrderBanner", "orderCountdownTimer",
"orderCountdownSeconds", "orderCountdownDeadline", "orderCountdownOrderId", "fetchOrderCountdown",
"showOrderCountdown", "hideOrderCountdown", "_orderLastAlertAt", "_alertOrderExpiring",
"updateOrderCountdownText", "startOrderCountdown", "hideOrderBanner", "isOrderActionEligible",
"handleOrderBannerSurfaceClick", "showOrderActionsModal", "closeOrderActionsModal",
"handleOrderBannerClick", "payCurrentOrderFromModal", "returnCurrentOrderFromModal",
"findCurrentOrderBike", "orderCardHtml",
],
"order/actions.ts": [
"tryCardPayOrRedirect", "cardPayLoading", "returnLoading", "pendingReturnOrder",
"getOrderOperationLocation", "showReturnConfirm", "closeReturnConfirm", "doReturnBike",
"orderTempActionLoading", "tempLockCurrentOrder", "tempUnlockCurrentOrder", "unlockPendingCode",
"unlockPendingPosition", "handleQuickUnlock", "unlockChoice", "unlockSrcList", "unlockSrcShowAll",
"openUnlockAccountChooser", "renderUnlockSrcList", "loadUnlockSrcShowAll", "chooseUnlockSrc",
"closeUnlockSrc", "proceedToUnlockConfirm", "closeUnlockConfirm", "doUnlockBike", "quickUnlock",
"startRentalFromServer", "clearRentalState", "openRentalSettingsModal", "closeRentalSettingsModal",
"saveRentalSettings", "syncWechatOrder", "checkRentalStatus", "startRental", "showRentalBar",
"updateRentalFinalTime", "updateRentalCountdown", "showReturnModal", "closeReturnModal",
"confirmReturn", "isNativeShell", "nativeUnlockBike", "unlockBike", "openOrderTrajectory",
"closeOrderTrajModal", "renderOrderTrajectory", "orderTrajMap", "orderTrajOverlays",
"openOrdersModal", "closeOrdersModal", "renderUnlockPreview", "loadUnlockPreview",
"_addRoundTarget", "showAddRoundConfirm", "closeAddRoundModal", "confirmAddRound",
"addRoundForCurrent", "addRoundFromBanner", "findBike", "_doFindBikeRequest", "showLostModal",
"closeLostModal", "enableLostMode", "disableLostMode", "_onPageUnload", "_onVisibilityChange",
"_lostModeActive", "_lostModeTimer", "_findClickCount", "_findClickTimer", "_findLongPressTimer",
"LOST_TRIGGER_CLICKS", "LOST_TRIGGER_LONG", "LOST_INTERVAL", "scanCode", "currentBellTab",
"selectedRadius", "selectedLocation", "selectedStatuses", "rangeCircleOverlay",
"showBellPasswordModal", "switchBellTab", "selectRadius", "useCurrentLocation",
"useCenterLocation", "updateRangeCircle", "toggleStatusFilter", "updateStatusCounts",
"getFilteredBikes", "updateFilterInfo", "closeBellModal", "submitBellPassword",
],
"ui/settings.ts": [
"openSettingsPage", "closeSettingsPage", "saveMapClusteringSetting", "showProfileModal",
"closeProfileModal", "closeAllModals", "loadProfileData", "loadUserInfo", "parseJwtExpiry",
"renderTokenExpiry", "updateTokenExpiryDisplays", "_savedTokenExpiry",
"AUTH_EXPIRY_BANNER_THRESHOLD", "AUTH_EXPIRY_BANNER_URGENT", "renderAuthExpiryBanner",
"refreshAuthExpiry", "openAuthModal", "closeAuthModal", "_strictGuideShown", "maybeStrictGuide",
"checkStrictGuide", "getDeviceId", "getDeviceName", "openDevicesModal", "closeDevicesModal",
"loadDevicesList", "kickDevice", "logoutAllOtherDevices", "openPackagesModal",
"closePackagesModal", "loadPackagesList", "saveProfileToken", "showLoginGate", "hideLoginGate",
"doLogin", "handleLoginSubmit", "registerCodeCountdown", "registerCodeTimer",
"setRegisterCodeBtn", "sendRegisterCode", "handleRegisterSubmit", "handleLogout",
"updateAuthButton", "BATCH_RING_ALLOWED_EMAILS", "canUseBatchRing", "updateBellBtnVisibility",
"checkAuthStatus", "showLoginModal", "closeLoginModal", "showRegisterModal",
"closeRegisterModal", "handleAuthBtnClick", "_forgotFromGate", "showForgotModal",
"showForgotFromGate", "closeForgotModal", "backToLoginFromForgot", "forgotTimer",
"setForgotCodeBtn", "sendForgotCode", "handleForgotSubmit", "openVersionModal",
"closeVersionModal", "maybeAutoShowVersion", "VERSION_TAG", "VERSION_LOGS",
"versionModalInited", "versionAutoTries",
],
"ui/modals.ts": [
"appConfirm", "appConfirmClose", "_appConfirmResolve", "showToast", "showDownloadTipModal",
"closeDownloadTipModal", "closeExportTipModal", "copyExportLink", "exportHistoryCsv",
"copyDownloadLink", "showTokenExpiredModal", "closeTokenExpiredModal", "loadExpiredTokenFields",
"saveExpiredToken", "notifyCredentialInvalid", "_credInvalidLastShownAt",
"CRED_INVALID_MODAL_COOLDOWN", "CAPTURE_TOOL_PATH", "detectHarmony", "detectMobile",
"detectInAppBrowser", "captureToolUrl", "onDownloadCaptureTool", "showQrModal", "closeQrModal",
"createQrImage", "setupQrLongPress", "currentQrPosition", "longPressTimer", "longPressTarget",
"qrModalBikeCode", "shareAfterLogin",
],
"nav/navigation.ts": [
"_nav", "_navLoading", "_navEpoch", "NAV_DEVIATE_M", "NAV_RECOMPUTE_COOLDOWN_MS", "NAV_SNAP_M",
"NAV_BOTTOM_RATIO", "NAV_FREE_TIMEOUT", "_haversineM", "_gpsToGcj", "_bearing",
"_projectOnRoute", "_navBanner", "_navPill", "_navBtnText", "_clearNavLayers", "_redrawRoute",
"_headingSupported", "_headingAnim", "_rotateByAnimation", "_applyHeading", "_centerOnUser",
"_compassHeading", "_compassBound", "_bindCompass", "_ensureCompassPermission", "_navArrowIcon",
"_turnKind", "_turnSvg", "_setTurnIcon", "_destIcon", "_placeNavArrow", "_rotateNavArrow",
"_clearNavArrow", "_navTick", "_navGuidance", "_recomputeRoute", "_requestNavRoute",
"_applyRoute", "stopNavigation", "toggleNavigation", "_navSelfMoveUntil",
"_markProgrammaticMove", "_scheduleResume", "_onMapDragStart", "_onMapDragging",
"_onMapDragEnd", "resumeNavigation", "startNavigation", "bindNavMapEvents",
],
"nav/walk-route.ts": [
"_walkRouteCache", "MAX_WALK_DISTANCE_M", "parseWalkDistance", "parseWalkDuration",
"refineWalkRoute",
],
"share/share.ts": [
"partnerLabel", "shareRec", "shareTabNow", "openShareModal", "closeShareModal", "switchShareTab",
"sharePendingHtml", "loadShareData", "sendShareRequest", "acceptShareRequest",
"rejectShareRequest", "shareCfg", "openShareConfig", "closeShareConfig", "saveShareConfig",
"unbindShare", "shareRemarkCfg", "openShareRemark", "closeShareRemark", "saveShareRemark",
"shareAskQueue", "shareAskActive", "shareAskCur", "checkPendingShareRequests",
"nextShareAskIfQueue", "acceptCurrentShareAsk", "rejectCurrentShareAsk", "shareActiveList",
"pendingShareReturn", "refreshShareBanners", "openShareReturnByIdx", "updateShareCountdowns",
"closeShareReturnModal", "confirmShareReturn",
],
"subscribe/subscribe.ts": [
"subscribeLocations", "SUB_WEEKDAYS", "openSubscribeModal", "closeSubscribeModal",
"loadSubscribeLocations", "subRuleRowHtml", "toggleSubAdvanced", "loadSubscribeRules",
"addSubscribeRule", "toggleSubscribeRule", "deleteSubscribeRule",
],
};
/* 搬进 core/state.ts 的可变状态(原本靠全局词法绑定跨模块共享) */
const STATE_VARS = [
"map", "currentType", "currentUser", "authKickToastShown", "authMode", "authToken",
"currentMarkers", "currentPolygons", "selectedBike", "markersData", "currentMarkersById",
"scannedMarkers", "myLocationMarker", "autoLocationMarker", "autoLocationWatchId",
"hasLocationPermission", "initialLocationCentered", "nearestBikeId", "isFirstLoad",
"highlightedBikeId", "bikeClusteringEnabled", "activeRental", "rentalCountdownTimer",
/* 下面几个原本在 map.js 顶层、但被别处的块(含顶层 IIFE / handleLogout)赋值,
* ESM 下 import 进来的绑定不能赋值,同样收进 S。 */
"currentOrder", "shareAskQueue", "shareAskActive",
"_fitCardTimer", "_findClickCount", "_findLongPressTimer",
];
const STATE_CONSTS = ["RENTAL_KEY"];
/* 由手写模块提供、但被搬过来的正文直接使用的名字(原先是 geo.js 的全局函数) */
const EXTRA_HOME = {
offsetCoord: "core/geo.ts",
calcDistance: "core/geo.ts",
Geo: "core/geo.ts",
};
/* ---------------- 4. 分析 ---------------- */
function analyse() {
const blocks = [];
for (const src of SOURCES) {
const text = fs.readFileSync(path.join(ROOT, src.file), "utf8").replace(/\r\n/g, "\n");
for (const p of splitBlocks(src.file, text)) {
blocks.push({ ...p, ...classify(p), source: src.id });
}
}
const bad = [];
for (const b of blocks) {
try { new vm.Script(b.body, { filename: `${b.file}:${b.from}` }); }
catch (e) { bad.push({ where: `${b.file}:${b.from}-${b.to}`, err: e.message, head: b.body.split("\n")[0] }); }
}
return { blocks, bad };
}
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
function moduleOf(name) {
for (const [mod, names] of Object.entries(MODULES)) if (names.includes(name)) return mod;
return null;
}
function relSpecifier(fromModule, toModule) {
const from = path.posix.dirname(fromModule);
let rel = path.posix.relative(from, toModule).replace(/\.ts$/, "");
if (!rel.startsWith(".")) rel = "./" + rel;
return rel;
}
function main() {
const { blocks, bad } = analyse();
if (bad.length) {
console.log("=== 切块语法自检失败 ===");
for (const b of bad) console.log(` ${b.where} ${b.err}\n ${b.head}`);
process.exitCode = 1;
return;
}
/* 去重(同名声明只保留第一份) */
const emitted = new Set();
const decls = [];
const dups = [];
for (const b of blocks) {
if (b.kind === "stmt") continue;
if (emitted.has(b.name)) { dups.push(`${b.name} @ ${b.file}:${b.from}`); continue; }
emitted.add(b.name);
decls.push(b);
}
const stmts = blocks.filter((b) => b.kind === "stmt");
const stateSet = new Set(STATE_VARS);
const stateConstSet = new Set(STATE_CONSTS);
const homeOf = new Map();
const unassigned = [];
for (const b of decls) {
if (stateSet.has(b.name) || stateConstSet.has(b.name)) homeOf.set(b.name, "core/state.ts");
else {
const m = moduleOf(b.name);
if (!m) unassigned.push(`${b.name} @ ${b.file}:${b.from}`);
else homeOf.set(b.name, m);
}
}
/* 引用 / 赋值统计 */
const nameSet = new Set([...decls.map((b) => b.name), ...Object.keys(EXTRA_HOME)]);
/** 某个名字的「家」:搬过来的块,或手写模块(core/geo.ts 之类)。 */
const homeOfExt = (n) => homeOf.get(n) || EXTRA_HOME[n];
const identRe = /(\.\.\.|^|[^.\w$])([A-Za-z_$][\w$]*)(?![\w$])/mg;
const refsBy = new Map();
const writeBy = new Map();
const units = [
...decls.map((b) => ({ module: homeOf.get(b.name), text: b.masked, where: `${b.file}:${b.from}` })),
...stmts.map((b) => ({ module: "__boot", text: b.masked, where: `${b.file}:${b.from}` })),
];
for (const u of units) {
let m;
identRe.lastIndex = 0;
while ((m = identRe.exec(u.text))) {
const n = m[2];
if (!nameSet.has(n)) continue;
if (!refsBy.has(n)) refsBy.set(n, new Set());
refsBy.get(n).add(u.module);
}
for (const n of nameSet) {
const re = new RegExp(`(^|[^.\\w$])${esc(n)}\\s*(=(?![=>])|\\+=|-=|\\*=|/=|\\+\\+|--)`, "g");
let mm;
while ((mm = re.exec(u.text))) {
if (!writeBy.has(n)) writeBy.set(n, new Set());
writeBy.get(n).add(u.module);
}
}
}
const crossRef = (n) => [...(refsBy.get(n) || [])].some((m) => m !== homeOf.get(n));
const foreignWriters = (n) => [...(writeBy.get(n) || [])].filter((m) => m !== homeOf.get(n));
/* 局部遮蔽检查(只查真·声明位置) */
const shadowOf = new Map();
for (const b of blocks) {
for (const n of stateSet) {
const pats = [
new RegExp(`\\(\\s*${esc(n)}\\s*[,)]`),
new RegExp(`,\\s*${esc(n)}\\s*[,)=]`),
new RegExp(`(?:let|const|var)\\s+${esc(n)}\\b`),
new RegExp(`catch\\s*\\(\\s*${esc(n)}\\b`),
new RegExp(`(?:^|[\\s(,])${esc(n)}\\s*=>`),
new RegExp(`\\(\\s*\\{[^)]*\\b${esc(n)}\\b[^)]*\\}\\s*\\)\\s*=`),
];
if (pats.some((r) => r.test(b.masked))) {
if (!shadowOf.has(n)) shadowOf.set(n, []);
shadowOf.get(n).push(`${b.file}:${b.from} (${b.name || "stmt"})`);
}
}
}
if (ANALYZE_ONLY) {
console.log(`块 ${blocks.length} | 声明 ${decls.length} | 顶层语句 ${stmts.length} | 切块语法自检 ✓`);
/* 覆盖率:源文件里每一行「有代码但没被任何块覆盖」的都算漏搬 */
for (const src of SOURCES) {
const text = fs.readFileSync(path.join(ROOT, src.file), "utf8").replace(/\r\n/g, "\n");
const mLines = mask(text).split("\n");
const covered = new Set();
for (const b of blocks) {
if (b.file !== src.file) continue;
for (let l = b.from; l <= b.to; l++) covered.add(l);
}
const missing = [];
for (let l = 1; l <= mLines.length; l++) {
if (covered.has(l)) continue;
if (!mLines[l - 1].trim()) continue; // 空行 / 纯注释
missing.push(l);
}
console.log(`覆盖检查 ${src.file}: 共 ${mLines.length} 行,未被块覆盖的**代码**行 ${missing.length}` +
(missing.length ? ` -> ${missing.slice(0, 20).join(",")}` : " ✓"));
}
console.log(`\n未分派声明 ${unassigned.length}: ${unassigned.join(", ") || "无"}`);
console.log(`\n同名重复声明 ${dups.length}: ${dups.join("; ") || "无"}`);
console.log("\n状态变量的局部遮蔽候选:");
for (const [n, list] of shadowOf) console.log(` ${n}: ${list.join("; ")}`);
console.log("\n需要 setter 的跨模块赋值变量:");
for (const n of nameSet) {
const f = foreignWriters(n);
if (f.length) console.log(` ${n} home=${homeOf.get(n)} writers=${f.join(",")}`);
}
console.log("\n顶层语句(按原顺序):");
stmts.forEach((s) => console.log(` ${s.file}:${s.from}-${s.to} ${s.body.split("\n")[0].slice(0, 80)}`));
return;
}
if (unassigned.length) {
console.error("有声明没分派:" + unassigned.join(", "));
process.exitCode = 1;
return;
}
/* ---------------- 5. 改写:状态变量 → S.xxx ---------------- */
const renameReport = [];
const skippedKeys = [];
function rewrite(text, masked) {
const spans = [];
for (const n of stateSet) {
const re = new RegExp(`(\\.\\.\\.|^|[^.\\w$])${esc(n)}(?![\\w$])`, "gm");
let m;
while ((m = re.exec(masked))) {
const start = m.index + m[1].length;
const end = start + n.length;
if (text.slice(start, end) !== n) continue;
const prevCh = masked.slice(0, start).replace(/\s+$/, "").slice(-1);
const nextCh = masked.slice(end).replace(/^\s+/, "").slice(0, 1);
/* 对象字面量的**键**位置({ name: ... })不动 */
if (nextCh === ":" && (prevCh === "{" || prevCh === "," || prevCh === "(")) {
skippedKeys.push(`${n} @ ${prevCh}${n}:`);
continue;
}
/* 对象字面量的**简写属性**(`{ map, ... }`):必须写成 `map: S.map`,
* 否则 `S.map` 在键位置不是合法语法。判断方式:该行(去掉缩进、去掉
* 行尾逗号)恰好只有这个名字。全仓只有 map.js:3242 一处。 */
const lineStart = masked.lastIndexOf("\n", start) + 1;
const nl = masked.indexOf("\n", end);
const lineEnd = nl < 0 ? masked.length : nl;
const lineCode = text.slice(lineStart, lineEnd).trim();
const lineMasked = masked.slice(lineStart, lineEnd).trim();
if ((lineMasked === n || lineMasked === n + ",") && lineCode === lineMasked) {
spans.push([start, end, `${n}: S.${n}`]);
continue;
}
spans.push([start, end, `S.${n}`]);
}
}
spans.sort((a, b) => b[0] - a[0]);
let out = text;
for (const [s, e, rep] of spans) out = out.slice(0, s) + rep + out.slice(e);
if (spans.length) renameReport.push(spans.length);
return out;
}
const n_of = (text, s, e) => text.slice(s, e);
const rewritten = new Map();
for (const b of blocks) {
rewritten.set(b, b.body);
}
function applyRewrite(b) { rewritten.set(b, rewrite(b.body, b.masked)); }
/* ---------------- 6. 生成 core/state.ts ---------------- */
const stateLines = [];
stateLines.push("/* 全局可变状态集中处。");
stateLines.push(" *");
stateLines.push(" * 原实现里 map.js 顶部那一堆 `let xxx = ...` 是**经典脚本的全局词法绑定**,");
stateLines.push(" * 被 navigation/share/subscribe/map 四个脚本一起读写。改成 ES 模块后,import 进来的");
stateLines.push(" * 绑定不可赋值,所以这里统一收进 S 对象;正文里的裸标识符写成 S.xxx(由 tools/gen.mjs 改写)。");
stateLines.push(" * 语义不变:同一个对象、同一份可变状态、初始化顺序仍在模块求值阶段。");
stateLines.push(" */");
stateLines.push("");
stateLines.push("/** 状态容器类型:字段按需增删,读取处一律 any。 */");
stateLines.push("export type AppState = Record<string, any>;");
stateLines.push("");
stateLines.push("export const S: AppState = {");
const stateBlocks = decls.filter((b) => stateSet.has(b.name));
for (const b of stateBlocks) {
const init = extractInitializer(b.body, b.name);
stateLines.push(` // ${b.file}:${b.from}`);
stateLines.push(` ${init},`);
}
stateLines.push("};");
stateLines.push("");
for (const b of decls.filter((x) => stateConstSet.has(x.name))) {
const masked = mask(b.body);
const semi = masked.lastIndexOf(";");
const decl = semi > 0 ? b.body.slice(0, semi + 1) : b.body;
stateLines.push(`// ${b.file}:${b.from}`);
stateLines.push(`export ${decl.replace(/^var\s+/, "const ")}`);
stateLines.push("");
}
const stateSrc = stateLines.join("\n") + "\n";
/* ---------------- 7. 生成各功能模块 ---------------- */
const moduleOrder = [
"core/http.ts", "core/format.ts", "map/icons.ts", "map/core.ts", "map/markers.ts",
"card/bike-card.ts", "order/status.ts", "order/actions.ts", "ui/settings.ts", "ui/modals.ts",
"nav/navigation.ts", "nav/walk-route.ts", "share/share.ts", "subscribe/subscribe.ts",
];
const byModule = new Map(moduleOrder.map((m) => [m, []]));
for (const b of decls) {
const home = homeOf.get(b.name);
if (home === "core/state.ts") { applyRewriteAlways(b); continue; }
byModule.get(home).push(b);
}
function applyRewriteAlways(b) {
/* state 变量在 state.ts 里是对象字段,不改写;但其它块要改 */
rewritten.set(b, b.body);
}
for (const [mod, list] of byModule) {
for (const b of list) applyRewrite(b);
}
for (const st of stmts) applyRewrite(st);
const fileOut = new Map();
for (const mod of moduleOrder) {
const list = byModule.get(mod);
const needS = list.some((b) => rewritten.get(b).includes("S."));
const imports = new Map();
const add = (target, name) => {
if (!imports.has(target)) imports.set(target, new Set());
imports.get(target).add(name);
};
for (const b of list) {
let m;
identRe.lastIndex = 0;
while ((m = identRe.exec(b.masked))) {
const n = m[2];
if (!nameSet.has(n)) continue;
const home = homeOfExt(n);
if (!home || home === mod) continue;
if (stateSet.has(n)) continue; /* S 的字段走 S.x;stateConstSet 是普通 const,仍需 import */
add(home, n);
}
}
const head = [];
head.push(`/* 由 static/js/{navigation,share,subscribe,map}.js 逐块搬运而来;正文与原实现一致。 */`);
head.push("");
if (needS) head.push(`import { S } from "${relSpecifier(mod, "core/state.ts")}";`);
const sc = [...(imports.get("core/state.ts") || [])];
if (sc.length) head.push(`import { ${sc.join(", ")} } from "${relSpecifier(mod, "core/state.ts")}";`);
for (const [target, names] of [...imports].sort((a, b) => a[0].localeCompare(b[0]))) {
if (target === "core/state.ts") continue;
head.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier(mod, target)}";`);
}
if (head[head.length - 1] !== "") head.push("");
const body = [];
for (const b of list) {
const txt = rewritten.get(b);
body.push(`// ${b.file}:${b.from}-${b.to}`);
if (b.kind === "function") body.push("export " + txt);
else if (b.kind === "var") {
const exp = crossRef(b.name) ? "export " : "";
/* 顶层 let 一律标 any:这些变量在原实现里是 JS 的动态变量,会被赋成别的类型 */
const annotated = b.declKind === "let" ? annotateLetAny(txt, b.name) : txt;
body.push(exp + annotated);
}
body.push("");
}
fileOut.set(mod, head.join("\n") + body.join("\n"));
}
/* ---------------- 8. 生成 main.ts(bootstrap 顺序) ---------------- */
const bootImports = new Map();
for (const st of stmts) {
let m;
identRe.lastIndex = 0;
while ((m = identRe.exec(st.masked))) {
const n = m[2];
if (!nameSet.has(n)) continue;
const home = homeOfExt(n);
if (!home || stateSet.has(n)) continue;
if (!bootImports.has(home)) bootImports.set(home, new Set());
bootImports.get(home).add(n);
}
}
const bootNeedS = stmts.some((s) => rewritten.get(s).includes("S."));
const mainHead = [
"/* 入口:装配顺序 + 原先分散在各脚本顶层的「注册/定时器/首屏初始化」语句。",
" *",
" * 这些语句在原实现里按 [navigation → share → subscribe → map] 的脚本顺序,",
" * 在各文件中「按行号」执行;这里 1:1 按同一顺序搬进 bootstrap(),末尾立即调用。",
" */",
'import "./compat/globals";',
];
if (bootNeedS) mainHead.push(`import { S } from "./core/state";`);
const scBoot = [...(bootImports.get("core/state.ts") || [])];
if (scBoot.length) mainHead.push(`import { ${scBoot.join(", ")} } from "./core/state";`);
for (const [target, names] of [...bootImports].sort((a, b) => a[0].localeCompare(b[0]))) {
if (target === "core/state.ts") continue;
mainHead.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier("main.ts", target)}";`);
}
mainHead.push("");
mainHead.push("/** 原脚本顶层副作用:注册监听 / 起定时器 / 首屏 auth 与弹窗判定。 */");
mainHead.push("export function bootstrap(): void {");
for (const st of stmts) {
mainHead.push(` // ${st.file}:${st.from}-${st.to}`);
mainHead.push(rewritten.get(st).replace(/^/gm, " ").replace(/^ {4}$/gm, ""));
}
mainHead.push("}");
mainHead.push("");
mainHead.push("bootstrap();");
mainHead.push("");
fileOut.set("main.ts", mainHead.join("\n"));
/* ---------------- 9. 生成 compat/globals.ts ---------------- */
const fnNames = decls.filter((b) => b.kind === "function").map((b) => b.name).sort();
const compatImports = new Map();
for (const b of decls.filter((x) => x.kind === "function")) {
const home = homeOf.get(b.name);
if (!compatImports.has(home)) compatImports.set(home, new Set());
compatImports.get(home).add(b.name);
}
const compat = [];
compat.push("/* **唯一**把函数挂到 window 的地方。");
compat.push(" *");
compat.push(" * templates/map.html 里还有大量内联 onclick=\"foo()\",它们要求 foo 是全局函数。");
compat.push(" * 原实现是经典脚本(顶层 function 声明天然成为全局),bundle 之后必须显式挂回去。");
compat.push(" * 函数清单由 tools/gen.mjs 从源文件里抓,正常情况下与 map.js 的全局面 1:1 对应。");
compat.push(" */");
compat.push(`import { Geo, offsetCoord, calcDistance } from "${relSpecifier("compat/globals.ts", "core/geo.ts")}";`);
for (const [target, names] of [...compatImports].sort((a, b) => a[0].localeCompare(b[0]))) {
compat.push(`import { ${[...names].sort().join(", ")} } from "${relSpecifier("compat/globals.ts", target)}";`);
}
compat.push("");
compat.push("/* 直接写 window.X = X,便于正则核对与调试(Window 已加索引签名,见 types/api.d.ts) */");
compat.push("");
for (const n of fnNames) compat.push(`window.${n} = ${n};`);
compat.push("");
compat.push("/* 原 static/js/src/core/geo.js 也把这三个挂在 window 上,这里挂同一份实现。 */");
compat.push("window.Geo = Geo;");
compat.push("window.offsetCoord = offsetCoord;");
compat.push("window.calcDistance = calcDistance;");
compat.push("");
fileOut.set("compat/globals.ts", compat.join("\n") + "\n");
/* ---------------- 9.5 类型补丁(逐条登记,重跑生成会重新套用) ----------------
* 这些是「原文是原生 JS、在 TS 下需要显式类型」的最小改动,全部只影响类型:
* 没有一条改动运行时行为(String(n) / 类型标注 / 可选参数 / as any)。
*/
const TEXT_PATCHES = [
/* 通用:TS7 下 Object.values(any) 与 new Promise(...) 会推成 unknown[] / unknown */
{ mod: "*", find: /Object\.values\(/g, replace: "Object.values<any>(" },
{ mod: "*", find: /Object\.entries\(/g, replace: "Object.entries<any>(" },
{ mod: "*", find: /new Promise\(/g, replace: "new Promise<any>(" },
/* core/http.ts:opts 上要挂 body,shareApi 后两个参数可选(原实现就是这样调用的) */
{ mod: "core/http.ts", find: 'export function shareApi(url, method, body) {', replace: 'export function shareApi(url: string, method?: string, body?: any) {' },
{ mod: "core/http.ts", find: 'const opts = { method: method || "GET", headers: {} };', replace: 'const opts: any = { method: method || "GET", headers: {} };' },
/* card/bike-card.ts:SVG 属性与 textContent 只吃字符串 */
{ mod: "card/bike-card.ts", find: 'fill.setAttribute("width", w);', replace: 'fill.setAttribute("width", String(w));' },
{ mod: "card/bike-card.ts", find: 'document.getElementById("card-electric").textContent = Math.round(electric);', replace: 'document.getElementById("card-electric").textContent = String(Math.round(electric));' },
/* map/markers.ts:状态计数写进 textContent */
{ mod: "map/markers.ts", find: '.textContent = availableCount;', replace: '.textContent = String(availableCount);' },
{ mod: "map/markers.ts", find: '.textContent = usedCount;', replace: '.textContent = String(usedCount);' },
{ mod: "map/markers.ts", find: '.textContent = lockedCount;', replace: '.textContent = String(lockedCount);' },
{ mod: "map/markers.ts", find: '.textContent = reservedCount;', replace: '.textContent = String(reservedCount);' },
{ mod: "map/markers.ts", find: '.textContent = lowCount;', replace: '.textContent = String(lowCount);' },
/* order/actions.ts:同上(响铃筛选面板的计数) */
{ mod: "order/actions.ts", find: ".textContent = counts.available;", replace: ".textContent = String(counts.available);" },
{ mod: "order/actions.ts", find: ".textContent = counts.used;", replace: ".textContent = String(counts.used);" },
{ mod: "order/actions.ts", find: ".textContent = counts.locked;", replace: ".textContent = String(counts.locked);" },
{ mod: "order/actions.ts", find: ".textContent = counts.low;", replace: ".textContent = String(counts.low);" },
{ mod: "order/actions.ts", find: ".textContent = counts.reserved;", replace: ".textContent = String(counts.reserved);" },
/* 同一个对象后面才补字段,字面量类型收不住 */
{ mod: "order/actions.ts", find: 'const payload = {\n code: unlockPendingCode,', replace: 'const payload: any = {\n code: unlockPendingCode,' },
/* nav/navigation.ts */
{ mod: "nav/navigation.ts", find: 'const D = window.DeviceOrientationEvent;', replace: 'const D: any = (window as any).DeviceOrientationEvent;' },
{ mod: "nav/navigation.ts", find: 'const err = new Error(msg);', replace: 'const err: any = new Error(msg);' },
];
const patchWarnings = [];
for (const [mod, src] of fileOut) {
let out = src;
for (const p of TEXT_PATCHES) {
if (p.mod !== "*" && p.mod !== mod) continue;
if (typeof p.find === "string") {
if (!out.includes(p.find)) { patchWarnings.push(`${mod}: 未命中 -> ${p.find.split("\n")[0].slice(0, 60)}`); continue; }
out = out.split(p.find).join(p.replace);
} else {
out = out.replace(p.find, p.replace);
}
}
fileOut.set(mod, out);
}
/* ---------------- 10. 落盘 ---------------- */
const written = [];
for (const [mod, src] of fileOut) {
const target = path.join(SRC_TS, mod);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, src, "utf8");
written.push({ mod, lines: src.split("\n").length });
}
const stateTarget = path.join(SRC_TS, "core/state.ts");
fs.mkdirSync(path.dirname(stateTarget), { recursive: true });
fs.writeFileSync(stateTarget, stateSrc, "utf8");
written.push({ mod: "core/state.ts", lines: stateSrc.split("\n").length });
/* 生成物语法自检:改写后的每一块都必须是合法 JS(块里没有 TS 语法,
* 所以可以直接用 vm 解析)。专门用来抓「改写把语法搞坏」——
* 例如对象简写属性 `{ map }` 被写成 `{ S.map }`。 */
const broken = [];
for (const b of blocks) {
const code = rewritten.get(b);
try {
new vm.Script(code, { filename: `${b.file}:${b.from}` });
} catch (e) {
broken.push(`${b.file}:${b.from}-${b.to} ${e.message}`);
}
}
console.log("生成结果:");
for (const w of written.sort((a, b) => a.mod.localeCompare(b.mod))) {
console.log(` src-ts/${w.mod.padEnd(24)} ${String(w.lines).padStart(5)} 行`);
}
console.log(`\nbootstrap 顶层语句 ${stmts.length} 条;S.xxx 改写 ${renameReport.reduce((a, b) => a + b, 0)} 处`);
if (skippedKeys.length) console.log(`对象键跳过 ${skippedKeys.length} 处: ${skippedKeys.slice(0, 20).join(" ")}`);
/* 保真度统计:把生成结果「反归一化」回原文写法后逐行比对 */
const norm = (s) =>
s
.split("\n")
.map((l) => l.replace(/^export\s+/, ""))
.join("\n")
.replace(/\bS\./g, "")
.replace(/\b(let\s+[A-Za-z_$][\w$]*)\s*:\s*any\b/g, "$1")
.replace(/\bString\(([^()]*)\)/g, "$1")
.replace(/<any>/g, "");
let origLines = 0, genLines = 0, diffLines = 0;
const diffSamples = [];
for (const b of blocks) {
const ol = norm(b.body).split("\n");
const gl = norm(rewritten.get(b)).split("\n");
origLines += ol.length;
genLines += gl.length;
const n = Math.max(ol.length, gl.length);
for (let i = 0; i < n; i++) {
if ((ol[i] || "") !== (gl[i] || "")) {
diffLines++;
if (diffSamples.length < 8) diffSamples.push(`${b.file}:${b.from} ${String(gl[i] || ol[i] || "").trim().slice(0, 76)}`);
}
}
}
console.log(`保真度:${blocks.length} 块 / 原文 ${origLines} 行 → 生成 ${genLines} 行;归一化后差异行 ${diffLines}`);
diffSamples.forEach((d) => console.log(" " + d));
const fw = [...nameSet].filter((n) => foreignWriters(n).length);
if (fw.length) console.log(`\n仍有跨模块赋值的变量(tsc 会报错,需手动换 setter):\n ${fw.join(", ")}`);
if (broken.length) {
console.log("\n生成物语法自检失败:");
for (const b of broken) console.log(" " + b);
process.exitCode = 1;
} else {
console.log("生成物语法自检 ✓(去掉 import/export 后逐文件可解析)");
}
if (patchWarnings.length) {
console.log("\n类型补丁未命中(说明原文变了,需要更新补丁表):");
for (const w of patchWarnings) console.log(" " + w);
} else {
console.log("类型补丁全部命中 ✓");
}
}
function extractInitializer(body, name) {
/* 用遮罩后的文本定位 `=` 与终止的 `;`,这样行尾注释不会混进初始值。 */
const masked = mask(body);
const eq = masked.indexOf("=");
const semi = masked.lastIndexOf(";");
if (eq < 0 || semi < eq) return `${name}: undefined`;
const init = body.slice(eq + 1, semi).trim();
if (!init) return `${name}: undefined`;
return `${name}: ${init}`;
}
/** 给顶层 `let NAME = ...` 补 `: any`(原实现这些变量是动态的)。 */
function annotateLetAny(text, name) {
const re = new RegExp(`^(let|var)\\s+${esc(name)}(\\s*)([:=])`);
const m = re.exec(text);
if (!m) return text;
if (m[3] === ":") return text; // 已有类型标注
return text.replace(re, `$1 ${name}: any$2$3`);
}
main();