mp-npm-core.mjs 19.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
/**
 * mp 小程序「构建 npm」核心逻辑(无副作用,供各入口复用)。
 *
 * 两个入口都只是薄壳:
 *   - apps/mp/<lane>/mp-npm.mjs   只管本 lane(日常用这个,谁改谁跑)
 *   - scripts/mp-npm.mjs          全量,遍历 apps/mp/manifest.json 里所有 lane
 *
 * 背景(为什么需要它):
 *   微信开发者工具的「构建 npm」有一套自己的判定逻辑,坑都在静默失败上:
 *   1. 只认 `miniprogram` 字段指向**目录**的包(packnpm.js 的 checkIsMiniprogramPack),
 *      指到文件会掉进 packJs() 兜底,打不动就 `continue`,连警告都没有;
 *   2. 前置产物(api-core 的 miniprogram_dist/、usedcar 内嵌 packageUsedCar 的 node_modules)
 *      全是 gitignore 的构建物,clone 完不跑就漏;
 *   3. 漏了的表现不是报错,是首屏白屏 + `module '@uj/api-core' is not defined`。
 */
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import net from 'node:net';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const here = dirname(fileURLToPath(import.meta.url));

/** 仓库根 */
export const ROOT = resolve(here, '..');
export const MP_ROOT = join(ROOT, 'apps', 'mp');
export const API_CORE_DIR = join(ROOT, 'packages', 'api-core');
export const DEVTOOLS_PORT = Number(process.env.WX_DEVTOOLS_PORT || 9420);

/**
 * 带内嵌子包的 lane:这些子包被 pnpm-workspace.yaml 显式排除(依赖走私有源),
 * 必须用它自己的 npm 装,工具才拿得到 node_modules。
 */
const SUBPACKAGES = {
  usedcar: {
    dir: 'packageUsedCar',
    setupScript: 'scripts/setup-package-used-car.mjs',
    fixHint: 'pnpm --filter @uj/mp-usedcar run setup:deps',
  },
};

// ---------------------------------------------------------------------------
// 小工具
// ---------------------------------------------------------------------------
const C = {
  reset: '\u001b[0m',
  dim: '\u001b[2m',
  red: '\u001b[31m',
  green: '\u001b[32m',
  yellow: '\u001b[33m',
  cyan: '\u001b[36m',
  bold: '\u001b[1m',
};
const tty = process.stdout.isTTY;
export const paint = (s, color) => (tty ? `${color}${s}${C.reset}` : s);
export const Cc = C;

const ok = (msg) => console.log(`  ${paint('✓', C.green)} ${msg}`);
const bad = (msg) => console.log(`  ${paint('✗', C.red)} ${msg}`);
const warn = (msg) => console.log(`  ${paint('!', C.yellow)} ${msg}`);
const info = (msg) => console.log(`  ${paint('·', C.dim)} ${msg}`);
const section = (msg) => console.log(`\n${paint(msg, C.bold)}`);

function readJson(file) {
  try {
    return JSON.parse(readFileSync(file, 'utf8'));
  } catch {
    return null;
  }
}

/** 目录是否存在且(递归两层内)含文件。@vant/weapp 构建后只有组件子目录,不能只看第一层。 */
function isNonEmptyDir(dir, depth = 0) {
  if (!existsSync(dir)) return false;
  if (!statSync(dir).isDirectory()) return false;
  let entries;
  try {
    entries = readdirSync(dir, { withFileTypes: true });
  } catch {
    return false;
  }
  if (entries.length === 0) return false;
  if (entries.some((e) => e.isFile())) return true;
  if (depth >= 2) return entries.length > 0;
  return entries.some((e) => e.isDirectory() && isNonEmptyDir(join(dir, e.name), depth + 1));
}

function run(cmd, args, opts = {}) {
  const res = spawnSync(cmd, args, {
    cwd: opts.cwd || ROOT,
    stdio: opts.capture ? 'pipe' : 'inherit',
    encoding: 'utf8',
    // Windows 上 pnpm / cli.bat 都是 .cmd / .bat,必须过 shell
    shell: process.platform === 'win32',
  });
  if (opts.capture && opts.verbose && res.stdout) console.log(res.stdout.trim());
  return { code: res.status ?? 1, stdout: res.stdout || '', stderr: res.stderr || '' };
}

function canConnect(port, host = '127.0.0.1', timeout = 800) {
  return new Promise((res) => {
    const socket = net.connect({ port, host });
    const done = (v) => {
      socket.destroy();
      res(v);
    };
    socket.once('connect', () => done(true));
    socket.once('error', () => done(false));
    socket.once('timeout', () => done(false));
    socket.setTimeout(timeout);
  });
}

// ---------------------------------------------------------------------------
// 参数 / lane 真源
// ---------------------------------------------------------------------------
/**
 * 解析命令行参数。
 * --check      只体检,不改任何文件
 * --no-build   跳过 api-core 构建
 * --no-install 跳过内嵌子包依赖安装
 * --verbose    透出子进程输出
 * --lane a,b   仅根入口用
 */
export function parseArgs(argv = process.argv.slice(2)) {
  const has = (flag) => argv.includes(flag);
  const valueOf = (flag) => {
    const i = argv.indexOf(flag);
    return i === -1 ? undefined : argv[i + 1];
  };
  const checkOnly = has('--check');
  return {
    checkOnly,
    noBuild: checkOnly || has('--no-build'),
    noInstall: checkOnly || has('--no-install'),
    verbose: has('--verbose'),
    lanes: (valueOf('--lane') || '')
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean),
  };
}

/** manifest 里声明、且磁盘上真实存在的 lane(按 manifest 顺序)。 */
export function listLanes() {
  const manifest = readJson(join(MP_ROOT, 'manifest.json'));
  const dirs = Array.isArray(manifest?.apps) ? manifest.apps.map((a) => a.dir) : [];
  return dirs.filter((d) => existsSync(join(MP_ROOT, d)));
}

function assertLanes(lanes) {
  const all = listLanes();
  const unknown = lanes.filter((d) => !all.includes(d));
  if (unknown.length) {
    console.error(`未知 lane: ${unknown.join(', ')}(manifest 里只有 ${all.join(' / ')})`);
    process.exit(1);
  }
  return lanes;
}

// ---------------------------------------------------------------------------
// 1. 准备:api-core 产物 + 内嵌子包依赖
// ---------------------------------------------------------------------------
function prepareApiCore(o) {
  const out = join(API_CORE_DIR, 'miniprogram_dist', 'index.js');
  if (o.noBuild) {
    if (existsSync(out)) {
      ok('miniprogram_dist/index.js 已存在(未重建)');
    } else {
      bad('miniprogram_dist/index.js 不存在,先跑 pnpm --filter @uj/api-core build');
    }
    return existsSync(out);
  }
  info('构建中:pnpm --filter @uj/api-core build');
  const r = run('pnpm', ['--filter', '@uj/api-core', 'build'], {
    capture: true,
    verbose: o.verbose,
  });
  if (r.code !== 0) {
    bad('构建失败');
    if (r.stderr) console.log(r.stderr.trim());
    return false;
  }
  if (!existsSync(out)) {
    bad('构建成功但没有 miniprogram_dist/index.js,检查 tsup.config.ts 的第二份配置');
    return false;
  }
  ok(`miniprogram_dist/index.js (${(statSync(out).size / 1024).toFixed(1)} KB)`);

  // 工具的 checkIsMiniprogramPack 只认目录;指到文件会被静默跳过(2026-11-09 白屏根因)
  const mpField = readJson(join(API_CORE_DIR, 'package.json'))?.miniprogram;
  const isDir =
    typeof mpField === 'string' &&
    existsSync(join(API_CORE_DIR, mpField)) &&
    statSync(join(API_CORE_DIR, mpField)).isDirectory();
  if (!isDir) {
    bad(`package.json 的 "miniprogram" 必须指向目录(当前: ${mpField ?? '缺失'})`);
    return false;
  }
  ok(`"miniprogram": "${mpField}" 指向目录,符合工具的 checkIsMiniprogramPack`);
  return true;
}

function prepareSubpackage(lane, sub, o) {
  const subDir = join(MP_ROOT, lane, sub.dir);
  const pkgPath = join(subDir, 'package.json');
  if (!existsSync(pkgPath)) {
    warn(`${lane}/${sub.dir} 没有 package.json,跳过`);
    return true;
  }
  const deps = Object.keys(readJson(pkgPath)?.dependencies || {});
  if (!deps.length) {
    info(`${sub.dir} 无 dependencies,跳过`);
    return true;
  }
  const missing = deps.filter((d) => !existsSync(join(subDir, 'node_modules', d)));
  if (!missing.length) {
    ok(`已安装:${deps.join(', ')}`);
    return true;
  }
  bad(`缺 ${missing.join(', ')}`);
  if (o.noInstall) {
    info(`未安装;修复命令:${sub.fixHint}`);
    return false;
  }
  info(`安装中:${sub.setupScript}(内部 npm install)`);
  const r = run(process.execPath, [sub.setupScript], { cwd: join(MP_ROOT, lane) });
  if (r.code !== 0) {
    bad('安装失败');
    return false;
  }
  const still = deps.filter((d) => !existsSync(join(subDir, 'node_modules', d)));
  if (still.length) {
    bad(`仍缺 ${still.join(', ')}`);
    return false;
  }
  ok('安装完成');
  return true;
}

// ---------------------------------------------------------------------------
// 2. 构建 npm(能自动就自动,不能就给出精确到按钮的清单)
// ---------------------------------------------------------------------------
function findDevtoolsCli() {
  return [
    process.env.WX_DEVTOOLS_CLI,
    'D:\\soft\\tencent\\微信web开发者工具\\cli.bat',
    'C:\\Program Files (x86)\\Tencent\\微信web开发者工具\\cli.bat',
    'C:\\Program Files\\Tencent\\微信web开发者工具\\cli.bat',
  ]
    .filter(Boolean)
    .find((p) => existsSync(p));
}

async function buildViaCli(lanes, o) {
  const cli = findDevtoolsCli();
  if (!(await canConnect(DEVTOOLS_PORT))) {
    warn(`服务端口 ${DEVTOOLS_PORT} 未监听,跳过自动构建`);
    return { mode: 'manual', cli, reason: `服务端口 ${DEVTOOLS_PORT} 未监听` };
  }
  if (!cli) {
    warn('找不到 cli.bat,跳过自动构建');
    return { mode: 'manual', cli, reason: '找不到 cli.bat(可用 WX_DEVTOOLS_CLI 指定)' };
  }
  const failed = [];
  for (const lane of lanes) {
    info(`${lane}: cli build-npm`);
    const r = run(cli, ['build-npm', '--project', join(MP_ROOT, lane), '--lang', 'zh'], {
      capture: true,
      verbose: o.verbose,
    });
    if (r.code === 0) {
      ok(`${lane} 构建 npm 完成`);
      continue;
    }
    failed.push(lane);
    bad(`${lane} 构建 npm 失败(exit ${r.code})`);
    // CLI 无输出是常见状态,有输出时给出来,别吞掉
    const detail = `${r.stdout || ''}${r.stderr || ''}`.trim();
    if (detail) console.log(detail.split('\n').slice(0, 6).join('\n'));
  }
  return { mode: 'cli', cli, failed };
}

// ---------------------------------------------------------------------------
// 3. 体检:miniprogram_npm 是否真的落地产物
// ---------------------------------------------------------------------------
/** 还原开发者工具要构建的关系表(手工模式读 packNpmRelationList,自动模式取 lane 根)。 */
function collectRelations(laneDir, projectConfig) {
  const list = projectConfig?.setting?.packNpmRelationList;
  if (Array.isArray(list) && list.length) {
    return list.map((r) => ({
      pkgJsonPath: resolve(laneDir, r.packageJsonPath),
      distDir: resolve(laneDir, r.miniprogramNpmDistDir || './'),
    }));
  }
  return [{ pkgJsonPath: join(laneDir, 'package.json'), distDir: laneDir }];
}

/**
 * 「构建 npm」会把 miniprogram_dist/index.js 原样拷进 miniprogram_npm/@uj/api-core/index.js。
 * 只看「文件存在」会把旧 bundle 也判成就位 —— 主入口导出面一变(如新增 createClient),
 * 旧包在运行时就是 undefined。按内容比对(换行归一)识别过期,给中性提示而非报错。
 */
function apiCoreBundleFresh(target) {
  const src = join(API_CORE_DIR, 'miniprogram_dist', 'index.js');
  const dst = join(target, '@uj/api-core', 'index.js');
  if (!existsSync(src) || !existsSync(dst)) return undefined;
  const norm = (p) => readFileSync(p, 'utf8').replace(/\r\n/g, '\n');
  return norm(src) === norm(dst);
}

function checkRelation(rel) {
  const pkg = readJson(rel.pkgJsonPath);
  if (!pkg) return { error: `读不到 ${rel.pkgJsonPath}`, deps: [], missing: [], broken: [] };
  const deps = Object.keys(pkg.dependencies || {});
  if (!deps.length) return { deps, missing: [], broken: [], skipped: true, target: rel.distDir };
  const target = join(rel.distDir, 'miniprogram_npm');
  const missing = deps.filter((dep) => !isNonEmptyDir(join(target, dep)));
  // api-core 是单文件 CJS 包,目录在但没 index.js 一样起不来
  const broken = [];
  if (deps.includes('@uj/api-core') && !existsSync(join(target, '@uj/api-core', 'index.js'))) {
    if (!missing.includes('@uj/api-core')) broken.push('@uj/api-core 缺 index.js');
  }
  const stale = [];
  if (deps.includes('@uj/api-core') && apiCoreBundleFresh(target) === false) {
    stale.push('@uj/api-core 产物不是最新(主入口已更新)');
  }
  return { deps, missing, broken, stale, target, pkgPath: rel.pkgJsonPath };
}

export function inspectLane(lane) {
  const laneDir = join(MP_ROOT, lane);
  const config = readJson(join(laneDir, 'project.config.json'));
  const rows = collectRelations(laneDir, config).map((rel) => {
    const label =
      rel.distDir === laneDir
        ? '主包'
        : rel.distDir.replace(laneDir, '').replace(/^[\\/]/, '') || '主包';
    return { label, ...checkRelation(rel) };
  });
  const gap = rows.flatMap((r) => [...(r.missing || []), ...(r.broken || [])]);
  const stale = rows.flatMap((r) => r.stale || []);
  const hasTarget = rows.some((r) => r.target && existsSync(r.target));
  return {
    lane,
    laneDir,
    rows,
    gap,
    stale,
    hasTarget,
    built: hasTarget && gap.length === 0 && stale.length === 0,
    autoMode: config?.setting?.packNpmManually !== true,
    nodeModulesOff: config?.setting?.nodeModules === false,
  };
}

function printLaneReport(r) {
  console.log(
    `\n  ${paint(r.lane, C.bold)}${r.autoMode ? paint('  (未配置 packNpmRelationList,自动模式)', C.dim) : ''}`,
  );
  for (const row of r.rows) {
    if (row.skipped) {
      info(`${row.label}: 无 dependencies,跳过`);
      continue;
    }
    if (row.error) {
      bad(`${row.label}: ${row.error}`);
      continue;
    }
    const total = row.deps.length;
    const gap = [...row.missing, ...row.broken];
    if (!gap.length) {
      ok(`${row.label}: ${total}/${total} 包就位`);
    } else if (!r.hasTarget) {
      bad(`${row.label}: 未构建(0/${total}),缺 ${row.deps.join(', ')}`);
    } else {
      bad(`${row.label}: ${total - row.missing.length}/${total} 包就位,缺 ${gap.join(', ')}`);
    }
    if (row.stale?.length) warn(`${row.label}: ${row.stale.join('、')}`);
  }
  if (r.nodeModulesOff) {
    warn('project.config.json 里 nodeModules: false(旧开关),工具可能不启用 npm 模块');
  }
}

// ---------------------------------------------------------------------------
// 主流程
// ---------------------------------------------------------------------------
/**
 * 对给定 lane 执行「准备 + 构建 + 体检」。
 * @returns {Promise<{ok: boolean, report: object[], build: object}>}
 */
export async function runLanes(lanes, opts = parseArgs()) {
  const o = { checkOnly: false, noBuild: false, noInstall: false, verbose: false, ...opts };
  const targets = assertLanes(lanes);
  const all = listLanes();
  const scope =
    targets.length === all.length
      ? `全部 ${targets.length} 个 lane: ${targets.join(', ')}`
      : `lane: ${targets.join(', ')}`;

  console.log(
    paint('mp 小程序 · 构建 npm', C.cyan) + paint(o.checkOnly ? '  (只读体检)' : '', C.dim),
  );
  console.log(paint(scope, C.dim));

  // 动态编排:单 lane 跑的时候不会出现用不上的步骤(比如非 usedcar 不会打印子包依赖)
  const steps = [{ key: 'apiCore', title: 'api-core 小程序产物', run: () => prepareApiCore(o) }];
  for (const lane of targets) {
    const sub = SUBPACKAGES[lane];
    if (!sub) continue;
    steps.push({
      key: `sub:${lane}`,
      title: `${lane} 内嵌子包依赖(${sub.dir} 用 npm,不进 workspace)`,
      run: () => prepareSubpackage(lane, sub, o),
    });
  }
  if (!o.checkOnly) {
    steps.push({
      key: 'build',
      title: '构建 npm(微信开发者工具)',
      run: () => buildViaCli(targets, o),
    });
  }

  const res = {};
  for (const [i, step] of steps.entries()) {
    section(`[${i + 1}/${steps.length + 1}] ${step.title}`);
    res[step.key] = await step.run();
  }

  section(`[${steps.length + 1}/${steps.length + 1}] miniprogram_npm 体检`);
  const report = targets.map(inspectLane);
  for (const r of report) printLaneReport(r);

  const pending = report.filter((r) => !r.built);
  const ready = report.filter((r) => r.built);
  const staleLanes = report.filter((r) => r.stale?.length);
  const build = res.build || { mode: 'skipped' };

  console.log(`\n${paint('── 结果 ──', C.bold)}`);
  if (ready.length)
    console.log(`  ${paint('可用', C.green)}: ${ready.map((r) => r.lane).join(', ')}`);
  if (pending.length) {
    if (build.mode === 'manual') {
      // 「工具 → 构建 npm」是微信小程序的默认手工动作,不是异常,不必报警为白屏风险
      console.log(`  ${paint('待手动构建 npm', C.yellow)}: ${pending.map((r) => r.lane).join(', ')}`);
    } else {
      // 缺包 vs 产物过期分开列:前者要装依赖,后者只需工具重跑一次「构建 npm」。
      const needBuild = pending.filter((r) => r.gap.length);
      const needManual = pending.filter((r) => !r.gap.length);
      if (needBuild.length) {
        console.log(`  ${paint('待构建', C.yellow)}: ${needBuild.map((r) => r.lane).join(', ')}`);
      }
      if (needManual.length) {
        console.log(
          `  ${paint('待手动构建 npm', C.yellow)}: ${needManual.map((r) => r.lane).join(', ')}  (api-core 产物已更新)`,
        );
      }
    }
  }

  if (!pending.length) {
    console.log(`\n${paint('全部就位,可以直接编译。', C.green)}`);
    return { ok: true, report, build };
  }

  if (!res.apiCore) {
    console.log(`\n  先修 api-core:${paint('pnpm --filter @uj/api-core build', C.cyan)}`);
  }
  for (const p of pending) {
    const sub = SUBPACKAGES[p.lane];
    if (!sub || res[`sub:${p.lane}`] !== false) continue;
    console.log(`  ${p.lane} 子包依赖缺失:${paint(sub.fixHint, C.cyan)}`);
  }
  if (build.mode === 'manual' || staleLanes.length) {
    const reason = build.reason ?? 'api-core 产物已更新,本地 miniprogram_npm 仍是旧 bundle';
    console.log(`\n  ${paint('构建 npm 需要开发者工具:', C.yellow)}${reason}`);
    console.log('  打开对应项目后执行「工具 → 构建 npm」,再重跑本命令校验:');
    const needBuild = build.mode === 'manual' ? pending : staleLanes;
    for (const p of needBuild) {
      const label = targets.length === 1 ? p.laneDir : `${p.lane}  (${p.laneDir})`;
      console.log(`    - ${label}`);
    }
    console.log(
      `\n  ${paint('想全自动:', C.dim)}开发者工具 → 设置 → 安全设置 → 打开「服务端口」(${DEVTOOLS_PORT}),之后本命令会直接调 cli 构建。`,
    );
  } else if (build.mode === 'cli' && build.failed?.length) {
    console.log(`\n  CLI 构建失败: ${build.failed.join(', ')}(多为项目未在该工具实例中打开)`);
  }
  return { ok: false, report, build };
}

/** lane 薄壳入口:跑完自带退出码。 */
export async function runLaneCli(lane, argv = process.argv.slice(2)) {
  const o = parseArgs(argv);
  if (o.lanes.length && !o.lanes.includes(lane)) {
    console.log(paint(`(忽略 --lane ${o.lanes.join(',')}:本入口只处理 ${lane})`, C.yellow));
  }
  const { ok } = await runLanes([lane], o);
  process.exit(ok ? 0 : 1);
}