build-native-account-review.mjs 10 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/env node
  2. /** 真实账号验收包:隔离构建,保留正式包名和真实数据源;不填演示身份。 */
  3. import fs from 'node:fs';
  4. import path from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. import { spawnSync } from 'node:child_process';
  7. import { createHash } from 'node:crypto';
  8. import { updateRealReview as updateNativeReview } from './lib/real-account-review-ledger.mjs';
  9. const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
  10. const revision=process.argv.find(x=>x.startsWith('--revision='))?.split('=')[1]||'r1';
  11. if(!/^r[1-9][0-9]*$/.test(revision))throw Error('非法构建修订');
  12. const evidence=path.join(root,'test-results/real-account-20261130');
  13. const ledger=path.join(evidence,'state.json');
  14. const state=JSON.parse(fs.readFileSync(ledger,'utf8'));
  15. if(state.packageId!=='cn.fmode.app'||state.sourceMode!=='production-real')throw Error('真实包边界配置不符');
  16. const targetPackage=state.packageId;
  17. const id='build_'+revision;
  18. const save=()=>updateNativeReview(current=>{if(state.actions[id])current.actions[id]=state.actions[id];for(const item of state.failures){if(!current.failures.some(x=>x.stage===item.stage&&x.at===item.at&&x.message===item.message))current.failures.push(item)}});
  19. const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
  20. function walk(dir,list=[]){for(const item of fs.readdirSync(dir,{withFileTypes:true})){const full=path.join(dir,item.name);if(item.isDirectory())walk(full,list);else if(item.isFile())list.push(full)}return list}
  21. function skipAndroid(name,isDirectory,relative){
  22. return isDirectory&&['build','.gradle','.kotlin','.cxx','node_modules','.git'].includes(name)
  23. ||/^app\/src\/main\/assets\/public(?:\/|$)/.test(relative)
  24. ||/^(?:local|keystore|key|signing)\.properties$/i.test(name)||name==='google-services.json'||/\.(?:apk|aab|jks|keystore|log)$/i.test(name);
  25. }
  26. function androidInputs(source,relative='',list=[]){
  27. for(const item of fs.readdirSync(source,{withFileTypes:true})){
  28. const rel=path.posix.join(relative,item.name);if(skipAndroid(item.name,item.isDirectory(),rel))continue;
  29. const full=path.join(source,item.name);if(item.isDirectory())androidInputs(full,rel,list);else if(item.isFile())list.push(full);else throw Error('构建输入不支持特殊路径 '+rel);
  30. }return list;
  31. }
  32. function collectInputs(){return [...new Set([
  33. ...walk(path.join(root,'src')).filter(f=>/\.(ts|scss|css|html)$/.test(f)&&!f.endsWith('.spec.ts')),
  34. ...walk(path.join(root,'public')),...androidInputs(path.join(root,'android')),
  35. ...fs.readdirSync(root,{withFileTypes:true}).filter(x=>x.isFile()&&/^(?:tsconfig.*\.json|tailwind\.config\..+|postcss\.config\..+|\.postcssrc(?:\..+)?|\.browserslistrc|browserslist|ngsw-config\.json)$/.test(x.name)).map(x=>path.join(root,x.name)),
  36. ...['angular.json','package.json','package-lock.json','pnpm-lock.yaml','yarn.lock','npm-shrinkwrap.json','capacitor.config.ts','.env.jpush','scripts/build-native-account-review.mjs','scripts/build-native-account-review.ps1'].map(f=>path.join(root,f)).filter(f=>fs.existsSync(f))
  37. ])].sort()}
  38. function inputHash(files){const result=createHash('sha256');for(const file of files){result.update(path.relative(root,file));result.update(fs.readFileSync(file))}return result.digest('hex')}
  39. const sources=collectInputs();const fingerprint=inputHash(sources);
  40. if(state.actions[id]){
  41. const previous=state.actions[id];
  42. if(previous.status==='confirmed'&&previous.receipt&&previous.receipt.sourceSha256===fingerprint&&fs.existsSync(previous.receipt.apk)&&hash(fs.readFileSync(previous.receipt.apk))===previous.receipt.sha256){console.log(JSON.stringify({reusedConfirmedBuild:true,...previous.receipt}));process.exit(0)}
  43. throw Error('构建动作已有记录;先核对原日志/进程/回执,不覆盖或盲重跑:'+id);
  44. }
  45. const build=path.join(evidence,'build-'+revision);
  46. if(fs.existsSync(build))throw Error('构建目录已存在而账本无相应动作,先核实');
  47. state.actions[id]={status:'registered',at:new Date().toISOString(),target:targetPackage,revision,sourceSha256:fingerprint,steps:[]};save();
  48. fs.mkdirSync(build,{recursive:true});
  49. fs.writeFileSync(path.join(build,'source-inputs.json'),JSON.stringify(sources.map(file=>({path:path.relative(root,file),sha256:hash(fs.readFileSync(file))})),null,2),{flag:'wx'});
  50. const isolated=path.join(build,'project');fs.mkdirSync(isolated);
  51. const env={...process.env,ANDROID_HOME:'E:/coding-environment/AndroidSDK',ANDROID_SDK_ROOT:'E:/coding-environment/AndroidSDK',JAVA_HOME:'E:/coding/runtimes/java/jdk-21',FMODE_VENDOR_PUSH:'false',NG_BUILD_MAX_WORKERS:'2'};
  52. for(const key of Object.keys(env))if(/^(?:ANDROID_KEYSTORE|ANDROID_KEY_ALIAS|ANDROID_KEY_PASSWORD|JPUSH_|XIAOMI_|HUAWEI_|OPPO_|VIVO_|HONOR_)/.test(key))delete env[key];
  53. let pushEnabled=false;
  54. if(fs.existsSync(path.join(root,'.env.jpush'))){const values=Object.fromEntries([...fs.readFileSync(path.join(root,'.env.jpush'),'utf8').matchAll(/^\s*([A-Z_]+)\s*=\s*(.*?)\s*$/gm)].map(m=>[m[1],m[2].replace(/^['"]|['"]$/g,'')]));pushEnabled=values.FMODE_JPUSH_ENABLED==='true'&&!!values.JPUSH_APPKEY;if(pushEnabled)env.JPUSH_APPKEY=values.JPUSH_APPKEY;}
  55. function command(name,executable,args,cwd=isolated){
  56. const log=path.join(build,name+'.log');if(fs.existsSync(log))throw Error('阶段日志已存在:'+name);
  57. const step={name,status:'registered',at:new Date().toISOString(),log};state.actions[id].steps.push(step);save();console.log('开始 '+name);
  58. const fd=fs.openSync(log,'wx');let result;
  59. try{result=spawnSync(executable,args,{cwd,env,stdio:['ignore',fd,fd],windowsHide:true,timeout:20*60*1000})}finally{fs.closeSync(fd)}
  60. step.exitCode=result.status;step.status=result.status===0?'confirmed':result.error?.code==='ETIMEDOUT'?'uncertain':'failed';step.completedAt=new Date().toISOString();save();
  61. if(result.status!==0)throw Error(name+' 未通过,保留现场:'+log+';'+(result.error?.message||'exit '+result.status));console.log('通过 '+name);
  62. }
  63. function copyAndroid(source,target,relative=''){
  64. fs.mkdirSync(target,{recursive:true});
  65. for(const item of fs.readdirSync(source,{withFileTypes:true})){
  66. const rel=path.posix.join(relative,item.name);if(skipAndroid(item.name,item.isDirectory(),rel))continue;
  67. const to=path.join(target,item.name),from=path.join(source,item.name);
  68. if(item.isDirectory())copyAndroid(from,to,rel);else if(item.isFile())fs.copyFileSync(from,to);else throw Error('不复制特殊路径 '+rel);
  69. }
  70. }
  71. try{
  72. copyAndroid(path.join(root,'android'),path.join(isolated,'android'));
  73. fs.symlinkSync(path.join(root,'node_modules'),path.join(isolated,'node_modules'),'junction');
  74. fs.copyFileSync(path.join(root,'package.json'),path.join(isolated,'package.json'));
  75. fs.writeFileSync(path.join(isolated,'capacitor.config.json'),JSON.stringify({appId:targetPackage,appName:'飞马SI',webDir:'www/browser',appendUserAgent:'FmodeApp/2.0 RealAccountReview/20261130',server:{hostname:'localhost',androidScheme:'https'},android:{allowMixedContent:false}},null,2));
  76. const gradleFile=path.join(isolated,'android/app/build.gradle');let gradleSource=fs.readFileSync(gradleFile,'utf8');if(!gradleSource.includes('applicationId "cn.fmode.app"'))throw Error('原applicationId定位失败');fs.writeFileSync(gradleFile,gradleSource);
  77. // 正式包保留分享入口和原深链接,不复制演示包的隔离Intent配置。
  78. for(const folder of ['values','values-en']){const file=path.join(isolated,'android/app/src/main/res',folder,'strings.xml');if(fs.existsSync(file)){let xml=fs.readFileSync(file,'utf8');xml=xml.replace(/(<string name="(?:app_name|title_activity_main)">)[\s\S]*?(<\/string>)/g,'$1飞马SI$2');fs.writeFileSync(file,xml)}}
  79. fs.writeFileSync(path.join(isolated,'android/local.properties'),'sdk.dir=E:/coding-environment/AndroidSDK\n');
  80. const configuration=JSON.parse(fs.readFileSync(path.join(root,'angular.json'),'utf8')).projects['fmode-app-v2'].architect.build.configurations.production;
  81. if(!configuration.fileReplacements.some(x=>x.with==='src/environments/environment.production.ts')||!/useMockData:\s*false/.test(fs.readFileSync(path.join(root,'src/environments/environment.production.ts'),'utf8')))throw Error('真实数据构建配置未确认');
  82. command('web-real',process.execPath,[path.join(root,'node_modules/@angular/cli/bin/ng.js'),'build','--configuration','production','--output-path',path.join(isolated,'www')],root);
  83. command('capacitor-sync',process.execPath,[path.join(root,'node_modules/@capacitor/cli/bin/capacitor'),'sync','android']);
  84. const distributions=path.join(process.env.USERPROFILE,'.gradle/wrapper/dists/gradle-8.14.3-bin');
  85. const gradle=walk(distributions).find(file=>file.endsWith(path.join('gradle-8.14.3','bin','gradle.bat')));if(!gradle)throw Error('本机Gradle8.14.3缺失,不回退旧APK');
  86. const shell=spawnSync('where.exe',['pwsh.exe'],{encoding:'utf8'}).status===0?'pwsh.exe':'powershell.exe';
  87. command('gradle-debug',shell,['-NoProfile','-NonInteractive','-File',path.join(root,'scripts/build-native-account-review.ps1'),'-Gradle',gradle,'-Project',path.join(isolated,'android'),'-Revision',revision,'-PushEnabled',String(pushEnabled)]);
  88. const apk=path.join(isolated,'android/app/build/outputs/apk/debug/app-debug.apk');if(!fs.existsSync(apk))throw Error('本次APK未生成');
  89. const aapt='E:/coding-environment/AndroidSDK/build-tools/36.0.0/aapt.exe';const badging=spawnSync(aapt,['dump','badging',apk],{encoding:'utf8',windowsHide:true});if(badging.status!==0||!/^package: name='cn\.fmode\.app'/m.test(badging.stdout))throw Error('APK包名未确认,禁止安装');
  90. fs.writeFileSync(path.join(build,'apk-badging.txt'),badging.stdout);
  91. if(inputHash(collectInputs())!==fingerprint)throw Error('构建期间输入发生变化,不确认此APK,不安装');
  92. const receipt={packageId:targetPackage,revision,sourceMode:'production-real',sourceSha256:fingerprint,sourceFiles:sources.length,apk,sha256:hash(fs.readFileSync(apk)),bytes:fs.statSync(apk).size,at:new Date().toISOString(),realData:true,pushEnabled,vendorPushEnabled:false};
  93. fs.writeFileSync(path.join(build,'apk-receipt.json'),JSON.stringify(receipt,null,2)+'\n',{flag:'wx'});
  94. state.actions[id].status='confirmed';state.actions[id].receipt=receipt;save();console.log(JSON.stringify(receipt,null,2));
  95. }catch(error){state.actions[id].status=state.actions[id].steps.some(x=>x.status==='uncertain')?'uncertain':'failed';state.failures.push({stage:id,message:error.message,at:new Date().toISOString()});save();console.error(error.message);process.exitCode=1}