sync-mp-apps.mjs 10.7 KB
#!/usr/bin/env node
/**
 * mp lane 名字真源的消费端。
 *
 * 唯一真源:apps/mp/manifest.json(定义所有原生小程序 lane 的 dir / displayName / appId / backend)。
 * 本脚本依据 manifest 为每个小程序生成 / 同步脚手架(package.json / tsconfig.json / eslint.config.mjs / src/index.ts)。
 *
 * 用法:
 *   node scripts/sync-mp-apps.mjs            # 新增缺失的 lane、同步包名,不删除多余目录(仅警告)
 *   node scripts/sync-mp-apps.mjs --prune    # 额外删除不在 manifest 中的 apps/mp 子目录(example / manifest 除外)
 *
 * 改名流程:改 manifest 的 dir -> 跑本脚本(旧目录会告警)-> 加 --prune 清掉旧目录。
 */
import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, rmSync, renameSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '..');
const MP_ROOT = join(ROOT, 'apps', 'mp');
const manifestPath = join(MP_ROOT, 'manifest.json');

const PRUNE = process.argv.includes('--prune');

const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
if (!Array.isArray(manifest.apps)) {
  console.error('[错误] manifest.json 缺少 apps 数组');
  process.exit(1);
}
const apps = manifest.apps;
const wantedDirs = new Set(apps.map((a) => a.dir));

function templatePackageJson(dir) {
  return {
    name: `@uj/mp-${dir}`,
    version: '0.0.0',
    private: true,
    // 原生小程序入口;lint 只扫 src(工具链不管 mp 业务 js,见根 eslint.config.js 的 ignores)。
    // 刻意不写 "type": "module":mp 自带代码与它自己的 node 测试都是 CommonJS 口径
    // (utils/lib/*.js 用 module.exports),带上 type 会让这些测试全红,
    // 也会让 devtool「构建 npm」看到的清单和源工程不一致。ESLint 配置改用 .mjs 后缀自证 ESM。
    main: 'app.js',
    scripts: { typecheck: 'tsc --noEmit', lint: 'eslint src' },
    dependencies: { '@uj/api-core': 'workspace:*' },
    devDependencies: {
      '@uj/contracts': 'workspace:*',
      '@uj/eslint-config': 'workspace:*',
      '@uj/typescript-config': 'workspace:*',
      typescript: 'catalog:',
    },
  };
}

function templateTsconfig() {
  return {
    extends: '../../../packages/typescript-config/mini-program.json',
    compilerOptions: {
      baseUrl: '.',
      paths: {
        '@uj/api-core': ['../../../packages/api-core/src/index.ts'],
        '@uj/contracts': ['../../../packages/contracts/src/index.ts'],
      },
    },
    include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.d.ts'],
  };
}

function templateEslint() {
  return [
    "import { mp } from '@uj/eslint-config';",
    '',
    '// 小程序 lane:禁止引用 web/host 独占运行时(见 @uj/eslint-config 的 mp 预设)。',
    'export default mp();',
    '',
  ].join('\n');
}

function templateIndexTs(dir, displayName) {
  const gatewayId = `${dir}-backend`;
  const signerId = `${dir}-sha1`;
  // dir 可能含连字符(如 uj-points),不能直接当 JS 标识符用。
  // 转 camelCase 供 const / 函数名使用;id 字符串仍保留原 dir(带连字符,合法)。
  const camelDir = dir.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
  const capCamel = camelDir.charAt(0).toUpperCase() + camelDir.slice(1);
  const L = [];
  L.push("import {");
  L.push("  createRpcDispatcher,");
  L.push("  createWxSender,");
  L.push("  createSha1Signer,");
  L.push("  registerGateway,");
  L.push("  type GatewayStrategy,");
  L.push("  type GatewayCredential,");
  L.push("  type NormalizedEnvelope,");
  L.push("  type RpcCall,");
  L.push("} from '@uj/api-core';");
  L.push('');
  L.push('/**');
  L.push(` * ${displayName}(apps/mp lane 脚手架,由 scripts/sync-mp-apps.mjs 依据 apps/mp/manifest.json 生成)。`);
  L.push(' *');
  L.push(' * 与 web 子应用共用同一套 @uj/api-core 契约,差异只在 transport 一个参数:');
  L.push(' *  - web 子应用:createHostSender(requestViaHost()) 把请求交回主壳 axios;');
  L.push(' *  - 原生小程序:createWxSender() 直接用 wx.request(不经由主壳,不破坏请求层边界)。');
  L.push(' *');
  L.push(' * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、');
  L.push(' * appKey/format/method/v + params 全签),与 web points 子应用的 MD5 网关是两套不同');
  L.push(' * 算法——同一后端家族、不同端用不同摘要,故 mp 走 createSha1Signer。');
  L.push(' *');
  L.push(' * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();');
  L.push(' * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。');
  L.push(' */');
  L.push(`export const ${camelDir}Gateway: GatewayStrategy = {`);
  L.push(`  id: '${gatewayId}',`);
  L.push(`  // 落点随接入项目而变:scrm 系为 rop-scrm-<dir>/router,dj 系为 rop-dj-<dir>/router。`);
  L.push(`  router: 'rop-scrm-${dir}/router',`);
  L.push("  tokenHeader: 'token',");
  L.push(`  // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。`);
  L.push(`  signer: createSha1Signer({ id: '${signerId}' }),`);
  L.push("  // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。");
  L.push("  fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },");
  L.push('  // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。');
  L.push('  normalize(body: unknown): NormalizedEnvelope {');
  L.push("    if (!body || typeof body !== 'object') return { data: body };");
  L.push('    const env = body as Record<string, unknown>;');
  L.push("    const code = env['code'];");
  L.push("    if (String(code) === '0') return { data: env['data'] };");
  L.push('    return {');
  L.push('      code: Number(code) || 500,');
  L.push("      message: typeof env['message'] === 'string' ? env['message'] : '请求失败',");
  L.push('    };');
  L.push('  },');
  L.push('};');
  L.push(`registerGateway(${camelDir}Gateway);`);
  L.push('');
  L.push('/** 运行时凭据:真实项目从配置中心 / 编译变量注入,本层不留密钥字面量。 */');
  L.push('const credentials = new Map<string, GatewayCredential>([');
  L.push(`  ['${gatewayId}', { origin: 'https://${dir}.example.com', appKey: 'app-key', secret: 'app-secret', version: '1.0', format: 'json' }],`);
  L.push(']);');
  L.push('');
  L.push('const dispatch = createRpcDispatcher({');
  L.push('  // 原生小程序 transport:wx.request(非 wujie 环境,可自行发请求)。');
  L.push('  sender: createWxSender(),');
  L.push('  resolveCredential: (id) => {');
  L.push('    const c = credentials.get(id);');
  L.push('    if (!c) throw new Error(`未配置网关 ${id} 的凭据`);');
  L.push('    return c;');
  L.push('  },');
  L.push("  resolveToken: () => '',");
  L.push('  timeout: 30000,');
  L.push('});');
  L.push('');
  L.push('/** 业务侧调用:只说方法名和参数,不关心对方怎么加签 / 怎么发。 */');
  L.push(`export function call${capCamel}<T = unknown>(method: string, params: Record<string, unknown>): Promise<T> {`);
  L.push(`  const call: RpcCall = { gateway: '${gatewayId}', method, params, signed: true };`);
  L.push('  return dispatch(call) as Promise<T>;');
  L.push('}');
  L.push('');
  return L.join('\n');
}

let created = 0;
for (const app of apps) {
  const { dir, displayName } = app;
  if (!dir || !/^[a-z][a-z0-9-]*$/.test(dir)) {
    console.error(`[错误] 非法 dir: ${dir}(需小写字母开头,含小写字母/数字/连字符)`);
    process.exit(1);
  }
  const appDir = join(MP_ROOT, dir);
  const srcDir = join(appDir, 'src');
  mkdirSync(srcDir, { recursive: true });

  const pkgPath = join(appDir, 'package.json');
  if (existsSync(pkgPath)) {
    const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
    const expected = templatePackageJson(dir);
    const drift = [];
    if (pkg.name !== expected.name) {
      pkg.name = expected.name;
      drift.push(`name -> ${expected.name}`);
    }
    // 物理迁入的 lane 带着原工程 package.json 的字段,这里只回收 lane 规范项,不动业务字段。
    if ('type' in pkg) {
      delete pkg.type;
      drift.push('删除 type(mp 代码与其自带测试按 CommonJS 口径)');
    }
    if (pkg.main !== expected.main) {
      pkg.main = expected.main;
      drift.push(`main -> ${expected.main}`);
    }
    for (const [script, command] of Object.entries(expected.scripts)) {
      if (pkg.scripts?.[script] !== command) {
        pkg.scripts = { ...pkg.scripts, [script]: command };
        drift.push(`scripts.${script} -> ${command}`);
      }
    }
    if (drift.length) {
      writeFileSync(pkgPath, `${JSON.stringify(pkg, null, 2)}\n`);
      console.log(`同步 ${dir}/package.json: ${drift.join(', ')}`);
    }
  } else {
    writeFileSync(pkgPath, `${JSON.stringify(templatePackageJson(dir), null, 2)}\n`);
    console.log(`新建 ${dir}/package.json`);
  }

  const tsconfigPath = join(appDir, 'tsconfig.json');
  if (!existsSync(tsconfigPath)) {
    writeFileSync(tsconfigPath, `${JSON.stringify(templateTsconfig(), null, 2)}\n`);
  }
  const eslintPath = join(appDir, 'eslint.config.mjs');
  if (!existsSync(eslintPath)) {
    const legacyPath = join(appDir, 'eslint.config.js');
    if (existsSync(legacyPath)) {
      // lane 不再带 package.json type,.js 会被当 CJS -> 必须换成 .mjs 后缀自证 ESM。
      renameSync(legacyPath, eslintPath);
      console.log(`重命名 ${dir}/eslint.config.js -> eslint.config.mjs`);
    } else {
      writeFileSync(eslintPath, templateEslint());
    }
  }
  const indexPath = join(srcDir, 'index.ts');
  if (!existsSync(indexPath)) {
    writeFileSync(indexPath, templateIndexTs(dir, displayName));
    created++;
    console.log(`新建 ${dir}/src/index.ts (${displayName})`);
  }
}

// 反向校验:磁盘上不在 manifest 的 apps/mp 子目录(排除 example / manifest / 脚本 / node_modules),提示或清理。
const reserved = new Set(['example', 'node_modules']);
const entries = readdirSync(MP_ROOT, { withFileTypes: true });
const stale = entries
  .filter((e) => e.isDirectory() && !wantedDirs.has(e.name) && !reserved.has(e.name))
  .map((e) => e.name);
for (const s of stale) {
  const p = join(MP_ROOT, s);
  if (PRUNE) {
    rmSync(p, { recursive: true, force: true });
    console.log(`[prune] 删除不在 manifest 的 lane: ${s}`);
  } else {
    console.warn(`[警告] 磁盘存在不在 manifest 的 lane: ${s}(如需删除请加 --prune 重跑)`);
  }
}

console.log(`\n完成:manifest 含 ${apps.length} 个小程序,本次新建 ${created} 个 index.ts 脚手架。`);