-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathesbuild-shared.mjs
More file actions
208 lines (186 loc) · 7.09 KB
/
esbuild-shared.mjs
File metadata and controls
208 lines (186 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/**
* Shared esbuild utilities for Socket CLI builds.
* Contains helpers for environment variable inlining and build metadata.
*/
import { execSync } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const rootPath = path.join(__dirname, '..')
/**
* Create a standard index loader config.
* @param {Object} options - Configuration options
* @param {string} options.entryPoint - Path to entry point file
* @param {string} options.outfile - Path to output file
* @param {boolean} [options.minify=false] - Whether to minify output
* @returns {Object} esbuild configuration object
*/
export function createIndexConfig({ entryPoint, minify = false, outfile }) {
// Get inlined environment variables for build-time constant replacement.
const inlinedEnvVars = getInlinedEnvVars()
const config = {
banner: {
js: '#!/usr/bin/env node',
},
bundle: true,
entryPoints: [entryPoint],
external: [],
format: 'cjs',
outfile,
platform: 'node',
target: 'node18',
treeShaking: true,
// Define environment variables for inlining.
define: {
'process.env.NODE_ENV': '"production"',
...createDefineEntries(inlinedEnvVars),
},
// Add plugin for post-bundle env var replacement.
plugins: [envVarReplacementPlugin(inlinedEnvVars)],
// Plugin needs to transform output.
write: false,
}
if (minify) {
config.minify = true
} else {
config.minifyWhitespace = true
config.minifyIdentifiers = true
config.minifySyntax = false
}
return config
}
/**
* Helper to create both dot and bracket notation define keys.
* This ensures esbuild can replace both forms of process.env access.
*/
export function createDefineEntries(envVars) {
const entries = {}
for (const [key, value] of Object.entries(envVars)) {
// Dot notation: process.env.KEY
entries[`process.env.${key}`] = value
// Bracket notation: process.env["KEY"]
entries[`process.env["${key}"]`] = value
}
return entries
}
/**
* esbuild plugin to replace env vars after bundling (handles mangled identifiers).
* This is necessary because esbuild's define doesn't catch all forms after minification.
*/
export function envVarReplacementPlugin(envVars) {
return {
name: 'env-var-replacement',
setup(build) {
build.onEnd(result => {
const outputs = result.outputFiles
if (!outputs || outputs.length === 0) {
return
}
for (const output of outputs) {
let content = output.text
// Replace all forms of process.env["KEY"] access, even with mangled identifiers.
// Pattern: <anything>.env["KEY"] where <anything> could be "import_node_process21.default" etc.
for (const [key, value] of Object.entries(envVars)) {
// Match: <identifier>.env["KEY"] or <identifier>.env['KEY']
const pattern = new RegExp(`(\\w+\\.)+env\\["${key}"\\]`, 'g')
const singleQuotePattern = new RegExp(
`(\\w+\\.)+env\\['${key}'\\]`,
'g',
)
// Replace with the actual value (already JSON.stringified).
content = content.replace(pattern, value)
content = content.replace(singleQuotePattern, value)
}
// Update the output content.
output.contents = Buffer.from(content, 'utf8')
}
})
},
}
}
/**
* Get all inlined environment variables with their values.
* This reads package.json metadata and computes derived values.
*
* @returns {Record<string, string>} Object with env var names as keys and JSON-stringified values
*/
export function getInlinedEnvVars() {
// Read package.json for metadata.
const packageJson = JSON.parse(
readFileSync(path.join(rootPath, 'package.json'), 'utf-8'),
)
// Read version from socket package (the published package).
const socketPackageJson = JSON.parse(
readFileSync(
path.join(rootPath, '../package-builder/build/socket/package.json'),
'utf-8',
),
)
// Get current git commit hash.
let gitHash = ''
try {
gitHash = execSync('git rev-parse --short HEAD', {
cwd: rootPath,
encoding: 'utf-8',
}).trim()
} catch {}
// Get dependency versions from package.json devDependencies.
const synpVersion = packageJson.devDependencies?.['synp'] || ''
// Get external tool versions from external-tools.json.
const externalTools = JSON.parse(
readFileSync(path.join(rootPath, 'external-tools.json'), 'utf-8'),
)
function getExternalToolVersion(key, field = 'version') {
const tool = externalTools[key]
if (!tool) {
throw new Error(
`External tool "${key}" not found in external-tools.json. Please add it to the configuration.`,
)
}
const value = tool[field]
if (!value) {
throw new Error(
`External tool "${key}" is missing required field "${field}" in external-tools.json.`,
)
}
return value
}
const cdxgenVersion = getExternalToolVersion('@cyclonedx/cdxgen')
const coanaVersion = getExternalToolVersion('@coana-tech/cli')
const pyCliVersion = getExternalToolVersion('socketsecurity')
const pythonBuildTag = getExternalToolVersion('python', 'buildTag')
const pythonVersion = getExternalToolVersion('python')
const sfwVersion = getExternalToolVersion('sfw')
const socketPatchVersion = getExternalToolVersion('socket-patch')
// Build-time constants that can be overridden by environment variables.
const publishedBuild =
process.env['INLINED_SOCKET_CLI_PUBLISHED_BUILD'] === '1'
const sentryBuild = process.env['INLINED_SOCKET_CLI_SENTRY_BUILD'] === '1'
// Compute version hash (matches Rollup implementation).
const randUuidSegment = randomUUID().split('-')[0]
const versionHash = `${packageJson.version}:${gitHash}:${randUuidSegment}${
publishedBuild ? '' : ':dev'
}`
// Return all environment variables as JSON-stringified values.
return {
INLINED_SOCKET_CLI_VERSION: JSON.stringify(socketPackageJson.version),
INLINED_SOCKET_CLI_VERSION_HASH: JSON.stringify(versionHash),
INLINED_SOCKET_CLI_NAME: JSON.stringify(packageJson.name),
INLINED_SOCKET_CLI_HOMEPAGE: JSON.stringify(packageJson.homepage),
INLINED_SOCKET_CLI_CDXGEN_VERSION: JSON.stringify(cdxgenVersion),
INLINED_SOCKET_CLI_COANA_VERSION: JSON.stringify(coanaVersion),
INLINED_SOCKET_CLI_CYCLONEDX_CDXGEN_VERSION: JSON.stringify(cdxgenVersion),
INLINED_SOCKET_CLI_PYCLI_VERSION: JSON.stringify(pyCliVersion),
INLINED_SOCKET_CLI_SFW_VERSION: JSON.stringify(sfwVersion),
INLINED_SOCKET_CLI_SOCKET_PATCH_VERSION: JSON.stringify(socketPatchVersion),
INLINED_SOCKET_CLI_SYNP_VERSION: JSON.stringify(synpVersion),
INLINED_SOCKET_CLI_PUBLISHED_BUILD: JSON.stringify(
publishedBuild ? '1' : '',
),
INLINED_SOCKET_CLI_SENTRY_BUILD: JSON.stringify(sentryBuild ? '1' : ''),
INLINED_SOCKET_CLI_PYTHON_VERSION: JSON.stringify(pythonVersion),
INLINED_SOCKET_CLI_PYTHON_BUILD_TAG: JSON.stringify(pythonBuildTag),
}
}