蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测打包工具矩阵、package.json 构建配置校验、签名参数脱敏及 SHA-512 差分更新模拟

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-electron-packaging-and-distribution.mjs
explore-electron-packaging-and-distribution.mjs141 行
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

function casePackagingToolsMatrixAudit() {
  const tools = {
    'electron-builder': { autoUpdate: true, crossPlatform: true, bundledBuildTool: false, productionReady: true },
    'electron-packager': { autoUpdate: false, crossPlatform: true, bundledBuildTool: false, lightweight: true },
    'electron-forge': { autoUpdate: true, crossPlatform: true, bundledBuildTool: true, quickStart: true },
  };
  const actual = {
    toolCount: Object.keys(tools).length,
    builderAutoUpdate: tools['electron-builder'].autoUpdate,
    packagerAutoUpdate: tools['electron-packager'].autoUpdate,
    forgeBundledBuild: tools['electron-forge'].bundledBuildTool,
  };
  const expected = {
    toolCount: 3,
    builderAutoUpdate: true,
    packagerAutoUpdate: false,
    forgeBundledBuild: true,
  };
  return { name: 'packaging_tools_matrix_audit', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

function caseBuilderConfigAndPlatformAssets() {
  const buildConfig = {
    appId: 'com.example.myapp',
    productName: 'MyElectronApp',
    directories: { output: 'dist' },
    files: ['**/*'],
    extraResources: ['assets/'],
    extraFiles: ['LICENSE.txt'],
    mac: { category: 'public.app-category.utilities', icon: 'build/icon.icns', target: ['dmg', 'pkg'] },
    win: { target: 'nsis', icon: 'build/icon.ico' },
    linux: { target: ['AppImage', 'deb'], icon: 'build/icon.png' },
  };

  const validAppId = /^[a-z0-9]+(\.[a-z0-9-]+)+$/.test(buildConfig.appId);
  const iconExtensions = {
    win: path.extname(buildConfig.win.icon),
    mac: path.extname(buildConfig.mac.icon),
    linux: path.extname(buildConfig.linux.icon),
  };

  const actual = {
    validAppId,
    outputDir: buildConfig.directories.output,
    iconExtensions,
    winTarget: buildConfig.win.target,
    linuxTargets: buildConfig.linux.target,
    hasExtraResources: buildConfig.extraResources.includes('assets/'),
  };
  const expected = {
    validAppId: true,
    outputDir: 'dist',
    iconExtensions: { win: '.ico', mac: '.icns', linux: '.png' },
    winTarget: 'nsis',
    linuxTargets: ['AppImage', 'deb'],
    hasExtraResources: true,
  };
  return { name: 'builder_config_and_platform_assets', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

function caseCodeSigningAndNotarizationContract() {
  const winSignArgs = ['electron-builder', '--win', '--csc-link', 'certs/app.pfx', '--csc-key-password', 'REDACTED_ENV_SECRET'];
  const redactArgs = (args) =>
    args.map((v, i) => (args[i - 1] === '--csc-key-password' ? '***' : v));
  const safeLog = redactArgs(winSignArgs);

  const macCrossCompileRule = {
    canSignMacOnLinux: false,
    requiresMacOsHostForSigning: true,
    notarizationRequiredForGatekeeper: true,
  };

  const actual = {
    pfxExtension: path.extname(winSignArgs[3]),
    passwordRedactedInLog: safeLog[5] === '***',
    canSignMacOnLinux: macCrossCompileRule.canSignMacOnLinux,
    notarizationRequired: macCrossCompileRule.notarizationRequiredForGatekeeper,
  };
  const expected = {
    pfxExtension: '.pfx',
    passwordRedactedInLog: true,
    canSignMacOnLinux: false,
    notarizationRequired: true,
  };
  return { name: 'code_signing_and_notarization_contract', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
}

async function caseUpdaterManifestAndDeltaVerification() {
  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'electron-pkg-'));
  try {
    const v1Blocks = [Buffer.alloc(1024, 0x41), Buffer.alloc(1024, 0x42), Buffer.alloc(1024, 0x43), Buffer.alloc(1024, 0x44)];
    const v2Blocks = [v1Blocks[0], v1Blocks[1], Buffer.alloc(1024, 0x58), v1Blocks[3]];
    const v2Payload = Buffer.concat(v2Blocks);
    const v2File = path.join(tmpDir, 'MyElectronApp-1.0.2.exe');
    await fs.writeFile(v2File, v2Payload);

    const fileBytes = await fs.readFile(v2File);
    const sha512Base64 = crypto.createHash('sha512').update(fileBytes).digest('base64');
    const blockHash = (b) => crypto.createHash('sha256').update(b).digest('hex');
    const changedBlocks = v2Blocks.filter((b, idx) => blockHash(b) !== blockHash(v1Blocks[idx]));
    const deltaBytes = changedBlocks.reduce((s, b) => s + b.length, 0);

    const events = [];
    events.push('check-for-updates', 'update-available', 'update-downloaded', 'quit-and-install');

    const actual = {
      fullBytes: fileBytes.length,
      deltaBytes,
      bandwidthSavedRatio: Number(((fileBytes.length - deltaBytes) / fileBytes.length).toFixed(2)),
      sha512Length: sha512Base64.length,
      sha512MatchesSelf: crypto.createHash('sha512').update(v2Payload).digest('base64') === sha512Base64,
      lifecycleEvents: events,
    };
    const expected = {
      fullBytes: 4096,
      deltaBytes: 1024,
      bandwidthSavedRatio: 0.75,
      sha512Length: 88,
      sha512MatchesSelf: true,
      lifecycleEvents: ['check-for-updates', 'update-available', 'update-downloaded', 'quit-and-install'],
    };
    return { name: 'updater_manifest_and_delta_verification', passed: JSON.stringify(actual) === JSON.stringify(expected), expected, actual };
  } finally {
    await fs.rm(tmpDir, { recursive: true, force: true });
  }
}

const cases = [
  casePackagingToolsMatrixAudit(),
  caseBuilderConfigAndPlatformAssets(),
  caseCodeSigningAndNotarizationContract(),
  await caseUpdaterManifestAndDeltaVerification(),
];

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/electron-electron-packaging-and-distribution-lab/explore-electron-packaging-and-distribution.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-electron-packaging-and-distribution.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Electron

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a1081.zip

下载课程关联工程包:Electron

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1084.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习