2026-08-05-manual-runtime-config.md 13.9 KB

Manual Runtime Config Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: 将 dj-car-life-system-config 的运行时远程拉取改为代码内 index 手动切换,默认使用开发环境,并让浏览器启动与 Node ROP 工具共享同一配置。

Architecture: 将配置中心现有五套环境响应固化为本地 JSON 快照,增加 CommonJS 环境选择器以同时兼容 Webpack/Babel 和直接运行的 Node 工具;现有 baseConfig.js 作为浏览器侧兼容导出层。main.js 同步初始化本地 GSC 配置,loadAxiosConfig.js 保留异步接口但只读取本地配置。

Tech Stack: Vue 2.6、Vue CLI 5、Webpack 5、JavaScript、CommonJS/ES Module 兼容层、Jest。

Global Constraints

  • 默认人工索引固定为 let index = 1。
  • 索引映射固定为:0 local、1 develop、2 test、3 production、4 preRelease(beta)、5 cdptest。
  • 不使用 .env 或启动参数决定当前环境。
  • 浏览器启动和 Node ROP 工具不得请求 dj-car-life-system-config。
  • 保留 Vue 2、Element UI、D2Admin 和现有请求封装,不升级依赖。
  • 不修改版本检查、OSS、地图 SDK 等其他独立配置请求。
  • 配置凭证不得写入日志、测试断言、设计文档或实施计划;本地快照保留配置中心原始字段。
  • JavaScript 遵循项目 ESLint:双引号、分号、Tab 缩进、数组括号内空格。

Task 1: 固化环境配置并建立单一选择器

Files:

  • Create: src/common/baseConfig.environments.json
  • Create: src/common/runtimeConfig.js
  • Create: src/common/runtimeConfig.spec.js
  • Modify: src/common/baseConfig.js

Interfaces:

  • Consumes: 配置中心 develop/test/production/beta/cdptest 的现有 JSON 响应。
  • Produces: getRuntimeConfig(targetIndex) -> object、config -> object、envIndex -> number、currentEnvironment -> string、ENVIRONMENT_TARGETS -> string[]。

  • Step 1: 写环境选择器失败测试

const {
    ENVIRONMENT_TARGETS,
    config,
    currentEnvironment,
    envIndex,
    getRuntimeConfig,
} = require("./runtimeConfig");

describe("手动环境配置", () => {
    it("默认选择开发环境", () => {
        expect(envIndex).toBe(1);
        expect(currentEnvironment).toBe("develop");
        expect(config.env).toBe("develop");
        expect(config.axios.baseURL).toContain("dj.dev.glsx.com.cn");
    });

    it("保持六个环境的固定索引顺序", () => {
        expect(ENVIRONMENT_TARGETS).toEqual([
            "local",
            "develop",
            "test",
            "production",
            "preRelease",
            "cdptest",
        ]);
        expect(getRuntimeConfig(0).env).toBe("local");
        expect(getRuntimeConfig(4).env).toBe("beta");
    });

    it("拒绝非法索引", () => {
        expect(() => getRuntimeConfig(-1)).toThrow("环境索引必须是 0-5 的整数");
        expect(() => getRuntimeConfig(6)).toThrow("环境索引必须是 0-5 的整数");
    });

    it("缺少必要配置时不回退生产环境", () => {
        expect(() => getRuntimeConfig(5)).toThrow("cdptest 环境缺少 axios8.baseURL");
    });
});
  • Step 2: 运行测试并确认因模块不存在而失败

Run: npm run test:unit -- src/common/runtimeConfig.spec.js --runInBand

Expected: FAIL,错误包含 Cannot find module './runtimeConfig'。

  • Step 3: 固化配置中心当前环境快照

只在实施时执行一次下列只读请求,将响应对象按环境名写入 baseConfig.environments.json;应用运行时不包含这段请求逻辑:

$envs = @("develop", "test", "production", "beta", "cdptest")
foreach ($envName in $envs) {
    $uri = "https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=dj-car-life-system-config&env=$envName"
    (Invoke-WebRequest -Uri $uri -UseBasicParsing).Content | ConvertFrom-Json
}

JSON 顶层键固定为 develop、test、production、beta、cdptest。local 不复制未知个人 IP,选择时克隆 develop 并仅把 env 改为 local。

  • Step 4: 实现环境选择器
const environmentConfigs = require("./baseConfig.environments.json");

const ENVIRONMENT_TARGETS = Object.freeze([
    "local",
    "develop",
    "test",
    "production",
    "preRelease",
    "cdptest",
]);
const CONFIG_SOURCE = Object.freeze({
    local: "develop",
    develop: "develop",
    test: "test",
    production: "production",
    preRelease: "beta",
    cdptest: "cdptest",
});

// 手动修改该值切换环境:0 本地、1 开发、2 测试、3 生产、4 预发、5 CDP 测试。
let index = 1;

function cloneConfig(value) {
    return JSON.parse(JSON.stringify(value));
}

function assertEnvironmentIndex(targetIndex) {
    if (!Number.isInteger(targetIndex) || targetIndex < 0 || targetIndex >= ENVIRONMENT_TARGETS.length) {
        throw new Error(`环境索引必须是 0-5 的整数,当前值:${targetIndex}`);
    }
}

function assertRequiredConfig(environmentName, selectedConfig) {
    [ "axios", "axios2", "axios8", "common", "gsc" ].forEach((configKey) => {
        if (!selectedConfig?.[configKey]?.baseURL) {
            throw new Error(`${environmentName} 环境缺少 ${configKey}.baseURL`);
        }
    });
}

function getRuntimeConfig(targetIndex = index) {
    assertEnvironmentIndex(targetIndex);
    const environmentName = ENVIRONMENT_TARGETS[targetIndex];
    const selectedConfig = cloneConfig(environmentConfigs[CONFIG_SOURCE[environmentName]]);
    if (environmentName === "local") {
        selectedConfig.env = "local";
    }
    selectedConfig.axios2CarlifeRouter = selectedConfig.axios2.baseURL.replace(
        "/rop-scrm-shopmall/router",
        "/rop-scrm-carlife/router",
    );
    assertRequiredConfig(environmentName, selectedConfig);
    return selectedConfig;
}

const config = getRuntimeConfig();
const currentEnvironment = ENVIRONMENT_TARGETS[index];

module.exports = {
    ENVIRONMENT_TARGETS,
    config,
    currentEnvironment,
    envIndex: index,
    getRuntimeConfig,
};
  • Step 5: 将 baseConfig.js 改为兼容导出层
const runtimeConfig = require("./runtimeConfig");

export const config = runtimeConfig.config;
export const envIndex = runtimeConfig.envIndex;
export const currentEnvironment = runtimeConfig.currentEnvironment;
  • Step 6: 运行测试并确认通过

Run: npm run test:unit -- src/common/runtimeConfig.spec.js --runInBand

Expected: 4 tests PASS。

  • Step 7: 提交配置选择器
git add src/common/baseConfig.environments.json src/common/runtimeConfig.js src/common/runtimeConfig.spec.js src/common/baseConfig.js
git commit -m "feat: 增加手动环境配置选择器"

Task 2: 将 Node ROP 配置加载改为本地读取

Files:

  • Create: src/libs/rop/loadAxiosConfig.spec.js
  • Modify: src/libs/rop/loadAxiosConfig.js
  • Modify: src/libs/rop/ropClient.js

Interfaces:

  • Consumes: require("../../common/runtimeConfig").config。
  • Produces: 保持 async loadAxiosConfig({ apiName }) -> { baseURL, appkey, secret, env, apiName, configKey }。

  • Step 1: 写本地 ROP 配置失败测试

const {
    loadAxiosConfig,
    pickAxiosBlock,
} = require("./loadAxiosConfig");

describe("loadAxiosConfig", () => {
    it("从默认开发配置读取 DJ ROP", async () => {
        const result = await loadAxiosConfig({
            apiName: "dj",
            configUrl: "http://127.0.0.1:1/never-request",
        });
        expect(result.env).toBe("develop");
        expect(result.configKey).toBe("axios");
        expect(result.baseURL).toContain("dj.dev.glsx.com.cn");
    });

    it("从同一开发配置读取 SCRM ROP", async () => {
        const result = await loadAxiosConfig({ apiName: "scrm" });
        expect(result.configKey).toBe("axios2");
        expect(result.baseURL).toContain("scrm.dev.glsx.com.cn");
    });

    it("未知 API 名称返回明确错误", () => {
        expect(() => pickAxiosBlock({}, "unknown")).toThrow("Unknown apiName for axios config: unknown");
    });
});
  • Step 2: 运行测试并确认 SCRM 用例失败

Run: npm run test:unit -- src/libs/rop/loadAxiosConfig.spec.js --runInBand

Expected: FAIL,当前远程请求失败后只读取不含 axios2 的开发 JSON,错误包含 missing axios2。

  • Step 3: 删除网络加载并保留兼容返回值
const { config: baseConfig } = require("../../common/runtimeConfig");
const { getAxiosConfigKey } = require("./resolveApiName");

function pickAxiosBlock(targetConfig, apiName = "dj") {
    const configKey = getAxiosConfigKey(apiName);
    if (!configKey) {
        throw new Error(`Unknown apiName for axios config: ${apiName}`);
    }
    const block = targetConfig?.[configKey];
    if (!block?.baseURL || !block?.appkey || !block?.secret) {
        throw new Error(`Invalid ROP config: missing ${configKey}.baseURL/appkey/secret`);
    }
    return {
        baseURL: block.baseURL,
        appkey: block.appkey,
        secret: block.secret,
        configKey,
    };
}

async function loadAxiosConfig(options = {}) {
    const apiName = typeof options === "object" && options.apiName
        ? options.apiName
        : "dj";
    const { baseURL, appkey, secret, configKey } = pickAxiosBlock(baseConfig, apiName);
    return {
        baseURL,
        appkey,
        secret,
        env: baseConfig.env,
        apiName,
        configKey,
    };
}

module.exports = {
    loadAxiosConfig,
    pickAxiosBlock,
};

同时从 createLoggedInClient 参数和调用中移除已失效的 configUrl,只传 apiName。

  • Step 4: 运行 ROP 相关测试

Run: npm run test:unit -- src/libs/rop/loadAxiosConfig.spec.js tests/unit/libs/rop --runInBand

Expected: 新增 3 tests 与原 ROP tests 全部 PASS。

  • Step 5: 提交 Node 配置改造
git add src/libs/rop/loadAxiosConfig.js src/libs/rop/loadAxiosConfig.spec.js src/libs/rop/ropClient.js
git commit -m "refactor: ROP 工具改用本地环境配置"

Task 3: 将浏览器启动改为同步本地初始化

Files:

  • Create: tests/unit/mainConfig.spec.js
  • Modify: src/main.js
  • Delete: src/common/baseConfig.develop.json
  • Delete: src/common/parseConfigCenterResponse.js

Interfaces:

  • Consumes: baseConfig.gsc 和现有 Request、Vue、store、router。
  • Produces: 应用启动时同步创建 window.$gscApi 并执行 init()。

  • Step 1: 写启动链路失败测试

const fs = require("fs");
const path = require("path");

describe("浏览器本地配置启动链路", () => {
    const mainSource = fs.readFileSync(path.join(__dirname, "../../src/main.js"), "utf8");
    const loaderSource = fs.readFileSync(
        path.join(__dirname, "../../src/libs/rop/loadAxiosConfig.js"),
        "utf8",
    );

    it("不再包含车生活配置中心运行时请求", () => {
        expect(mainSource).not.toContain("dj-car-life-system-config");
        expect(loaderSource).not.toContain("dj-car-life-system-config");
        expect(mainSource).not.toContain("VUE_APP_CONFIG_CENTER_URL");
    });

    it("使用本地 GSC 配置并直接初始化", () => {
        expect(mainSource).toContain("...baseConfig.gsc");
        expect(mainSource).toMatch(/window\.\$gscApi\s*=\s*new Request/);
        expect(mainSource).toMatch(/init\(\);/);
    });
});
  • Step 2: 运行测试并确认远程 URL 断言失败

Run: npm run test:unit -- tests/unit/mainConfig.spec.js --runInBand

Expected: FAIL,main.js 仍包含 dj-car-life-system-config 和环境变量读取。

  • Step 3: 用本地配置同步创建 GSC 客户端

保留现有 session、错误提示和登出事件,仅将来源改为 baseConfig.gsc:

window.$gscApi = new Request({
    ...baseConfig.gsc,
    session: {
        requiresSession: true,
        sessionId: _ => util.cookies.get("token"),
    },
    events: {
        error: (error) => {
            Vue.prototype.$message.error(error.msg);
        },
        logout: () => {
            store.dispatch("d2admin/user/clear");
            util.cookies.remove("token");
            router.replace("/login");
            Vue.prototype.$message.error("登录超时,请重新登录");
        },
    },
});

init();

删除 developConfig、parseConfigCenterResponse、mergeConfigTarget、configCenterLoaded、fetch 链和 applyDevelopAxiosConfig。

  • Step 4: 删除无引用的旧配置文件并扫描引用

Run: rg -n "baseConfig\.develop|parseConfigCenterResponse|VUE_APP_CONFIG_CENTER_URL|VUE_APP_USE_DEVELOP_AXIOS|dj-car-life-system-config" src

Expected: 无匹配;随后删除 baseConfig.develop.json 和 parseConfigCenterResponse.js。

  • Step 5: 运行启动链路与完整 Jest

Run: npm run test:unit -- tests/unit/mainConfig.spec.js --runInBand

Expected: 2 tests PASS。

Run: npm run test:unit -- --runInBand

Expected: 所有测试 PASS。

  • Step 6: 提交浏览器启动改造
git add src/main.js tests/unit/mainConfig.spec.js src/common/baseConfig.develop.json src/common/parseConfigCenterResponse.js
git commit -m "refactor: 启动时直接读取本地环境配置"

Task 4: 静态检查、编译验收与推送

Files:

  • Modify only if verification exposes an issue: files changed in Tasks 1-3.

Interfaces:

  • Consumes: Tasks 1-3 的完整实现。
  • Produces: 可安装、可测试、可编译并已推送的 v1.0.0 分支。

  • Step 1: 检查远程配置残留与敏感日志

Run: rg -n "dj-car-life-system-config|VUE_APP_CONFIG_CENTER_URL|VUE_APP_USE_DEVELOP_AXIOS|console\.log\([^\n]*(appkey|secret)" src

Expected: 无匹配。

  • Step 2: 对修改的 JavaScript 文件执行无修复 ESLint

Run: npx eslint src/common/baseConfig.js src/common/runtimeConfig.js src/common/runtimeConfig.spec.js src/libs/rop/loadAxiosConfig.js src/libs/rop/loadAxiosConfig.spec.js src/libs/rop/ropClient.js src/main.js tests/unit/mainConfig.spec.js

Expected: exit 0,0 errors。

  • Step 3: 运行完整 Jest

Run: npm run test:unit -- --runInBand

Expected: 所有测试 PASS。

  • Step 4: 执行无 Mock 构建

Run: npm run build:nomock

Expected: Build complete 且 exit 0;构建输出不得出现 dj-car-life-system-config。

  • Step 5: 核对差异和提交历史

Run: git diff --check origin/v1.0.0...HEAD

Expected: 无空白错误。

Run: git status --short --branch

Expected: 工作区干净,分支为 v1.0.0。

  • Step 6: 推送远程分支

Run: git push origin v1.0.0

Expected: v1.0.0 -> v1.0.0。