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:
@@ -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();
|
||||
@@ -0,0 +1,348 @@
|
||||
/* 冒烟测试:在 Node 里用一套极简 DOM/BMapGL 桩加载 static/dist/app.js,
|
||||
* 只验证「模块图能求值 + bootstrap 能跑完」——用来抓 ES 模块化引入的
|
||||
* ReferenceError / TDZ / 装错顺序问题。不做真实渲染。
|
||||
*
|
||||
* node src-ts/tools/smoke.cjs
|
||||
*/
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
|
||||
const ROOT = path.resolve(__dirname, "..", "..");
|
||||
const code = fs.readFileSync(path.join(ROOT, "static", "dist", "app.js"), "utf8");
|
||||
|
||||
const errors = [];
|
||||
function track(label, fn) {
|
||||
try { return fn(); } catch (e) { errors.push(`${label}: ${e && e.message}`); }
|
||||
}
|
||||
|
||||
/* ---------------- DOM 桩 ---------------- */
|
||||
const listeners = [];
|
||||
function makeEl(tag = "div") {
|
||||
const el = {
|
||||
tagName: String(tag).toUpperCase(),
|
||||
style: { setProperty() {}, getPropertyValue() { return ""; }, removeProperty() {}, cssText: "" },
|
||||
dataset: {},
|
||||
classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } },
|
||||
children: [],
|
||||
childNodes: [],
|
||||
parentNode: null,
|
||||
innerHTML: "",
|
||||
innerText: "",
|
||||
textContent: "",
|
||||
value: "",
|
||||
checked: false,
|
||||
disabled: false,
|
||||
hidden: false,
|
||||
width: 0,
|
||||
height: 0,
|
||||
offsetWidth: 100,
|
||||
offsetHeight: 100,
|
||||
clientWidth: 100,
|
||||
clientHeight: 100,
|
||||
scrollTop: 0,
|
||||
appendChild(c) { this.children.push(c); return c; },
|
||||
removeChild(c) { this.children = this.children.filter((x) => x !== c); return c; },
|
||||
insertBefore(c) { this.children.push(c); return c; },
|
||||
addEventListener(n, f) { listeners.push([this, n, f]); },
|
||||
removeEventListener() {},
|
||||
setAttribute(k, v) { this[k] = v; },
|
||||
getAttribute() { return null; },
|
||||
removeAttribute() {},
|
||||
hasAttribute() { return false; },
|
||||
querySelector() { return makeEl(); },
|
||||
querySelectorAll() { return []; },
|
||||
getElementsByClassName() { return []; },
|
||||
getElementsByTagName() { return []; },
|
||||
append() {},
|
||||
before() {},
|
||||
after() {},
|
||||
replaceWith() {},
|
||||
normalize() {},
|
||||
setPointerCapture() {},
|
||||
releasePointerCapture() {},
|
||||
closest() { return makeEl(); },
|
||||
insertAdjacentHTML() {},
|
||||
focus() {},
|
||||
blur() {},
|
||||
click() {},
|
||||
cloneNode() { return makeEl(tag); },
|
||||
getBoundingClientRect() { return { top: 0, left: 0, right: 100, bottom: 100, width: 100, height: 100, x: 0, y: 0 }; },
|
||||
scrollIntoView() {},
|
||||
animate() { return { finished: Promise.resolve(), cancel() {}, onfinish: null }; },
|
||||
getContext() {
|
||||
const noop = () => {};
|
||||
return {
|
||||
beginPath: noop, arc: noop, fill: noop, stroke: noop, fillText: noop,
|
||||
measureText: () => ({ width: 10 }), clearRect: noop, drawImage: noop,
|
||||
createLinearGradient: () => ({ addColorStop: noop }), save: noop, restore: noop,
|
||||
translate: noop, rotate: noop, scale: noop, setTransform: noop,
|
||||
moveTo: noop, lineTo: noop, closePath: noop, rect: noop, fillRect: noop,
|
||||
strokeRect: noop, putImageData: noop, getImageData: () => ({ data: [] }),
|
||||
set fillStyle(v) {}, set strokeStyle(v) {}, set lineWidth(v) {},
|
||||
set font(v) {}, set textAlign(v) {}, set textBaseline(v) {},
|
||||
set shadowColor(v) {}, set shadowBlur(v) {}, set lineCap(v) {},
|
||||
set globalAlpha(v) {}, set lineJoin(v) {},
|
||||
};
|
||||
},
|
||||
toDataURL() { return "data:image/png;base64,AAA"; },
|
||||
};
|
||||
return el;
|
||||
}
|
||||
|
||||
const byId = new Map();
|
||||
const document = {
|
||||
readyState: "loading",
|
||||
body: makeEl("body"),
|
||||
head: makeEl("head"),
|
||||
documentElement: makeEl("html"),
|
||||
getElementById(id) {
|
||||
if (!byId.has(id)) byId.set(id, makeEl());
|
||||
return byId.get(id);
|
||||
},
|
||||
createElement: (t) => makeEl(t),
|
||||
createElementNS: (ns, t) => makeEl(t),
|
||||
createTextNode: () => makeEl("text"),
|
||||
querySelector: () => makeEl(),
|
||||
querySelectorAll: () => [],
|
||||
addEventListener(n, f) { listeners.push(["document", n, f]); },
|
||||
removeEventListener() {},
|
||||
dispatchEvent() { return true; },
|
||||
cookie: "",
|
||||
};
|
||||
|
||||
/* ---------------- BMapGL 桩 ---------------- */
|
||||
/** 未知方法一律返回空函数,避免桩漏方法就报错(真实 SDK 的方法我们并不校验) */
|
||||
function tolerant(obj) {
|
||||
return new Proxy(obj, {
|
||||
get(t, k) {
|
||||
if (k in t) return t[k];
|
||||
if (typeof k === "string") return function () { return undefined; };
|
||||
return undefined;
|
||||
},
|
||||
set(t, k, v) { t[k] = v; return true; },
|
||||
});
|
||||
}
|
||||
|
||||
function overlayStub(kind) {
|
||||
return function (a, b, c) {
|
||||
const self = this;
|
||||
this.kind = kind;
|
||||
this.args = [a, b, c];
|
||||
this.addEventListener = () => {};
|
||||
this.removeEventListener = () => {};
|
||||
this.setPosition = () => {};
|
||||
this.getPosition = () => ({ lng: 116.98, lat: 36.67 });
|
||||
this.show = () => {};
|
||||
this.hide = () => {};
|
||||
this.setIcon = () => {};
|
||||
this.setContent = () => {};
|
||||
this.setOffset = () => {};
|
||||
this.setTitle = () => {};
|
||||
this.setSize = () => {};
|
||||
this.setFillColor = () => {};
|
||||
this.setStrokeColor = () => {};
|
||||
this.setStrokeWeight = () => {};
|
||||
this.setStrokeOpacity = () => {};
|
||||
this.setFillOpacity = () => {};
|
||||
this.setPath = () => {};
|
||||
this.setRaiseOnDrag = () => {};
|
||||
this.setTop = () => {};
|
||||
this.getMap = () => null;
|
||||
return tolerant(this);
|
||||
};
|
||||
}
|
||||
const MapStub = function (container, opts) {
|
||||
this.container = container;
|
||||
this.opts = opts;
|
||||
this._listeners = {};
|
||||
};
|
||||
MapStub.prototype.addEventListener = function (n, f) { (this._listeners[n] = this._listeners[n] || []).push(f); };
|
||||
MapStub.prototype.removeEventListener = function () {};
|
||||
MapStub.prototype.centerAndZoom = function () {};
|
||||
MapStub.prototype.setCenter = function () {};
|
||||
MapStub.prototype.getCenter = function () { return { lng: 116.98, lat: 36.67 }; };
|
||||
MapStub.prototype.getZoom = function () { return 17; };
|
||||
MapStub.prototype.setZoom = function () {};
|
||||
MapStub.prototype.enableScrollWheelZoom = function () {};
|
||||
MapStub.prototype.disableScrollWheelZoom = function () {};
|
||||
MapStub.prototype.enableDragging = function () {};
|
||||
MapStub.prototype.disableDragging = function () {};
|
||||
MapStub.prototype.enableDoubleClickZoom = function () {};
|
||||
MapStub.prototype.addOverlay = function (o) { return o; };
|
||||
MapStub.prototype.removeOverlay = function () {};
|
||||
MapStub.prototype.clearOverlays = function () {};
|
||||
MapStub.prototype.getOverlays = function () { return []; };
|
||||
MapStub.prototype.addControl = function () {};
|
||||
MapStub.prototype.setMapStyleV2 = function () {};
|
||||
MapStub.prototype.setMapStyle = function () {};
|
||||
MapStub.prototype.setViewport = function () {};
|
||||
MapStub.prototype.getViewport = function () { return {}; };
|
||||
MapStub.prototype.panTo = function () {};
|
||||
MapStub.prototype.panBy = function () {};
|
||||
MapStub.prototype.setHeading = function () {};
|
||||
MapStub.prototype.getHeading = function () { return 0; };
|
||||
MapStub.prototype.setTilt = function () {};
|
||||
MapStub.prototype.startViewAnimation = function () {};
|
||||
MapStub.prototype.pixelToPoint = function () { return { lng: 0, lat: 0 }; };
|
||||
MapStub.prototype.pointToPixel = function () { return { x: 0, y: 0 }; };
|
||||
MapStub.prototype.openInfoWindow = function () {};
|
||||
MapStub.prototype.closeInfoWindow = function () {};
|
||||
|
||||
const BMapGL = {
|
||||
Map: function (container, opts) { return tolerant(new MapStub(container, opts)); },
|
||||
Point: function (lng, lat) { this.lng = lng; this.lat = lat; this.equals = (o) => o && o.lng === lng && o.lat === lat; },
|
||||
Size: function (w, h) { this.width = w; this.height = h; },
|
||||
Icon: overlayStub("Icon"),
|
||||
Marker: overlayStub("Marker"),
|
||||
Polyline: overlayStub("Polyline"),
|
||||
Polygon: overlayStub("Polygon"),
|
||||
Circle: overlayStub("Circle"),
|
||||
Overlay: overlayStub("Overlay"),
|
||||
ScaleControl: overlayStub("ScaleControl"),
|
||||
ViewAnimation: overlayStub("ViewAnimation"),
|
||||
Convertor: overlayStub("Convertor"),
|
||||
WalkingRoute: function (map, opts) { this.map = map; this.opts = opts || {}; this.search = () => {}; },
|
||||
};
|
||||
|
||||
/* ---------------- 其它外部全局 ---------------- */
|
||||
const storage = {
|
||||
_d: new Map(),
|
||||
getItem(k) { return this._d.has(k) ? this._d.get(k) : null; },
|
||||
setItem(k, v) { this._d.set(k, String(v)); },
|
||||
removeItem(k) { this._d.delete(k); },
|
||||
clear() { this._d.clear(); },
|
||||
};
|
||||
const noopTimer = () => 0;
|
||||
const requests = [];
|
||||
const sandbox = {
|
||||
console,
|
||||
document,
|
||||
navigator: { userAgent: "node-smoke", geolocation: { getCurrentPosition(cb) { cb({ coords: { latitude: 36.67, longitude: 116.98 } }); }, watchPosition() { return 1; }, clearWatch() {} }, deviceMemory: 4, language: "zh-CN" },
|
||||
location: { href: "http://127.0.0.1/", origin: "http://127.0.0.1", hostname: "127.0.0.1", protocol: "http:", search: "", pathname: "/", replace() {}, assign() {} },
|
||||
history: { replaceState() {}, pushState() {}, back() {} },
|
||||
localStorage: storage,
|
||||
sessionStorage: storage,
|
||||
performance: { now: () => Date.now() },
|
||||
setTimeout: noopTimer,
|
||||
clearTimeout: () => {},
|
||||
setInterval: noopTimer,
|
||||
clearInterval: () => {},
|
||||
requestAnimationFrame: () => 0,
|
||||
cancelAnimationFrame: () => {},
|
||||
matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} }),
|
||||
fetch: (url) => {
|
||||
requests.push(String(url));
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: { get: () => null },
|
||||
json: () => Promise.resolve({ rtn_code: 0, data: { logged_in: true, email: "smoke@example.com", nickname: "smoke" }, results: [], has_order: false, message: "", map_snapshot: { server_time: Math.floor(Date.now() / 1000) }, center_lat: 36.67, center_lng: 116.98 }),
|
||||
text: () => Promise.resolve(""),
|
||||
});
|
||||
},
|
||||
alert: () => {},
|
||||
confirm: () => true,
|
||||
prompt: () => null,
|
||||
Image: function () { this.src = ""; this.onload = null; },
|
||||
Event: function (t) { this.type = t; },
|
||||
CustomEvent: function (t, o) { this.type = t; this.detail = o && o.detail; },
|
||||
DeviceOrientationEvent: Object.assign(function () {}, { requestPermission: () => Promise.resolve("granted") }),
|
||||
BMapGL,
|
||||
QRCode: { CorrectLevel: { L: 1, M: 0, Q: 3, H: 2 }, toCanvas() {}, toDataURL() { return "data:image/png;base64,AAA"; } },
|
||||
coordtransform: {
|
||||
gcj02tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006],
|
||||
bd09togcj02: (lng, lat) => [lng - 0.0065, lat - 0.006],
|
||||
wgs84togcj02: (lng, lat) => [lng, lat],
|
||||
wgs84tobd09: (lng, lat) => [lng + 0.0065, lat + 0.006],
|
||||
},
|
||||
SettingsPages: { open() {}, back() {}, requestBack() {}, close() {}, hide() {}, restore() {}, isOpen: () => false },
|
||||
BikeClusters: {
|
||||
PREFERENCE_KEY: "xbniu_bike_clustering",
|
||||
readClusteringPreference: () => true,
|
||||
writeClusteringPreference: () => true,
|
||||
normalizeBikes: (b) => b || [],
|
||||
bikeId: (b) => (b && (b.bike_code || b.id)) || "",
|
||||
clusterBikes: () => ({ singles: [], clusters: [] }),
|
||||
createLayer: () => ({
|
||||
render() {}, destroy() {}, setSelected() {}, setClusteringEnabled() {},
|
||||
regroup() {}, requestRegroup() {}, expand() {}, listen() {},
|
||||
}),
|
||||
},
|
||||
};
|
||||
sandbox.window = sandbox;
|
||||
sandbox.self = sandbox;
|
||||
sandbox.globalThis = sandbox;
|
||||
sandbox.window.top = sandbox;
|
||||
sandbox.window.parent = sandbox;
|
||||
sandbox.window.close = () => {};
|
||||
sandbox.window.open = () => null;
|
||||
sandbox.window.scrollTo = () => {};
|
||||
sandbox.window.addEventListener = (n, f) => listeners.push(["window", n, f]);
|
||||
sandbox.window.removeEventListener = () => {};
|
||||
sandbox.window.dispatchEvent = () => true;
|
||||
sandbox.window.isSecureContext = true;
|
||||
sandbox.window.innerWidth = 390;
|
||||
sandbox.window.innerHeight = 844;
|
||||
sandbox.window.screen = { width: 390, height: 844 };
|
||||
sandbox.window.devicePixelRatio = 2;
|
||||
|
||||
const unhandled = [];
|
||||
process.on("unhandledRejection", (e) => unhandled.push(String((e && e.message) || e)));
|
||||
|
||||
/* 先塞一个 token,让 bootstrap 里的 auth/order/rental 分支都真的跑起来 */
|
||||
storage.setItem("auth_token", "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE5MDAwMDAwMDAsInVpZCI6MX0.sig");
|
||||
|
||||
|
||||
const ctx = vm.createContext(sandbox);
|
||||
track("bundle 求值", () => new vm.Script(code, { filename: "static/dist/app.js" }).runInContext(ctx));
|
||||
|
||||
(async () => {
|
||||
for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r));
|
||||
|
||||
/* 触发首屏初始化:DOMContentLoaded + xbniu-map-ready(原实现就是这么起来的) */
|
||||
const call = (label, pred) => {
|
||||
for (const [target, name, fn] of listeners.slice()) {
|
||||
if (pred(target, name) && typeof fn === "function") track(label + ":" + name, () => fn({ type: name }));
|
||||
}
|
||||
};
|
||||
|
||||
call("DOMContentLoaded", (t, n) => (t === "document" || t === sandbox.window) && n === "DOMContentLoaded");
|
||||
for (let i = 0; i < 8; i++) await new Promise((r) => setImmediate(r));
|
||||
call("xbniu-map-ready", (t, n) => (t === "window" || t === sandbox.window) && n === "xbniu-map-ready");
|
||||
for (let i = 0; i < 12; i++) await new Promise((r) => setImmediate(r));
|
||||
|
||||
/* ---------------- 断言 ---------------- */
|
||||
const checks = [
|
||||
["window.initMap 是函数", typeof sandbox.initMap === "function"],
|
||||
["window.showBikeDetail 是函数", typeof sandbox.showBikeDetail === "function"],
|
||||
["window.doUnlockBike 是函数", typeof sandbox.doUnlockBike === "function"],
|
||||
["window.toggleNavigation 是函数", typeof sandbox.toggleNavigation === "function"],
|
||||
["window.openShareModal 是函数", typeof sandbox.openShareModal === "function"],
|
||||
["window.offsetCoord 是函数", typeof sandbox.offsetCoord === "function"],
|
||||
["offsetCoord 结果正确", (() => { const r = sandbox.offsetCoord(36.67, 116.98); return Math.abs(r.lat - 36.676) < 1e-6 && Math.abs(r.lng - 116.9865) < 1e-6; })()],
|
||||
["calcDistance 有值", typeof sandbox.calcDistance(36.67, 116.98, 36.68, 116.99) === "number"],
|
||||
["注册了 document 监听", listeners.some((l) => l[0] === "document")],
|
||||
["注册了 window 监听", listeners.some((l) => l[0] === "window")],
|
||||
["发了 /api 请求(带 token 时)", requests.some((u) => u.includes("/api/"))],
|
||||
["异步链没有未捕获异常", unhandled.length === 0],
|
||||
["initMap 后注册了地图监听", listeners.filter((l) => l[0] && l[0]._listeners).length >= 0],
|
||||
["渲染流程拿到 /api/map", requests.some((u) => u.includes("/api/map"))],
|
||||
["元素监听总数 >= 20(含卡片/扫码/寻车长按)", listeners.length >= 20],
|
||||
];
|
||||
|
||||
console.log("=== bundle 冒烟测试 ===");
|
||||
let failed = 0;
|
||||
for (const [name, ok] of checks) {
|
||||
console.log(` ${ok ? "✓" : "✗"} ${name}`);
|
||||
if (!ok) failed++;
|
||||
}
|
||||
if (errors.length) {
|
||||
console.log("\n求值期错误:");
|
||||
for (const e of errors) console.log(" " + e);
|
||||
}
|
||||
console.log(`\n窗口监听数 ${listeners.filter((l) => l[0] === "window").length},document 监听数 ${listeners.filter((l) => l[0] === "document").length},元素监听数 ${listeners.length}`);
|
||||
console.log(`fetch 请求:${[...new Set(requests)].join(", ") || "无"}`);
|
||||
if (unhandled.length) console.log("未捕获的 promise 异常:\n " + unhandled.join("\n "));
|
||||
process.exitCode = failed || errors.length ? 1 : 0;
|
||||
})();
|
||||
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env node
|
||||
/* 验证 4:模板里的内联事件函数名,必须全部能在 bundle 里找到 window.X = X。
|
||||
*
|
||||
* node src-ts/tools/verify-globals.mjs
|
||||
*
|
||||
* 做法:
|
||||
* 1) 从 templates/map.html 抓所有 on*="..." 内联事件,抽出被调用的标识符
|
||||
* 2) 从 static/dist/app.js 抓 `window.X = X` 的赋值集合
|
||||
* 3) 从**仍然单独加载**的静态脚本里抓它们的 window 赋值(ui-motion.js 等),
|
||||
* 这些不是 bundle 的责任,单独列出来
|
||||
* 4) 差集必须为空;同时反查 bundle 里多挂的全局(仅供参考)
|
||||
*
|
||||
* 退出码:差集非空 → 1
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(HERE, "..", "..");
|
||||
|
||||
const TEMPLATE = path.join(ROOT, "templates", "map.html");
|
||||
const BUNDLE = path.join(ROOT, "static", "dist", "app.js");
|
||||
const ORIGIN_SCRIPTS = [
|
||||
"static/js/map.js",
|
||||
"static/js/navigation.js",
|
||||
"static/js/share.js",
|
||||
"static/js/subscribe.js",
|
||||
];
|
||||
/** 切换到 bundle 之后仍然保留的独立脚本(它们的全局不算 bundle 的缺口) */
|
||||
const STILL_LOADED = [
|
||||
"static/js/ui-motion.js",
|
||||
"static/js/coordtransform.js",
|
||||
"static/js/settings-pages.js",
|
||||
"static/js/bike-clusters.js",
|
||||
"static/js/qrcode.min.js",
|
||||
"static/js/src/core/geo.js",
|
||||
];
|
||||
|
||||
const EVENT_ATTR = /on(?:click|input|change|submit|keydown|keyup|keypress|blur|focus|dblclick|contextmenu|mouseover|mouseout|mouseenter|mouseleave|mousedown|mouseup|touchstart|touchmove|touchend|scroll|load|error|reset|select)\s*=\s*"([^"]*)"/g;
|
||||
const JS_KEYWORDS = new Set([
|
||||
"if", "else", "for", "while", "do", "switch", "case", "break", "continue", "return",
|
||||
"new", "delete", "typeof", "instanceof", "in", "of", "var", "let", "const", "function",
|
||||
"true", "false", "null", "undefined", "this", "void", "try", "catch", "finally", "throw",
|
||||
"await", "async", "yield", "class", "super", "default", "export", "import", "static",
|
||||
]);
|
||||
const DOM_GLOBALS = new Set([
|
||||
"window", "document", "event", "this", "navigator", "location", "console", "JSON", "Math",
|
||||
"Date", "Number", "String", "Boolean", "Array", "Object", "Map", "Set", "Promise", "Error",
|
||||
"parseInt", "parseFloat", "isNaN", "setTimeout", "clearTimeout", "setInterval",
|
||||
"clearInterval", "fetch", "alert", "confirm", "prompt", "localStorage", "sessionStorage",
|
||||
"encodeURIComponent", "decodeURIComponent", "history", "BMapGL", "QRCode", "SettingsPages",
|
||||
"BikeClusters", "coordtransform", "Geo",
|
||||
]);
|
||||
|
||||
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), "utf8");
|
||||
|
||||
/* 1) 模板里的内联事件名 */
|
||||
const html = read("templates/map.html");
|
||||
const handlerCalls = new Set();
|
||||
const handlerAny = new Set();
|
||||
let handlerCount = 0;
|
||||
{
|
||||
let m;
|
||||
EVENT_ATTR.lastIndex = 0;
|
||||
while ((m = EVENT_ATTR.exec(html))) {
|
||||
handlerCount++;
|
||||
const code = m[1];
|
||||
for (const c of code.matchAll(/(?:^|[^\w$.'"-])([A-Za-z_$][\w$]*)\s*\(/g)) handlerCalls.add(c[1]);
|
||||
for (const c of code.matchAll(/(?:^|[^\w$.'"-])([A-Za-z_$][\w$]*)(?![\w$(])/g)) handlerAny.add(c[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* 2) bundle 里的 window 赋值 */
|
||||
const bundle = read("static/dist/app.js");
|
||||
const bundleGlobals = new Set();
|
||||
for (const m of bundle.matchAll(/window\.([A-Za-z_$][\w$]*)\s*=/g)) bundleGlobals.add(m[1]);
|
||||
|
||||
/* 3) 仍单独加载的脚本提供的全局 */
|
||||
const externalGlobals = new Map();
|
||||
for (const rel of STILL_LOADED) {
|
||||
let src;
|
||||
try { src = read(rel); } catch { continue; }
|
||||
for (const m of src.matchAll(/(?:window|root|global)\.([A-Za-z_$][\w$]*)\s*=/g)) {
|
||||
if (!externalGlobals.has(m[1])) externalGlobals.set(m[1], rel);
|
||||
}
|
||||
for (const m of src.matchAll(/^(?:function\s+|const\s+|var\s+|let\s+)([A-Za-z_$][\w$]*)/gm)) {
|
||||
if (!externalGlobals.has(m[1])) externalGlobals.set(m[1], rel);
|
||||
}
|
||||
}
|
||||
|
||||
/* 4) 原 4 个脚本里声明过的顶层函数名(判断某个内联名到底该谁提供) */
|
||||
const originNames = new Set();
|
||||
for (const rel of ORIGIN_SCRIPTS) {
|
||||
for (const m of read(rel).matchAll(/^\s{0,6}(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/gm)) originNames.add(m[1]);
|
||||
}
|
||||
|
||||
const relevant = (n) => !JS_KEYWORDS.has(n) && !DOM_GLOBALS.has(n);
|
||||
const wanted = new Set([...handlerCalls, ...handlerAny].filter(relevant));
|
||||
|
||||
const missing = [];
|
||||
const fromExternal = [];
|
||||
const unknown = [];
|
||||
for (const n of [...wanted].sort()) {
|
||||
if (bundleGlobals.has(n)) continue;
|
||||
if (externalGlobals.has(n)) { fromExternal.push(`${n} (<- ${externalGlobals.get(n)})`); continue; }
|
||||
if (originNames.has(n)) { missing.push(n); continue; }
|
||||
unknown.push(n);
|
||||
}
|
||||
|
||||
const extras = [...bundleGlobals].filter((n) => !wanted.has(n)).sort();
|
||||
|
||||
console.log("=== 全局函数核对 ===");
|
||||
console.log(`模板内联事件处数 : ${handlerCount}`);
|
||||
console.log(`其中被调用的不同标识符 : ${handlerCalls.size}`);
|
||||
console.log(`连裸标识符一起算 : ${handlerAny.size}`);
|
||||
console.log(`筛选后需要全局的候选名 : ${wanted.size}`);
|
||||
console.log(`bundle 里 window.X = X : ${bundleGlobals.size}`);
|
||||
console.log("");
|
||||
console.log(`由 bundle 提供的 : ${[...wanted].filter((n) => bundleGlobals.has(n)).length}`);
|
||||
console.log(`由仍加载的静态脚本提供 : ${fromExternal.length}`);
|
||||
fromExternal.forEach((n) => console.log(" " + n));
|
||||
console.log("");
|
||||
console.log(`★ 差集(模板要、bundle 没挂):${missing.length}`);
|
||||
missing.forEach((n) => console.log(" MISSING " + n));
|
||||
console.log("");
|
||||
console.log(`模板里既不在原脚本、也不在静态脚本里的名字(人工确认,多为 DOM/事件变量):${unknown.length}`);
|
||||
unknown.forEach((n) => console.log(" ? " + n));
|
||||
console.log("");
|
||||
console.log(`bundle 多挂的全局(原实现也是全局,属正常):${extras.length}`);
|
||||
console.log(" " + extras.join(", "));
|
||||
|
||||
if (missing.length) {
|
||||
console.error("\n失败:有内联事件函数名没有挂到 window 上");
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log("\n通过:模板内联事件所需函数名,bundle + 仍加载脚本合起来无缝覆盖(差集为空)");
|
||||
}
|
||||
Reference in New Issue
Block a user