verify-engine-natives.mjs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env node
  2. /**
  3. * 引擎原生模块自检 / 补装。
  4. *
  5. * 为什么需要:npm 对 optionalDependencies 的安装失败是**静默忽略**的。
  6. * 镜像里 `node-addon-require-builtin` 的平台包没装上时,`docker build` 依然成功,
  7. * 直到运行时才炸 `Cannot find module .../require_builtin.node`。
  8. * sharp / koffi / node-pty 同理,只是崩得晚一点。
  9. *
  10. * 用法(在 engine 目录,即含 node_modules 的那层):
  11. * node verify-engine-natives.mjs 只检查,缺失则退出码 1
  12. * node verify-engine-natives.mjs --fix 缺失的用官方源补装后再查
  13. * node verify-engine-natives.mjs --engine=/app/engine --fix
  14. *
  15. * 判据是"真实 require 一次",不是看文件存不存在 —— 后者会被残缺包骗过。
  16. */
  17. import { createRequire } from 'node:module'
  18. import fs from 'node:fs'
  19. import path from 'node:path'
  20. import { execFileSync } from 'node:child_process'
  21. const args = process.argv.slice(2)
  22. const opt = (name, fallback = '') => {
  23. const hit = args.find(a => a.startsWith(`--${name}=`))
  24. return hit ? hit.slice(name.length + 3) : fallback
  25. }
  26. const FIX = args.includes('--fix')
  27. const ROOT = path.resolve(opt('engine', process.cwd()))
  28. const REGISTRY = opt('registry', 'https://registry.npmjs.org')
  29. const require = createRequire(path.join(ROOT, 'package.json'))
  30. // 依赖链上真正会把引擎搞崩的几个;顺序按加载先后
  31. const MODULES = [
  32. { pkg: 'node-addon-require-builtin', why: '引擎 loader 的底层 require 钩子', probe: m => typeof m.requireBuiltin === 'function' },
  33. { pkg: 'sharp', why: '图片处理', probe: m => typeof m === 'function' },
  34. { pkg: 'koffi', why: 'FFI', probe: m => !!m },
  35. { pkg: 'node-pty', why: '终端', probe: m => !!m }
  36. ]
  37. function libcTag () {
  38. if (process.platform !== 'linux') return ''
  39. try {
  40. const report = process.report?.getReport?.()
  41. return report?.header?.glibcVersionRuntime ? 'gnu' : 'musl'
  42. } catch {
  43. return 'gnu'
  44. }
  45. }
  46. /** 从主包的 optionalDependencies 里挑出当前平台的包名(版本跟随主包) */
  47. function platformPackageOf (pkgName) {
  48. let meta
  49. try {
  50. meta = JSON.parse(fs.readFileSync(path.join(ROOT, 'node_modules', pkgName, 'package.json'), 'utf8'))
  51. } catch {
  52. return null
  53. }
  54. const deps = meta.optionalDependencies || {}
  55. const stem = `${process.platform}-${process.arch}`
  56. const libc = libcTag()
  57. const candidates = Object.entries(deps).filter(([k]) => k.includes(stem))
  58. // linux 要区分 glibc / musl:musl 包名里带 linuxmusl 或 -musl
  59. const filtered = candidates.filter(([k]) => {
  60. if (process.platform !== 'linux') return true
  61. const isMusl = /musl/.test(k)
  62. return libc === 'musl' ? isMusl : !isMusl
  63. })
  64. const hit = filtered[0] || candidates[0]
  65. return hit ? { name: hit[0], version: hit[1] } : null
  66. }
  67. function tryLoad (pkg) {
  68. try {
  69. const mod = require(pkg)
  70. return { mod, error: null }
  71. } catch (error) {
  72. return { mod: null, error }
  73. }
  74. }
  75. let failed = []
  76. console.log(`引擎原生模块自检:${ROOT}`)
  77. console.log(`平台 ${process.platform}-${process.arch}${libcTag() ? `-${libcTag()}` : ''}|node ${process.versions.node}\n`)
  78. for (const item of MODULES) {
  79. const { mod, error } = tryLoad(item.pkg)
  80. if (mod && (!item.probe || item.probe(mod))) {
  81. console.log(` ✓ ${item.pkg.padEnd(30)} ${item.why}`)
  82. continue
  83. }
  84. const reason = error ? String(error.message).split('\n')[0] : '加载成功但导出不符合预期'
  85. console.log(` ✗ ${item.pkg.padEnd(30)} ${reason}`)
  86. failed.push({ ...item, error })
  87. }
  88. if (!failed.length) {
  89. console.log('\n全部就绪')
  90. process.exit(0)
  91. }
  92. console.log(`\n${failed.length} 个模块不可用`)
  93. if (!FIX) {
  94. console.log('加 --fix 可按平台补装缺失包(需要能访问 npm registry)')
  95. process.exit(1)
  96. }
  97. for (const item of failed) {
  98. const plat = platformPackageOf(item.pkg)
  99. if (!plat) {
  100. console.log(` ! ${item.pkg}:读不到 optionalDependencies,跳过自动补装`)
  101. continue
  102. }
  103. console.log(`\n补装 ${plat.name}@${plat.version}(registry ${REGISTRY})`)
  104. try {
  105. execFileSync('npm', [
  106. 'install', '--no-save', '--force', '--no-audit', '--no-fund',
  107. `--registry=${REGISTRY}`,
  108. `${plat.name}@${plat.version}`
  109. ], { cwd: ROOT, stdio: 'inherit' })
  110. } catch (err) {
  111. console.log(` ! 补装失败:${err.message.split('\n')[0]}`)
  112. }
  113. }
  114. // 补装后复查,只有真的能 require 才算过
  115. let stillBad = 0
  116. for (const item of MODULES) {
  117. const { mod } = tryLoad(item.pkg)
  118. const ok = mod && (!item.probe || item.probe(mod))
  119. console.log(` ${ok ? '✓' : '✗'} ${item.pkg}`)
  120. if (!ok) stillBad++
  121. }
  122. process.exit(stillBad ? 1 : 0)