packager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const BOOTSTRAP_MARKER = '/* hot-update-builder:bootstrap */';
  6. const NATIVE_PLATFORMS = new Set([
  7. 'android',
  8. 'ios',
  9. 'mac',
  10. 'windows',
  11. 'linux',
  12. 'native',
  13. 'openharmony',
  14. 'harmonyos-next',
  15. ]);
  16. const BOOTSTRAP_SCRIPT = `${BOOTSTRAP_MARKER}
  17. (function () {
  18. if (typeof window.jsb === 'object') {
  19. var hotUpdateSearchPaths = localStorage.getItem('HotUpdateSearchPaths');
  20. if (hotUpdateSearchPaths) {
  21. var paths = JSON.parse(hotUpdateSearchPaths);
  22. jsb.fileUtils.setSearchPaths(paths);
  23. var fileList = [];
  24. var storagePath = paths[0] || '';
  25. var tempPath = storagePath + '_temp/';
  26. var baseOffset = tempPath.length;
  27. if (jsb.fileUtils.isDirectoryExist(tempPath) && !jsb.fileUtils.isFileExist(tempPath + 'project.manifest.temp')) {
  28. jsb.fileUtils.listFilesRecursively(tempPath, fileList);
  29. fileList.forEach(srcPath => {
  30. var relativePath = srcPath.substr(baseOffset);
  31. var dstPath = storagePath + relativePath;
  32. if (srcPath[srcPath.length] == '/') {
  33. jsb.fileUtils.createDirectory(dstPath)
  34. }
  35. else {
  36. if (jsb.fileUtils.isFileExist(dstPath)) {
  37. jsb.fileUtils.removeFile(dstPath)
  38. }
  39. jsb.fileUtils.renameFile(srcPath, dstPath);
  40. }
  41. })
  42. jsb.fileUtils.removeDirectory(tempPath);
  43. }
  44. }
  45. }
  46. })();
  47. `;
  48. async function packageHotUpdate({
  49. buildOptions,
  50. buildResult,
  51. remoteUrl,
  52. version,
  53. projectPath,
  54. }) {
  55. if (!buildResult?.dest) {
  56. throw new Error('[热更新打包] 构建结果缺少 dest 路径。');
  57. }
  58. const platform = String(buildOptions?.platform || '').toLowerCase();
  59. if (!NATIVE_PLATFORMS.has(platform)) {
  60. throw new Error(`[热更新打包] 平台 ${platform || '<unknown>'} 不是支持热更新的原生平台。`);
  61. }
  62. if (buildOptions?.md5Cache) {
  63. throw new Error('[热更新打包] 请关闭构建发布面板中的 MD5 Cache;AssetsManager Manifest 已负责文件版本校验。');
  64. }
  65. const normalizedUrl = normalizeRemoteUrl(remoteUrl);
  66. const normalizedVersion = normalizeVersion(version);
  67. const buildRoot = path.resolve(buildResult.dest);
  68. const dataRoot = await findNativeDataRoot(buildRoot);
  69. const mainScriptPath = path.join(dataRoot, 'main.js');
  70. await injectBootstrap(mainScriptPath);
  71. const projectInfo = await readProjectInfo(projectPath);
  72. const assetFiles = await collectPayloadFiles(dataRoot);
  73. const assets = {};
  74. let totalBytes = 0;
  75. for (const file of assetFiles) {
  76. const stat = await fs.promises.stat(file.absolutePath);
  77. const descriptor = {
  78. size: stat.size,
  79. md5: await calculateMd5(file.absolutePath),
  80. };
  81. if (path.extname(file.absolutePath).toLowerCase() === '.zip') {
  82. descriptor.compressed = true;
  83. }
  84. assets[encodeURI(file.relativePath)] = descriptor;
  85. totalBytes += stat.size;
  86. }
  87. const manifest = {
  88. packageUrl: normalizedUrl,
  89. remoteManifestUrl: new URL('project.manifest', normalizedUrl).toString(),
  90. remoteVersionUrl: new URL('version.manifest', normalizedUrl).toString(),
  91. version: normalizedVersion,
  92. engineVersion: projectInfo.creator?.version || '',
  93. assets,
  94. searchPaths: [],
  95. };
  96. const versionManifest = {
  97. packageUrl: manifest.packageUrl,
  98. remoteManifestUrl: manifest.remoteManifestUrl,
  99. remoteVersionUrl: manifest.remoteVersionUrl,
  100. version: manifest.version,
  101. engineVersion: manifest.engineVersion,
  102. };
  103. // Manifest 放入 data 根目录,Make 阶段会随原生包一起发布。
  104. const localManifestPath = path.join(dataRoot, 'project.manifest');
  105. await writeJsonAtomic(localManifestPath, manifest);
  106. await writeJsonAtomic(path.join(dataRoot, 'version.manifest'), versionManifest);
  107. // 每个版本独立输出,目录可以直接上传到面板中配置的 URL。
  108. const remotePackagePath = path.join(buildRoot, 'hot-update', normalizedVersion);
  109. await createRemotePackage({
  110. buildRoot,
  111. dataRoot,
  112. remotePackagePath,
  113. manifest,
  114. versionManifest,
  115. assetFiles,
  116. });
  117. return {
  118. version: normalizedVersion,
  119. localManifestPath,
  120. remotePackagePath,
  121. fileCount: assetFiles.length,
  122. totalBytes,
  123. };
  124. }
  125. function normalizeRemoteUrl(value) {
  126. const input = String(value || '').trim();
  127. let parsed;
  128. try {
  129. parsed = new URL(input);
  130. } catch {
  131. throw new Error(`[热更新打包] 热更新 URL 无效:${input || '<empty>'}`);
  132. }
  133. if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
  134. throw new Error('[热更新打包] 热更新 URL 仅支持 http:// 或 https://。');
  135. }
  136. parsed.hash = '';
  137. parsed.search = '';
  138. if (!parsed.pathname.endsWith('/')) {
  139. parsed.pathname += '/';
  140. }
  141. return parsed.toString();
  142. }
  143. function normalizeVersion(value) {
  144. const normalized = String(value || '').trim();
  145. if (!/^\d+(?:\.\d+){1,3}$/.test(normalized)) {
  146. throw new Error(`[热更新打包] 版本号无效:${normalized || '<empty>'}`);
  147. }
  148. return normalized;
  149. }
  150. async function findNativeDataRoot(buildRoot) {
  151. const candidates = [path.join(buildRoot, 'data'), path.join(buildRoot, 'assets')];
  152. for (const candidate of candidates) {
  153. if (await isDirectory(path.join(candidate, 'src')) && await isDirectory(path.join(candidate, 'assets'))) {
  154. return candidate;
  155. }
  156. }
  157. throw new Error(`[热更新打包] 在 ${buildRoot} 下找不到原生构建资源目录(data 或 assets)。`);
  158. }
  159. async function injectBootstrap(mainScriptPath) {
  160. let source;
  161. try {
  162. source = await fs.promises.readFile(mainScriptPath, 'utf8');
  163. } catch (error) {
  164. throw new Error(`[热更新打包] 无法读取 ${mainScriptPath}:${error.message}`);
  165. }
  166. if (source.includes(BOOTSTRAP_MARKER)) {
  167. return;
  168. }
  169. await writeTextAtomic(mainScriptPath, BOOTSTRAP_SCRIPT + source);
  170. }
  171. async function collectPayloadFiles(dataRoot) {
  172. const relativeFiles = [];
  173. for (const directory of ['src', 'assets', 'jsb-adapter']) {
  174. const absoluteDirectory = path.join(dataRoot, directory);
  175. if (await isDirectory(absoluteDirectory)) {
  176. await walkFiles(absoluteDirectory, dataRoot, relativeFiles);
  177. }
  178. }
  179. // Creator 3.8 将 application.js 放在 data 根目录,旧版生成器会漏掉它。
  180. const applicationScript = path.join(dataRoot, 'application.js');
  181. if (await isFile(applicationScript)) {
  182. relativeFiles.push({
  183. absolutePath: applicationScript,
  184. relativePath: 'application.js',
  185. });
  186. }
  187. relativeFiles.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
  188. return relativeFiles;
  189. }
  190. async function walkFiles(directory, root, output) {
  191. const entries = await fs.promises.readdir(directory, { withFileTypes: true });
  192. entries.sort((a, b) => a.name.localeCompare(b.name));
  193. for (const entry of entries) {
  194. if (entry.name.startsWith('.')) {
  195. continue;
  196. }
  197. const absolutePath = path.join(directory, entry.name);
  198. if (entry.isDirectory()) {
  199. await walkFiles(absolutePath, root, output);
  200. } else if (entry.isFile()) {
  201. output.push({
  202. absolutePath,
  203. relativePath: path.relative(root, absolutePath).replace(/\\/g, '/'),
  204. });
  205. }
  206. }
  207. }
  208. async function createRemotePackage({
  209. buildRoot,
  210. dataRoot,
  211. remotePackagePath,
  212. manifest,
  213. versionManifest,
  214. assetFiles,
  215. }) {
  216. assertPathInside(buildRoot, remotePackagePath);
  217. const stagingPath = path.join(buildRoot, 'hot-update', `.staging-${process.pid}-${Date.now()}`);
  218. assertPathInside(buildRoot, stagingPath);
  219. await fs.promises.mkdir(stagingPath, { recursive: true });
  220. try {
  221. for (const file of assetFiles) {
  222. const destination = path.join(stagingPath, ...file.relativePath.split('/'));
  223. await fs.promises.mkdir(path.dirname(destination), { recursive: true });
  224. await fs.promises.copyFile(file.absolutePath, destination);
  225. }
  226. await writeJsonAtomic(path.join(stagingPath, 'project.manifest'), manifest);
  227. await writeJsonAtomic(path.join(stagingPath, 'version.manifest'), versionManifest);
  228. await fs.promises.mkdir(path.dirname(remotePackagePath), { recursive: true });
  229. await fs.promises.rm(remotePackagePath, { recursive: true, force: true });
  230. await fs.promises.rename(stagingPath, remotePackagePath);
  231. } catch (error) {
  232. await fs.promises.rm(stagingPath, { recursive: true, force: true });
  233. throw error;
  234. }
  235. }
  236. function assertPathInside(parent, child) {
  237. const relative = path.relative(path.resolve(parent), path.resolve(child));
  238. if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
  239. throw new Error(`[热更新打包] 拒绝操作构建目录外的路径:${child}`);
  240. }
  241. }
  242. function calculateMd5(filePath) {
  243. return new Promise((resolve, reject) => {
  244. const hash = crypto.createHash('md5');
  245. const stream = fs.createReadStream(filePath);
  246. stream.on('error', reject);
  247. stream.on('data', (chunk) => hash.update(chunk));
  248. stream.on('end', () => resolve(hash.digest('hex')));
  249. });
  250. }
  251. async function readProjectInfo(projectPath) {
  252. const packagePath = path.join(projectPath, 'package.json');
  253. try {
  254. return JSON.parse(await fs.promises.readFile(packagePath, 'utf8'));
  255. } catch {
  256. return {};
  257. }
  258. }
  259. async function writeJsonAtomic(filePath, value) {
  260. await writeTextAtomic(filePath, `${JSON.stringify(value, null, 2)}\n`);
  261. }
  262. async function writeTextAtomic(filePath, content) {
  263. await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
  264. const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
  265. await fs.promises.writeFile(tempPath, content, 'utf8');
  266. await fs.promises.rename(tempPath, filePath);
  267. }
  268. async function isDirectory(target) {
  269. try {
  270. return (await fs.promises.stat(target)).isDirectory();
  271. } catch {
  272. return false;
  273. }
  274. }
  275. async function isFile(target) {
  276. try {
  277. return (await fs.promises.stat(target)).isFile();
  278. } catch {
  279. return false;
  280. }
  281. }
  282. module.exports = {
  283. BOOTSTRAP_MARKER,
  284. collectPayloadFiles,
  285. normalizeRemoteUrl,
  286. normalizeVersion,
  287. packageHotUpdate,
  288. };