From 87c04aa87e1096686772fb87aa9f561b83738f47 Mon Sep 17 00:00:00 2001 From: jdalton Date: Wed, 1 Apr 2026 19:24:54 -0400 Subject: [PATCH] chore(build): remove dead code - Delete esbuild-plugin-dead-code-elimination.mjs (unused plugin) - Delete packages/cli/scripts/esbuild.config.mjs (broken orphan referencing non-existent esbuild.cli.config.mjs) - Remove dead-code-elimination export from build-infra/package.json - Remove socketPackages / resolvePackageSubpath / resolve-socket-packages plugin from esbuild.cli.build.mjs (socketPackages is always empty {}) - Remove INLINED_LEGACY_BUILD constant (unused) - Update build-infra README to remove dead code elimination docs --- packages/build-infra/README.md | 38 +---- .../esbuild-plugin-dead-code-elimination.mjs | 156 ------------------ packages/build-infra/package.json | 1 - packages/cli/.config/esbuild.cli.build.mjs | 87 +--------- packages/cli/scripts/constants/env.mjs | 1 - packages/cli/scripts/esbuild.config.mjs | 57 ------- 6 files changed, 7 insertions(+), 333 deletions(-) delete mode 100644 packages/build-infra/lib/esbuild-plugin-dead-code-elimination.mjs delete mode 100644 packages/cli/scripts/esbuild.config.mjs diff --git a/packages/build-infra/README.md b/packages/build-infra/README.md index ec830a275..edcb1cbe4 100644 --- a/packages/build-infra/README.md +++ b/packages/build-infra/README.md @@ -14,10 +14,10 @@ Shared build infrastructure utilities for Socket CLI. Provides esbuild plugins, │ │ Unicode │ │ API Client │ │ SHA256 │ │ │ │ Transform │ │ + Download │ │ Content │ │ │ │ │ │ │ │ Hashing │ │ -│ ├───────────────┤ ├──────────────┤ └──────────┤ │ -│ │ Dead Code │ │ Asset Cache │ │ Skip │ │ -│ │ Elimination │ │ (1hr TTL) │ │ Regen │ │ -│ └───────────────┘ └──────────────┘ └──────────┘ │ +│ └───────────────┘ ├──────────────┤ └──────────┤ │ +│ │ Asset Cache │ │ Skip │ │ +│ │ (1hr TTL) │ │ Regen │ │ +│ └──────────────┘ └──────────┘ │ │ │ │ Helpers │ │ ┌───────────────────────────────────────────────────────┐ │ @@ -72,30 +72,6 @@ export default { - Replaces unsupported patterns with `/(?:)/` (no-op) - Removes `/u` and `/v` flags after transformation -#### `deadCodeEliminationPlugin()` - -Removes unreachable code branches based on constant boolean conditions. Simplifies bundled output by eliminating dead paths. - -```javascript -import { deadCodeEliminationPlugin } from 'build-infra/lib/esbuild-plugin-dead-code-elimination' - -export default { - plugins: [deadCodeEliminationPlugin()], -} -``` - -**Transformations:** - -- `if (false) { deadCode() }` → `` (removed) -- `if (true) { liveCode() } else { deadCode() }` → `liveCode()` (unwrapped) -- `if (false) { } else { liveCode() }` → `liveCode()` (unwrapped) - -**Implementation:** - -- Uses Babel parser + MagicString for safe AST transformations -- Only processes `.js` files in esbuild output -- Applies transformations in reverse order to maintain positions - ### esbuild Helpers #### `IMPORT_META_URL_BANNER` @@ -296,10 +272,9 @@ ensureOutputDir('/path/to/output/file.js') ### esbuild Configuration ```javascript -// .config/esbuild.config.mjs +// .config/esbuild.cli.build.mjs import { IMPORT_META_URL_BANNER } from 'build-infra/lib/esbuild-helpers' import { unicodeTransformPlugin } from 'build-infra/lib/esbuild-plugin-unicode-transform' -import { deadCodeEliminationPlugin } from 'build-infra/lib/esbuild-plugin-dead-code-elimination' export default { entryPoints: ['src/cli.mts'], @@ -317,7 +292,7 @@ export default { 'import.meta.url': '__importMetaUrl', }, - plugins: [unicodeTransformPlugin(), deadCodeEliminationPlugin()], + plugins: [unicodeTransformPlugin()], } ``` @@ -439,7 +414,6 @@ Assets are cached per tag to avoid re-downloading across builds. **Consumers:** - `packages/cli/.config/esbuild.cli.build.mjs` - Main CLI bundle config -- `packages/cli/.config/esbuild.inject.config.mjs` - Shadow npm inject config - `packages/cli/scripts/download-assets.mjs` - Unified asset downloader - `packages/cli/scripts/sea-build-utils/builder.mjs` - SEA binary builder diff --git a/packages/build-infra/lib/esbuild-plugin-dead-code-elimination.mjs b/packages/build-infra/lib/esbuild-plugin-dead-code-elimination.mjs deleted file mode 100644 index ac2a58101..000000000 --- a/packages/build-infra/lib/esbuild-plugin-dead-code-elimination.mjs +++ /dev/null @@ -1,156 +0,0 @@ -/** - * @fileoverview esbuild plugin for dead code elimination. - * - * Removes unreachable code branches like `if (false) { ... }` and `if (true) { } else { ... }`. - * Uses Babel parser + magic-string for safe AST-based transformations. - * - * @example - * import { deadCodeEliminationPlugin } from 'build-infra/lib/esbuild-plugin-dead-code-elimination' - * - * export default { - * plugins: [deadCodeEliminationPlugin()], - * } - */ - -import { parse } from '@babel/parser' -import { default as traverseImport } from '@babel/traverse' -import MagicString from 'magic-string' - -const traverse = - typeof traverseImport === 'function' ? traverseImport : traverseImport.default - -/** - * Evaluate a test expression to determine if it's a constant boolean. - * - * @param {import('@babel/types').Node} test - Test expression node - * @returns {boolean | null} true/false if constant, null if dynamic - */ -function evaluateTest(test) { - if (test.type === 'BooleanLiteral') { - return test.value - } - if (test.type === 'UnaryExpression' && test.operator === '!') { - const argValue = evaluateTest(test.argument) - return argValue !== null ? !argValue : null - } - return null -} - -/** - * Remove dead code branches from JavaScript code. - * - * @param {string} code - JavaScript code to transform - * @returns {string} Transformed code with dead branches removed - */ -function removeDeadCode(code) { - const ast = parse(code, { - sourceType: 'module', - plugins: [], - }) - - const s = new MagicString(code) - const nodesToRemove = [] - - traverse(ast, { - IfStatement(path) { - const testValue = evaluateTest(path.node.test) - - if (testValue === false) { - // if (false) { ... } [else { ... }]. - // Remove entire if statement, keep else block if present. - if (path.node.alternate) { - // Replace if statement with else block content. - const { alternate } = path.node - if (alternate.type === 'BlockStatement') { - // Remove braces from else block. - const start = alternate.start + 1 - const end = alternate.end - 1 - const elseContent = code.slice(start, end) - nodesToRemove.push({ - start: path.node.start, - end: path.node.end, - replacement: elseContent, - }) - } else { - // Single statement else. - nodesToRemove.push({ - start: path.node.start, - end: path.node.end, - replacement: code.slice(alternate.start, alternate.end), - }) - } - } else { - // No else block, remove entire if statement. - nodesToRemove.push({ - start: path.node.start, - end: path.node.end, - replacement: '', - }) - } - } else if (testValue === true) { - // if (true) { ... } [else { ... }]. - // Keep consequent, remove else block. - const { consequent } = path.node - if (consequent.type === 'BlockStatement') { - // Remove braces from consequent block. - const start = consequent.start + 1 - const end = consequent.end - 1 - const consequentContent = code.slice(start, end) - nodesToRemove.push({ - start: path.node.start, - end: path.node.end, - replacement: consequentContent, - }) - } else { - // Single statement consequent. - nodesToRemove.push({ - start: path.node.start, - end: path.node.end, - replacement: code.slice(consequent.start, consequent.end), - }) - } - } - }, - }) - - // Apply replacements in reverse order to maintain correct positions. - for (const node of nodesToRemove.reverse()) { - s.overwrite(node.start, node.end, node.replacement) - } - - return s.toString() -} - -/** - * Create esbuild plugin for dead code elimination. - * - * @returns {import('esbuild').Plugin} esbuild plugin - */ -export function deadCodeEliminationPlugin() { - return { - name: 'dead-code-elimination', - setup(build) { - build.onEnd(result => { - const outputs = result.outputFiles - if (!outputs || !outputs.length) { - return - } - - for (const output of outputs) { - // Only process JavaScript files. - if (!output.path.endsWith('.js')) { - continue - } - - let content = output.text - - // Remove dead code branches. - content = removeDeadCode(content) - - // Update the output content. - output.contents = Buffer.from(content, 'utf8') - } - }) - }, - } -} diff --git a/packages/build-infra/package.json b/packages/build-infra/package.json index 36c3380bc..fbcf59474 100644 --- a/packages/build-infra/package.json +++ b/packages/build-infra/package.json @@ -6,7 +6,6 @@ "type": "module", "exports": { "./lib/esbuild-helpers": "./lib/esbuild-helpers.mjs", - "./lib/esbuild-plugin-dead-code-elimination": "./lib/esbuild-plugin-dead-code-elimination.mjs", "./lib/esbuild-plugin-unicode-transform": "./lib/esbuild-plugin-unicode-transform.mjs", "./lib/extraction-cache": "./lib/extraction-cache.mjs", "./lib/github-error-utils": "./lib/github-error-utils.mjs", diff --git a/packages/cli/.config/esbuild.cli.build.mjs b/packages/cli/.config/esbuild.cli.build.mjs index 254283947..87070e7c4 100644 --- a/packages/cli/.config/esbuild.cli.build.mjs +++ b/packages/cli/.config/esbuild.cli.build.mjs @@ -4,7 +4,7 @@ * esbuild is much faster than Rollup and doesn't have template literal corruption issues. */ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -46,50 +46,6 @@ function findSocketLibPath(importerPath) { return null } -// CLI build must use published packages only - no local sibling directories. -// This ensures the CLI is properly isolated and doesn't depend on local dev setup. -const socketPackages = {} - -// Resolve subpath from package.json exports. -function resolvePackageSubpath(packagePath, subpath) { - try { - const pkgJsonPath = path.join(packagePath, 'package.json') - const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) - const exports = pkgJson.exports || {} - - // Try exact export match. - const exportKey = subpath === '.' ? '.' : `./${subpath}` - if (exports[exportKey]) { - const exportValue = exports[exportKey] - // Handle conditional exports. - if (typeof exportValue === 'object' && exportValue.default) { - return path.join(packagePath, exportValue.default) - } - // Handle simple string exports. - if (typeof exportValue === 'string') { - return path.join(packagePath, exportValue) - } - } - - // Fallback: try conventional paths. - const distPath = path.join(packagePath, 'dist', subpath) - if (existsSync(`${distPath}.js`)) { - return `${distPath}.js` - } - if (existsSync(`${distPath}.mjs`)) { - return `${distPath}.mjs` - } - if (existsSync(path.join(distPath, 'index.js'))) { - return path.join(distPath, 'index.js') - } - if (existsSync(path.join(distPath, 'index.mjs'))) { - return path.join(distPath, 'index.mjs') - } - } catch {} - - return null -} - const config = { entryPoints: [path.join(rootPath, 'src/cli-dispatch.mts')], bundle: true, @@ -148,47 +104,6 @@ const config = { // Environment variable replacement must run AFTER unicode transform. envVarReplacementPlugin(inlinedEnvVars), unicodeTransformPlugin(), - { - name: 'resolve-socket-packages', - setup(build) { - // Resolve local Socket packages with subpath exports. - for (const [packageName, packagePath] of Object.entries( - socketPackages, - )) { - // Handle package root imports. - build.onResolve( - { filter: new RegExp(`^${packageName.replace('/', '\\/')}$`) }, - () => { - if (!existsSync(packagePath)) { - return null - } - const resolved = resolvePackageSubpath(packagePath, '.') - if (resolved) { - return { path: resolved } - } - return null - }, - ) - - // Handle subpath imports. - build.onResolve( - { filter: new RegExp(`^${packageName.replace('/', '\\/')}\\/`) }, - args => { - if (!existsSync(packagePath)) { - return null - } - const subpath = args.path.slice(packageName.length + 1) - const resolved = resolvePackageSubpath(packagePath, subpath) - if (resolved) { - return { path: resolved } - } - return null - }, - ) - } - }, - }, - { name: 'resolve-socket-lib-internals', setup(build) { diff --git a/packages/cli/scripts/constants/env.mjs b/packages/cli/scripts/constants/env.mjs index e1a20e1ab..59d47e8c8 100644 --- a/packages/cli/scripts/constants/env.mjs +++ b/packages/cli/scripts/constants/env.mjs @@ -6,7 +6,6 @@ export const INLINED_COANA_VERSION = export const INLINED_CYCLONEDX_CDXGEN_VERSION = 'INLINED_CYCLONEDX_CDXGEN_VERSION' export const INLINED_HOMEPAGE = 'INLINED_HOMEPAGE' -export const INLINED_LEGACY_BUILD = 'INLINED_LEGACY_BUILD' export const INLINED_NAME = 'INLINED_NAME' export const INLINED_PUBLISHED_BUILD = 'INLINED_PUBLISHED_BUILD' diff --git a/packages/cli/scripts/esbuild.config.mjs b/packages/cli/scripts/esbuild.config.mjs deleted file mode 100644 index ef6277dc9..000000000 --- a/packages/cli/scripts/esbuild.config.mjs +++ /dev/null @@ -1,57 +0,0 @@ -/** - * esbuild build script for Socket CLI. - */ - -import { readFileSync, writeFileSync } from 'node:fs' -import { brotliCompressSync } from 'node:zlib' - -import { build } from 'esbuild' - -import { getDefaultLogger } from '@socketsecurity/lib/logger' - -import config from './esbuild.cli.config.mjs' - -const logger = getDefaultLogger() -logger.log('Building Socket CLI with esbuild...\n') - -try { - const result = await build(config) - - logger.log('✓ Build completed successfully') - logger.log(`✓ Output: ${config.outfile}`) - - if (result.metafile) { - const outputSize = Object.values(result.metafile.outputs)[0]?.bytes - if (outputSize) { - logger.log(`✓ Bundle size: ${(outputSize / 1024 / 1024).toFixed(2)} MB`) - } - } - - // Compress with brotli. - logger.log('\n🗜️ Compressing with brotli...') - const jsCode = readFileSync(config.outfile) - const compressed = brotliCompressSync(jsCode, { - params: { - [require('node:zlib').constants.BROTLI_PARAM_QUALITY]: 11, - - [require('node:zlib').constants.BROTLI_PARAM_SIZE_HINT]: jsCode.length, - }, - }) - - const bzPath = `${config.outfile}.bz` - writeFileSync(bzPath, compressed) - - const originalSize = jsCode.length / 1024 / 1024 - const compressedSize = compressed.length / 1024 / 1024 - const compressionRatio = ((compressed.length / jsCode.length) * 100).toFixed( - 1, - ) - - logger.log(`✓ Compressed: ${bzPath}`) - logger.log(`✓ Original size: ${originalSize.toFixed(2)} MB`) - logger.log(`✓ Compressed size: ${compressedSize.toFixed(2)} MB`) - logger.log(`✓ Compression ratio: ${compressionRatio}%`) -} catch (error) { - logger.error('Build failed:', error) - process.exitCode = 1 -}