-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathsetup.mts
More file actions
619 lines (534 loc) · 16.2 KB
/
setup.mts
File metadata and controls
619 lines (534 loc) · 16.2 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import process from 'node:process'
/**
* @fileoverview Developer setup script - checks prerequisites and prepares environment.
*
* Checks and optionally installs:
* - Node.js version (>=18.0.0)
* - pnpm version (>=10.21.0)
* - gh CLI (optional, for cache restoration)
* - Homebrew (if needed for installations)
*
* Actions:
* - Checks for required tools (Node.js, pnpm) and fails if missing
* - Auto-installs optional tools (gh CLI, brew/choco) if --install flag provided
* - Verifies installed tools are actually available in PATH before proceeding
* - Attempts to restore build cache from CI (only if gh CLI available)
* - Reports missing tools with installation instructions
*
* Usage:
* pnpm run setup # Check prerequisites and restore GitHub cache
* pnpm run setup --install # Check and auto-install optional tools, then restore cache
* pnpm run setup --skip-prereqs # Only restore GitHub cache (skip prerequisite checks)
* pnpm run setup --skip-gh-cache # Check prerequisites but skip GitHub cache restoration
* pnpm run setup --quiet # Minimal output (for postinstall)
*
* Flags:
* --install Auto-install missing optional tools (gh CLI)
* --skip-prereqs Skip prerequisite checks (for CI use; still attempts cache restoration)
* --skip-gh-cache Skip GitHub cache restoration (useful when cache is corrupt)
* --quiet Minimal output
*
* Note: Setup helpers are also exported in build-infra/lib/setup-helpers
* for reuse in other build scripts.
*/
import { existsSync } from 'node:fs'
import { mkdir } from 'node:fs/promises'
import { WIN32 } from '@socketsecurity/lib/constants/platform'
import { getDefaultLogger } from '@socketsecurity/lib/logger'
import { spawn } from '@socketsecurity/lib/spawn'
const logger = getDefaultLogger()
const autoInstall = process.argv.includes('--install')
const quiet = process.argv.includes('--quiet')
const skipPrereqs = process.argv.includes('--skip-prereqs')
const skipGhCache = process.argv.includes('--skip-gh-cache')
// Handle --help flag.
const showHelp = process.argv.includes('--help') || process.argv.includes('-h')
if (showHelp) {
logger.log(`
Socket CLI Developer Setup
Usage:
pnpm run setup [options]
Options:
--install Auto-install missing optional tools (gh CLI)
--skip-prereqs Skip prerequisite checks (for CI use)
--skip-gh-cache Skip GitHub cache restoration (useful when cache is corrupt)
--quiet Minimal output
--help, -h Show this help message
Examples:
pnpm run setup # Check prerequisites and restore cache
pnpm run setup --install # Auto-install optional tools
pnpm run setup --skip-gh-cache # Skip cache (useful if cache is corrupt)
pnpm run setup --skip-prereqs # Skip checks, only restore cache
`)
process.exitCode = 0
}
interface VersionInfo {
major: number
minor: number
patch: number
}
interface PrerequisiteOptions {
command: string
minVersion?: VersionInfo
name: string
required?: boolean
}
/**
* Check if a command is available.
*/
async function hasCommand(command: string): Promise<boolean> {
try {
const result = await spawn(command, ['--version'], {
stdio: 'pipe',
})
return result.code === 0
} catch {
return false
}
}
/**
* Get version of a command.
*/
async function getVersion(
command: string,
args: string[] = ['--version'],
): Promise<string | undefined> {
try {
const result = await spawn(command, args, {
stdio: 'pipe',
})
if (result.code === 0) {
return String(result.stdout).trim()
}
} catch {
// Ignore.
}
return undefined
}
/**
* Parse version string to compare.
*/
function parseVersion(versionString: string): VersionInfo | undefined {
const match = versionString.match(/(\d+)\.(\d+)\.(\d+)/)
if (!match) {
return undefined
}
return {
major: Number.parseInt(match[1], 10),
minor: Number.parseInt(match[2], 10),
patch: Number.parseInt(match[3], 10),
}
}
/**
* Compare two version objects.
* Returns: -1 if a < b, 0 if a === b, 1 if a > b
*/
function compareVersions(a: VersionInfo, b: VersionInfo): number {
if (a.major !== b.major) {
return a.major < b.major ? -1 : 1
}
if (a.minor !== b.minor) {
return a.minor < b.minor ? -1 : 1
}
if (a.patch !== b.patch) {
return a.patch < b.patch ? -1 : 1
}
return 0
}
/**
* Install Homebrew (macOS/Linux).
*/
async function installHomebrew(): Promise<boolean> {
if (WIN32) {
logger.warn('Homebrew is not available on Windows')
return false
}
logger.step('Installing Homebrew...')
logger.info('This requires sudo access and may take a few minutes')
const installScript =
'/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
const result = await spawn('bash', ['-c', installScript], {
stdio: 'inherit',
})
if (result.code === 0) {
logger.success('Homebrew installed successfully!')
return true
}
logger.error('Failed to install Homebrew')
return false
}
/**
* Install Chocolatey (Windows).
*/
async function installChocolatey(): Promise<boolean> {
if (!WIN32) {
logger.warn('Chocolatey is only available on Windows')
return false
}
logger.step('Installing Chocolatey...')
logger.info('This requires admin access and may take a few minutes')
const installScript =
"Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))"
const result = await spawn('powershell', ['-Command', installScript], {
stdio: 'inherit',
})
if (result.code === 0) {
logger.success('Chocolatey installed successfully!')
return true
}
logger.error('Failed to install Chocolatey')
logger.info('You may need to run as Administrator')
return false
}
/**
* Install a package using Homebrew (macOS/Linux).
*/
async function installWithHomebrew(packageName: string): Promise<boolean> {
if (!(await hasCommand('brew'))) {
logger.error('Homebrew not available')
return false
}
logger.step(`Installing ${packageName} with Homebrew...`)
const result = await spawn('brew', ['install', packageName], {
stdio: 'inherit',
})
if (result.code === 0) {
logger.success(`${packageName} installed successfully!`)
return true
}
logger.error(`Failed to install ${packageName}`)
return false
}
/**
* Install a package using Chocolatey (Windows).
*/
async function installWithChocolatey(packageName: string): Promise<boolean> {
if (!(await hasCommand('choco'))) {
logger.error('Chocolatey not available')
return false
}
logger.step(`Installing ${packageName} with Chocolatey...`)
const result = await spawn('choco', ['install', packageName, '-y'], {
stdio: 'inherit',
})
if (result.code === 0) {
logger.success(`${packageName} installed successfully!`)
return true
}
logger.error(`Failed to install ${packageName}`)
logger.info('You may need to run as Administrator')
return false
}
/**
* Check and optionally install gh CLI.
*/
async function ensureGhCli(): Promise<boolean> {
if (await hasCommand('gh')) {
const version = await getVersion('gh')
logger.log(`gh CLI ${version} (optional)`)
return true
}
if (!autoInstall) {
logger.info('gh CLI not found (optional - enables cache restoration)')
logger.info('Install from: https://cli.github.com/')
logger.info('Or run: pnpm run setup --install')
return false
}
// Auto-install mode.
if (WIN32) {
// Windows: Try Chocolatey.
if (!(await hasCommand('choco'))) {
logger.info('Chocolatey not found (needed for auto-install on Windows)')
logger.log('Attempting to install Chocolatey...')
const installed = await installChocolatey()
if (!installed) {
logger.warn('Could not install Chocolatey')
logger.info('Install gh CLI manually from: https://cli.github.com/')
logger.info(
'Or install Chocolatey from: https://chocolatey.org/install',
)
return false
}
}
// Install gh CLI with Chocolatey.
logger.log('Installing gh CLI with Chocolatey...')
const installed = await installWithChocolatey('gh')
if (installed) {
// Verify gh is actually available after installation.
if (await hasCommand('gh')) {
const version = await getVersion('gh')
logger.log(`gh CLI ${version} installed!`)
return true
}
logger.warn('gh CLI installed but not available in PATH')
logger.info('You may need to restart your shell or run: pnpm run setup')
return false
}
logger.warn('Could not install gh CLI')
logger.info('Install manually from: https://cli.github.com/')
return false
}
// macOS/Linux: Try Homebrew.
if (!(await hasCommand('brew'))) {
logger.info('Homebrew not found (needed for auto-install)')
logger.log('Attempting to install Homebrew...')
const installed = await installHomebrew()
if (!installed) {
logger.warn('Could not install Homebrew')
logger.info('Install gh CLI manually from: https://cli.github.com/')
return false
}
}
// Install gh CLI with Homebrew.
logger.log('Installing gh CLI with Homebrew...')
const installed = await installWithHomebrew('gh')
if (installed) {
// Verify gh is actually available after installation.
if (await hasCommand('gh')) {
const version = await getVersion('gh')
logger.log(`gh CLI ${version} installed!`)
return true
}
logger.warn('gh CLI installed but not available in PATH')
logger.info('You may need to restart your shell or run: pnpm run setup')
return false
}
logger.warn('Could not install gh CLI')
logger.info('Install manually from: https://cli.github.com/')
return false
}
/**
* Check prerequisite.
*/
async function checkPrerequisite({
command,
minVersion,
name,
required = true,
}: PrerequisiteOptions): Promise<boolean> {
const version = await getVersion(command)
if (!version) {
logger.error(`${name} not found`)
return false
}
if (minVersion) {
const current = parseVersion(version)
if (!current) {
logger.warn(`Could not parse ${name} version: ${version}`)
return !required
}
if (compareVersions(current, minVersion) < 0) {
const minVersionStr = `${minVersion.major}.${minVersion.minor}.${minVersion.patch}`
logger.error(`${name} ${version} found, but >=${minVersionStr} required`)
return false
}
}
logger.log(`${name} ${version}`)
return true
}
/**
* Generate cli-with-sentry package from template.
*/
async function generateCliSentryPackage(): Promise<boolean> {
if (!quiet) {
logger.log('Generating cli-with-sentry package from template...')
}
const scriptPath = new URL(
'../packages/package-builder/scripts/generate-cli-sentry-package.mts',
import.meta.url,
)
const result = await spawn('node', [scriptPath.pathname], {
stdio: quiet ? 'pipe' : 'inherit',
})
if (result.code === 0) {
if (!quiet) {
logger.log('cli-with-sentry package generated!')
}
return true
}
logger.warn('Failed to generate cli-with-sentry package')
return false
}
/**
* Generate socket package from template.
*/
/**
* Generate socketbin packages from template.
*/
async function generateSocketbinPackages(): Promise<boolean> {
if (!quiet) {
logger.log('Generating socketbin packages from template...')
}
const scriptPath = new URL(
'../packages/package-builder/scripts/generate-socketbin-packages.mts',
import.meta.url,
)
const result = await spawn('node', [scriptPath.pathname], {
stdio: quiet ? 'pipe' : 'inherit',
})
if (result.code === 0) {
if (!quiet) {
logger.log('Socketbin packages generated!')
}
return true
}
logger.warn('Failed to generate socketbin packages')
return false
}
/**
* Restore build cache if possible.
*/
async function restoreCache(hasGh: boolean): Promise<boolean> {
// Skip entirely if gh CLI not available.
if (!hasGh) {
logger.info('Skipping cache restoration (gh CLI not available)')
return false
}
// Check if already built.
if (existsSync('packages/cli/build') && existsSync('packages/cli/dist')) {
logger.info('Build artifacts already exist, skipping cache restoration')
return true
}
// Ensure directories exist.
logger.log('Ensuring build directories exist...')
await mkdir('packages/cli/build', { recursive: true })
await mkdir('packages/cli/dist', { recursive: true })
logger.log('Attempting to restore build cache from CI...')
const result = await spawn(
'pnpm',
['--filter', '@socketsecurity/cli', 'run', 'restore-cache', '--quiet'],
{
stdio: 'inherit',
},
)
if (result.code === 0) {
logger.log('Build cache restored!')
return true
}
logger.info('Cache not available for this commit (will build from scratch)')
return false
}
/**
* Main entry point.
*/
async function main(): Promise<number> {
// Handle --skip-prereqs: skip prerequisite checks, proceed to cache restoration.
if (skipPrereqs) {
if (!quiet) {
logger.log('')
logger.log('Socket CLI Cache Restoration')
logger.log('============================')
logger.log('')
logger.info('Skipping prerequisite checks (--skip-prereqs)')
logger.log('')
}
// Cache restoration respects --skip-gh-cache flag.
if (!skipGhCache) {
const hasGh = await hasCommand('gh')
if (!hasGh) {
logger.error('gh CLI not found (required for cache restoration)')
logger.info('Install from: https://cli.github.com/')
return 1
}
await restoreCache(hasGh)
} else if (!quiet) {
logger.info('Skipping GitHub cache restoration (--skip-gh-cache)')
}
if (!quiet) {
logger.log('')
logger.log('Setup complete!')
logger.log('')
}
return 0
}
// Normal setup flow: check prerequisites and restore cache.
if (!quiet) {
logger.log('')
logger.log('Socket CLI Developer Setup')
logger.log('==========================')
logger.log('')
if (autoInstall) {
logger.info('Auto-install mode enabled (--install)')
logger.log('')
}
}
logger.log('Checking prerequisites...')
if (!quiet) {
logger.log('')
}
// Check Node.js.
const nodeOk = await checkPrerequisite({
command: 'node',
minVersion: { major: 18, minor: 0, patch: 0 },
name: 'Node.js',
required: true,
})
// Check pnpm.
const pnpmOk = await checkPrerequisite({
command: 'pnpm',
minVersion: { major: 10, minor: 21, patch: 0 },
name: 'pnpm',
required: true,
})
// Check gh CLI (optional, with auto-install).
const ghOk = await ensureGhCli()
if (!quiet) {
logger.log('')
}
if (!nodeOk || !pnpmOk) {
logger.error(
'Required prerequisites missing. Please install and try again.',
)
if (!quiet) {
logger.log('')
}
if (!nodeOk) {
logger.info('Node.js: https://nodejs.org/')
}
if (!pnpmOk) {
logger.info('pnpm: npm install -g pnpm')
}
return 1
}
logger.log('All required prerequisites met!')
if (!quiet) {
logger.log('')
}
// Generate packages from templates.
await generateCliSentryPackage()
if (!quiet) {
logger.log('')
}
await generateSocketbinPackages()
if (!quiet) {
logger.log('')
}
// Always restore cache after prerequisite checks (unless --skip-gh-cache).
if (!skipGhCache) {
await restoreCache(ghOk)
} else if (!quiet) {
logger.info('Skipping GitHub cache restoration (--skip-gh-cache)')
}
if (!quiet) {
logger.log('')
logger.log('Setup complete!')
logger.log('')
logger.log('Next steps:')
logger.log(' pnpm run build # Build the CLI')
logger.log(' pnpm test # Run tests')
logger.log(' pnpm exec socket # Run the CLI')
logger.log('')
}
return 0
}
if (!showHelp) {
main()
.then((code: number) => {
process.exitCode = code
})
.catch((e: unknown) => {
const message = e instanceof Error ? e.message : String(e)
logger.error(message)
process.exitCode = 1
})
}