-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathbuild.mjs
More file actions
285 lines (252 loc) · 7.37 KB
/
build.mjs
File metadata and controls
285 lines (252 loc) · 7.37 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* Build script for Socket CLI.
* Options: --quiet, --verbose, --force, --watch
*/
import { copyFileSync } from 'node:fs'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { WIN32 } from '@socketsecurity/lib/constants/platform'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { spawn } from '@socketsecurity/lib/spawn'
const logger = getDefaultLogger()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const packageRoot = path.resolve(__dirname, '..')
const repoRoot = path.resolve(__dirname, '../../..')
// Node options for memory allocation.
const NODE_MEMORY_FLAGS = ['--max-old-space-size=8192']
// Simple CLI helpers without registry dependencies.
const isQuiet = () => process.argv.includes('--quiet')
const isVerbose = () => process.argv.includes('--verbose')
const log = {
info: msg => logger.info(msg),
step: msg => logger.step(msg),
success: msg => logger.success(msg),
error: msg => logger.error(msg),
}
const printHeader = title => {
logger.log('')
logger.log(title)
logger.log('='.repeat(title.length))
logger.log('')
}
const printFooter = () => logger.log('')
const printSuccess = msg => {
logger.log('')
logger.success(msg)
logger.log('')
}
const printError = msg => {
logger.log('')
logger.error(msg)
logger.log('')
}
/**
* Post-process bundled files to break node-gyp require.resolve strings.
* This prevents esbuild from trying to bundle node-gyp during the build.
*
* @param {string} dir - Directory to process
* @param {object} options - Options
* @param {boolean} options.quiet - Suppress output
* @param {boolean} options.verbose - Show detailed output
*/
async function fixNodeGypStrings(dir, options = {}) {
const { quiet = false, verbose = false } = options
// Find all .js files in build directory.
const files = await fs.readdir(dir, { withFileTypes: true })
for (const file of files) {
const filePath = path.join(dir, file.name)
if (file.isDirectory()) {
// Recursively process subdirectories.
await fixNodeGypStrings(filePath, options)
} else if (file.name.endsWith('.js')) {
// Read file contents.
const contents = await fs.readFile(filePath, 'utf8')
// Check if file contains the problematic pattern.
if (contents.includes('node-gyp/bin/node-gyp.js')) {
// Replace literal string with concatenated version.
const fixed = contents.replace(
/["']node-gyp\/bin\/node-gyp\.js["']/g,
'"node-" + "gyp/bin/node-gyp.js"',
)
await fs.writeFile(filePath, fixed, 'utf8')
if (!quiet && verbose) {
log.info(
`Fixed node-gyp string in ${path.relative(packageRoot, filePath)}`,
)
}
}
}
}
}
async function main() {
const quiet = isQuiet()
const verbose = isVerbose()
const watch = process.argv.includes('--watch')
const force = process.argv.includes('--force')
// Pass --force flag via environment variable.
if (force) {
process.env.SOCKET_CLI_FORCE_BUILD = '1'
}
// Delegate to watch mode.
if (watch) {
if (!quiet) {
log.info('Starting watch mode...')
}
// First extract yoga WASM.
const extractResult = await spawn(
'node',
[...NODE_MEMORY_FLAGS, 'scripts/extract-yoga-wasm.mjs'],
{
shell: WIN32,
stdio: 'inherit',
},
)
if (extractResult.code !== 0) {
process.exitCode = extractResult.code
throw new Error(
`WASM extraction failed with exit code ${extractResult.code}`,
)
}
// Then start esbuild in watch mode.
const watchResult = await spawn(
'node',
[...NODE_MEMORY_FLAGS, '.config/esbuild.cli.build.mjs', '--watch'],
{
shell: WIN32,
stdio: 'inherit',
},
)
if (watchResult.code !== 0) {
process.exitCode = watchResult.code
throw new Error(`Watch mode failed with exit code ${watchResult.code}`)
}
return
}
try {
if (!quiet) {
printHeader('Build Runner')
}
// If force build, always clean first.
const shouldClean = force
const steps = [
...(shouldClean
? [
{
name: 'Clean Dist',
command: 'pnpm',
args: ['run', 'clean:dist'],
},
]
: []),
// {
// name: 'Extract MiniLM Model',
// command: 'node',
// args: ['scripts/extract-minilm-model.mjs'],
// },
// {
// name: 'Extract ONNX Runtime',
// command: 'node',
// args: ['scripts/extract-onnx-runtime.mjs'],
// },
{
name: 'Extract Yoga WASM',
command: 'node',
args: [...NODE_MEMORY_FLAGS, 'scripts/extract-yoga-wasm.mjs'],
},
{
name: 'Extract AI Models',
command: 'node',
args: [...NODE_MEMORY_FLAGS, 'scripts/extract-models.mjs'],
},
{
name: 'Extract binject',
command: 'node',
args: [...NODE_MEMORY_FLAGS, 'scripts/extract-binject.mjs'],
},
{
name: 'Build CLI Bundle',
command: 'node',
args: [...NODE_MEMORY_FLAGS, '.config/esbuild.cli.build.mjs'],
},
{
name: 'Build Index Loader',
command: 'node',
args: [...NODE_MEMORY_FLAGS, '.config/esbuild.index.config.mjs'],
},
{
name: 'Build Shadow NPM Inject',
command: 'node',
args: [...NODE_MEMORY_FLAGS, '.config/esbuild.inject.config.mjs'],
},
]
// Run build steps sequentially.
if (!quiet) {
log.step(
`Running ${steps.length} build step${steps.length > 1 ? 's' : ''}...`,
)
}
for (const { args, command, name } of steps) {
if (verbose && !quiet) {
log.info(`Running: ${command} ${args.join(' ')}`)
}
const result = await spawn(command, args, {
shell: WIN32,
stdio: 'inherit',
})
if (result.code !== 0) {
if (!quiet) {
log.error(`${name} failed (exit code: ${result.code})`)
printError('Build failed')
}
process.exitCode = 1
return
}
if (!quiet && verbose) {
log.success(`${name} completed`)
}
}
// Copy CLI bundle to dist (required for dist/index.js to work).
copyFileSync('build/cli.js', 'dist/cli.js')
// Post-process: Fix node-gyp strings to prevent bundler issues.
if (!quiet && verbose) {
log.info('Post-processing build output...')
}
await fixNodeGypStrings(path.join(packageRoot, 'build'), { quiet, verbose })
if (!quiet && verbose) {
log.success('Build output post-processed')
}
// Copy files from repo root.
if (!quiet && verbose) {
log.info('Copying files from repo root...')
}
const filesToCopy = [
'CHANGELOG.md',
'LICENSE',
'logo-dark.png',
'logo-light.png',
]
for (const file of filesToCopy) {
await fs.cp(path.join(repoRoot, file), path.join(packageRoot, file))
}
if (!quiet && verbose) {
log.success('Files copied from repo root')
}
if (!quiet) {
printSuccess('Build completed')
printFooter()
}
} catch (error) {
if (!quiet) {
printError(`Build failed: ${error.message}`)
}
if (verbose) {
logger.error(error)
}
process.exitCode = 1
}
}
main().catch(e => {
logger.error(e)
process.exitCode = 1
})