obfuscate-dist.mjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { readdir, readFile, stat, writeFile } from 'node:fs/promises'
  2. import { isAbsolute, join, resolve } from 'node:path'
  3. import JavaScriptObfuscator from 'javascript-obfuscator'
  4. const distDir = process.env.FILE_VIEWER_DIST_DIR
  5. ? resolve(process.env.FILE_VIEWER_DIST_DIR)
  6. : join(process.cwd(), 'dist')
  7. const largeBundleLimit = Number(process.env.FILE_VIEWER_OBFUSCATE_LARGE_LIMIT || 1_000_000)
  8. const requestedTargets = process.argv.slice(2)
  9. const targets = requestedTargets.map(target => isAbsolute(target) ? target : join(distDir, target))
  10. const skippedGeneratedAssetRE = /[/\\]wasm[/\\]cad[/\\].+\.(mjs|js)$/
  11. async function collectFiles(dir) {
  12. const entries = await readdir(dir)
  13. for (const entry of entries) {
  14. const filePath = join(dir, entry)
  15. const fileStat = await stat(filePath)
  16. if (fileStat.isDirectory()) {
  17. await collectFiles(filePath)
  18. } else if (/\.(mjs|js)$/.test(entry)) {
  19. targets.push(filePath)
  20. }
  21. }
  22. }
  23. if (!requestedTargets.length) {
  24. await collectFiles(distDir)
  25. }
  26. for (const filePath of targets) {
  27. if (!requestedTargets.length && skippedGeneratedAssetRE.test(filePath)) {
  28. console.log(`kept generated wasm asset ${filePath.replace(`${process.cwd()}/`, '')}`)
  29. continue
  30. }
  31. let source
  32. try {
  33. source = await readFile(filePath, 'utf8')
  34. } catch (error) {
  35. if (error?.code === 'ENOENT') {
  36. console.warn(`skipped missing ${filePath.replace(`${process.cwd()}/`, '')}`)
  37. continue
  38. }
  39. throw error
  40. }
  41. const isLargeBundle = source.length > largeBundleLimit
  42. if (!requestedTargets.length && isLargeBundle) {
  43. console.log(`kept minified large bundle ${filePath.replace(`${process.cwd()}/`, '')}`)
  44. continue
  45. }
  46. const result = JavaScriptObfuscator.obfuscate(source, {
  47. compact: true,
  48. controlFlowFlattening: false,
  49. deadCodeInjection: false,
  50. identifierNamesGenerator: 'mangled',
  51. ignoreImports: true,
  52. renameGlobals: false,
  53. selfDefending: false,
  54. simplify: true,
  55. sourceMap: false,
  56. splitStrings: false,
  57. // Explicit large-target obfuscation keeps the safer low-memory settings.
  58. stringArray: !isLargeBundle,
  59. stringArrayEncoding: [],
  60. stringArrayThreshold: isLargeBundle ? 0 : 0.2,
  61. target: 'browser',
  62. unicodeEscapeSequence: false
  63. })
  64. await writeFile(filePath, result.getObfuscatedCode(), 'utf8')
  65. console.log(`obfuscated ${filePath.replace(`${process.cwd()}/`, '')}`)
  66. }