@socketsecurity/cli 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js DELETED
@@ -1,4133 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- var vendor = require('./vendor.js');
5
- var require$$0 = require('node:fs');
6
- var require$$1 = require('node:path');
7
- var require$$2$4 = require('node:url');
8
- var require$$6 = require('pony-cause');
9
- var require$$5 = require('yargs-parser');
10
- var sdk = require('./sdk.js');
11
- var require$$1$1 = require('@inquirer/prompts');
12
- var require$$0$1 = require('node:child_process');
13
- var require$$2 = require('@apideck/better-ajv-errors');
14
- var require$$3 = require('@socketsecurity/config');
15
- var pathResolve = require('./path-resolve.js');
16
- var require$$0$2 = require('node:os');
17
- var require$$3$1 = require('node:readline');
18
- var require$$0$3 = require('node:process');
19
- var require$$2$1 = require('node:readline/promises');
20
- var require$$2$2 = require('chalk-table');
21
- var require$$1$2 = require('blessed');
22
- var require$$2$3 = require('blessed-contrib');
23
- var require$$0$4 = require('node:util');
24
-
25
- var cli$1 = {};
26
-
27
- var cli = {};
28
-
29
- var commands = {};
30
-
31
- var cdxgen = {};
32
-
33
- var _interopRequireDefault$r = vendor.interopRequireDefault.default;
34
- Object.defineProperty(cdxgen, "__esModule", {
35
- value: true
36
- });
37
- cdxgen.cdxgen = void 0;
38
- var _nodeFs$2 = require$$0;
39
- var _nodePath$4 = require$$1;
40
- var _chalk$j = _interopRequireDefault$r(vendor.source);
41
- var _execa = vendor.execa;
42
- var _yargsParser = require$$5;
43
- const distPath$3 = __dirname;
44
- const rootPath$1 = _nodePath$4.resolve(distPath$3, '..');
45
- const {
46
- SBOM_SIGN_ALGORITHM,
47
- // Algorithm. Example: RS512
48
- SBOM_SIGN_PRIVATE_KEY,
49
- // Location to the RSA private key
50
- SBOM_SIGN_PUBLIC_KEY // Optional. Location to the RSA public key
51
- } = process.env;
52
- const toLower = arg => arg.toLowerCase();
53
- const arrayToLower = arg => arg.map(toLower);
54
- const execaConfig = {
55
- env: {
56
- NODE_ENV: ''
57
- },
58
- localDir: _nodePath$4.join(rootPath$1, 'node_modules')
59
- };
60
- const nodejsPlatformTypes = ['javascript', 'js', 'nodejs', 'npm', 'pnpm', 'ts', 'tsx', 'typescript'];
61
- const yargsConfig = {
62
- configuration: {
63
- 'camel-case-expansion': false,
64
- 'strip-aliased': true,
65
- 'parse-numbers': false,
66
- 'populate--': true,
67
- 'unknown-options-as-args': true
68
- },
69
- coerce: {
70
- author: arrayToLower,
71
- filter: arrayToLower,
72
- only: arrayToLower,
73
- profile: toLower,
74
- standard: arrayToLower,
75
- type: toLower
76
- },
77
- default: {
78
- //author: ['OWASP Foundation'],
79
- //'auto-compositions': true,
80
- //babel: true,
81
- //evidence: false,
82
- //'include-crypto': false,
83
- //'include-formulation': false,
84
- //'install-deps': true,
85
- //output: 'bom.json',
86
- //profile: 'generic',
87
- //'project-version': '',
88
- //recurse: true,
89
- //'server-host': '127.0.0.1',
90
- //'server-port': '9090',
91
- //'spec-version': '1.5',
92
- type: 'js'
93
- //validate: true,
94
- },
95
- alias: {
96
- help: ['h'],
97
- output: ['o'],
98
- print: ['p'],
99
- recurse: ['r'],
100
- 'resolve-class': ['c'],
101
- type: ['t'],
102
- version: ['v']
103
- },
104
- array: [{
105
- key: 'author',
106
- type: 'string'
107
- }, {
108
- key: 'exclude',
109
- type: 'string'
110
- }, {
111
- key: 'filter',
112
- type: 'string'
113
- }, {
114
- key: 'only',
115
- type: 'string'
116
- }, {
117
- key: 'standard',
118
- type: 'string'
119
- }],
120
- boolean: ['auto-compositions', 'babel', 'deep', 'evidence', 'fail-on-error', 'generate-key-and-sign', 'help', 'include-formulation', 'include-crypto', 'install-deps', 'print', 'required-only', 'server', 'validate', 'version'],
121
- string: ['api-key', 'output', 'parent-project-id', 'profile', 'project-group', 'project-name', 'project-version', 'project-id', 'server-host', 'server-port', 'server-url', 'spec-version']
122
- };
123
- function argvToArray(argv) {
124
- if (argv['help']) return ['--help'];
125
- const result = [];
126
- for (const {
127
- 0: key,
128
- 1: value
129
- } of Object.entries(argv)) {
130
- if (key === '_' || key === '--') continue;
131
- if (key === 'babel' || key === 'install-deps' || key === 'validate') {
132
- // cdxgen documents no-babel, no-install-deps, and no-validate flags so
133
- // use them when relevant.
134
- result.push(`--${value ? key : `no-${key}`}`);
135
- } else if (value === true) {
136
- result.push(`--${key}`);
137
- } else if (typeof value === 'string') {
138
- result.push(`--${key}=${value}`);
139
- } else if (Array.isArray(value)) {
140
- result.push(`--${key}`, ...value.map(String));
141
- }
142
- }
143
- if (argv['--']) {
144
- result.push('--', ...argv['--']);
145
- }
146
- return result;
147
- }
148
- cdxgen.cdxgen = {
149
- description: 'Create an SBOM with CycloneDX generator (cdxgen)',
150
- async run(argv_) {
151
- const yargv = {
152
- __proto__: null,
153
- ..._yargsParser(argv_, yargsConfig)
154
- };
155
- const unknown = yargv._;
156
- const {
157
- length: unknownLength
158
- } = unknown;
159
- if (unknownLength) {
160
- console.error(`Unknown argument${unknownLength > 1 ? 's' : ''}: ${yargv._.join(', ')}`);
161
- process.exitCode = 1;
162
- return;
163
- }
164
- let cleanupPackageLock = false;
165
- if (yargv.type !== 'yarn' && nodejsPlatformTypes.includes(yargv.type) && (0, _nodeFs$2.existsSync)('./yarn.lock')) {
166
- if ((0, _nodeFs$2.existsSync)('./package-lock.json')) {
167
- yargv.type = 'npm';
168
- } else {
169
- // Use synp to create a package-lock.json from the yarn.lock,
170
- // based on the node_modules folder, for a more accurate SBOM.
171
- try {
172
- await (0, _execa.$)(execaConfig)`synp --source-file ./yarn.lock`;
173
- yargv.type = 'npm';
174
- cleanupPackageLock = true;
175
- } catch {}
176
- }
177
- }
178
- if (yargv.output === undefined) {
179
- yargv.output = 'socket-cdx.json';
180
- }
181
- await (0, _execa.$)({
182
- ...execaConfig,
183
- env: {
184
- NODE_ENV: '',
185
- SBOM_SIGN_ALGORITHM,
186
- SBOM_SIGN_PRIVATE_KEY,
187
- SBOM_SIGN_PUBLIC_KEY
188
- },
189
- stdout: 'inherit'
190
- })`cdxgen ${argvToArray(yargv)}`;
191
- if (cleanupPackageLock) {
192
- try {
193
- await _nodeFs$2.promises.unlink('./package-lock.json');
194
- } catch {}
195
- }
196
- const fullOutputPath = _nodePath$4.join(process.cwd(), yargv.output);
197
- if ((0, _nodeFs$2.existsSync)(fullOutputPath)) {
198
- console.log(_chalk$j.default.cyanBright(`${yargv.output} created!`));
199
- }
200
- }
201
- };
202
-
203
- var info$1 = {};
204
-
205
- var flags = {};
206
-
207
- Object.defineProperty(flags, "__esModule", {
208
- value: true
209
- });
210
- flags.validationFlags = flags.outputFlags = flags.commandFlags = void 0;
211
- flags.commandFlags = {
212
- enable: {
213
- type: 'boolean',
214
- default: false,
215
- description: 'Enables the Socket npm/npx wrapper'
216
- },
217
- disable: {
218
- type: 'boolean',
219
- default: false,
220
- description: 'Disables the Socket npm/npx wrapper'
221
- }
222
- };
223
- flags.outputFlags = {
224
- json: {
225
- type: 'boolean',
226
- shortFlag: 'j',
227
- default: false,
228
- description: 'Output result as json'
229
- },
230
- markdown: {
231
- type: 'boolean',
232
- shortFlag: 'm',
233
- default: false,
234
- description: 'Output result as markdown'
235
- }
236
- };
237
- flags.validationFlags = {
238
- all: {
239
- type: 'boolean',
240
- default: false,
241
- description: 'Include all issues'
242
- },
243
- strict: {
244
- type: 'boolean',
245
- default: false,
246
- description: 'Exits with an error code if any matching issues are found'
247
- }
248
- };
249
-
250
- var apiHelpers = {};
251
-
252
- var _interopRequireDefault$q = vendor.interopRequireDefault.default;
253
- Object.defineProperty(apiHelpers, "__esModule", {
254
- value: true
255
- });
256
- apiHelpers.handleAPIError = handleAPIError;
257
- apiHelpers.handleApiCall = handleApiCall;
258
- apiHelpers.handleUnsuccessfulApiResponse = handleUnsuccessfulApiResponse;
259
- apiHelpers.queryAPI = queryAPI;
260
- apiHelpers.queryOrgsAPI = queryOrgsAPI;
261
- var _chalk$i = _interopRequireDefault$q(vendor.source);
262
- var _ponyCause$4 = require$$6;
263
- var _errors$l = sdk.errors;
264
- function handleUnsuccessfulApiResponse(_name, result, spinner) {
265
- const resultError = 'error' in result && result.error && typeof result.error === 'object' ? result.error : {};
266
- const message = 'message' in resultError && typeof resultError.message === 'string' ? resultError.message : 'No error message returned';
267
- if (result.status === 401 || result.status === 403) {
268
- spinner.stop();
269
- throw new _errors$l.AuthError(message);
270
- }
271
- spinner.fail(_chalk$i.default.white.bgRed('API returned an error:') + ' ' + message);
272
- process.exit(1);
273
- }
274
- async function handleApiCall(value, description) {
275
- let result;
276
- try {
277
- result = await value;
278
- } catch (cause) {
279
- throw new _ponyCause$4.ErrorWithCause(`Failed ${description}`, {
280
- cause
281
- });
282
- }
283
- return result;
284
- }
285
- async function handleAPIError(code) {
286
- if (code === 400) {
287
- return `One of the options passed might be incorrect.`;
288
- } else if (code === 403) {
289
- return `You might be trying to access an organization that is not linked to the API key you are logged in with.`;
290
- }
291
- }
292
- const API_V0_URL = 'https://api.socket.dev/v0';
293
- async function queryOrgsAPI(path, apiKey) {
294
- return await fetch(`${API_V0_URL}/orgs/${path}`, {
295
- method: 'GET',
296
- headers: {
297
- 'Authorization': 'Basic ' + btoa(`${apiKey}:${apiKey}`)
298
- }
299
- });
300
- }
301
- async function queryAPI(path, apiKey) {
302
- return await fetch(`${API_V0_URL}/${path}`, {
303
- method: 'GET',
304
- headers: {
305
- 'Authorization': 'Basic ' + btoa(`${apiKey}:${apiKey}`)
306
- }
307
- });
308
- }
309
-
310
- var formatIssues = {};
311
-
312
- var misc = {};
313
-
314
- Object.defineProperty(misc, "__esModule", {
315
- value: true
316
- });
317
- misc.createDebugLogger = createDebugLogger;
318
- misc.objectSome = objectSome;
319
- misc.pick = pick;
320
- misc.stringJoinWithSeparateFinalSeparator = stringJoinWithSeparateFinalSeparator;
321
- var _chalkMarkdown$4 = sdk.chalkMarkdown;
322
- function createDebugLogger(printDebugLogs) {
323
- return printDebugLogs ? (...params) => console.error(_chalkMarkdown$4.logSymbols.info, ...params) : () => {};
324
- }
325
- function stringJoinWithSeparateFinalSeparator(list, separator = ' and ') {
326
- const values = list.filter(value => !!value);
327
- if (values.length < 2) {
328
- return values[0] || '';
329
- }
330
- const finalValue = values.pop();
331
- return values.join(', ') + separator + finalValue;
332
- }
333
- function pick(input, keys) {
334
- const result = {};
335
- for (const key of keys) {
336
- result[key] = input[key];
337
- }
338
- return result;
339
- }
340
- function objectSome(obj) {
341
- for (const key in obj) {
342
- if (obj[key]) {
343
- return true;
344
- }
345
- }
346
- return false;
347
- }
348
-
349
- Object.defineProperty(formatIssues, "__esModule", {
350
- value: true
351
- });
352
- formatIssues.formatSeverityCount = formatSeverityCount;
353
- formatIssues.getSeverityCount = getSeverityCount;
354
- var _misc$3 = misc;
355
- const SEVERITIES_BY_ORDER = ['critical', 'high', 'middle', 'low'];
356
- function getDesiredSeverities(lowestToInclude) {
357
- const result = [];
358
- for (const severity of SEVERITIES_BY_ORDER) {
359
- result.push(severity);
360
- if (severity === lowestToInclude) {
361
- break;
362
- }
363
- }
364
- return result;
365
- }
366
- function getSeverityCount(issues, lowestToInclude) {
367
- const severityCount = (0, _misc$3.pick)({
368
- low: 0,
369
- middle: 0,
370
- high: 0,
371
- critical: 0
372
- }, getDesiredSeverities(lowestToInclude));
373
- for (const issue of issues) {
374
- const value = issue.value;
375
- if (!value) {
376
- continue;
377
- }
378
- if (severityCount[value.severity] !== undefined) {
379
- severityCount[value.severity] += 1;
380
- }
381
- }
382
- return severityCount;
383
- }
384
- function formatSeverityCount(severityCount) {
385
- const summary = [];
386
- for (const severity of SEVERITIES_BY_ORDER) {
387
- if (severityCount[severity]) {
388
- summary.push(`${severityCount[severity]} ${severity}`);
389
- }
390
- }
391
- return (0, _misc$3.stringJoinWithSeparateFinalSeparator)(summary);
392
- }
393
-
394
- var formatting = {};
395
-
396
- Object.defineProperty(formatting, "__esModule", {
397
- value: true
398
- });
399
- formatting.printFlagList = printFlagList;
400
- formatting.printHelpList = printHelpList;
401
- function printHelpList(list, indent, {
402
- keyPrefix = '',
403
- padName = 18
404
- } = {}) {
405
- const names = Object.keys(list).sort();
406
- let result = '';
407
- for (const name of names) {
408
- const rawDescription = list[name];
409
- const description = (typeof rawDescription === 'object' ? rawDescription.description : rawDescription) || '';
410
- result += ''.padEnd(indent) + (keyPrefix + name).padEnd(padName) + description + '\n';
411
- }
412
- return result.trim();
413
- }
414
- function printFlagList(list, indent, {
415
- keyPrefix = '--',
416
- padName
417
- } = {}) {
418
- return printHelpList({
419
- help: 'Print this help and exits.',
420
- version: 'Prints current version and exits.',
421
- ...list
422
- }, indent, {
423
- keyPrefix,
424
- padName
425
- });
426
- }
427
-
428
- var _interopRequireDefault$p = vendor.interopRequireDefault.default;
429
- Object.defineProperty(info$1, "__esModule", {
430
- value: true
431
- });
432
- info$1.info = void 0;
433
- var _chalk$h = _interopRequireDefault$p(vendor.source);
434
- var _meow$o = _interopRequireDefault$p(vendor.build);
435
- var _ora$k = _interopRequireDefault$p(vendor.ora);
436
- var _flags$i = flags;
437
- var _apiHelpers$i = apiHelpers;
438
- var _chalkMarkdown$3 = sdk.chalkMarkdown;
439
- var _errors$k = sdk.errors;
440
- var _formatIssues$1 = formatIssues;
441
- var _formatting$l = formatting;
442
- var _misc$2 = misc;
443
- var _sdk$j = sdk.sdk;
444
- const info = info$1.info = {
445
- description: 'Look up info regarding a package',
446
- async run(argv, importMeta, {
447
- parentName
448
- }) {
449
- const name = parentName + ' info';
450
- const input = setupCommand$l(name, info.description, argv, importMeta);
451
- if (input) {
452
- const spinnerText = input.pkgVersion === 'latest' ? `Looking up data for the latest version of ${input.pkgName}\n` : `Looking up data for version ${input.pkgVersion} of ${input.pkgName}\n`;
453
- const spinner = (0, _ora$k.default)(spinnerText).start();
454
- const packageData = await fetchPackageData(input.pkgName, input.pkgVersion, input, spinner);
455
- if (packageData) {
456
- formatPackageDataOutput(packageData, {
457
- name,
458
- ...input
459
- }, spinner);
460
- }
461
- }
462
- }
463
- };
464
-
465
- // Internal functions
466
-
467
- function setupCommand$l(name, description, argv, importMeta) {
468
- const flags = {
469
- ..._flags$i.outputFlags,
470
- ..._flags$i.validationFlags
471
- };
472
- const cli = (0, _meow$o.default)(`
473
- Usage
474
- $ ${name} <name>
475
-
476
- Options
477
- ${(0, _formatting$l.printFlagList)(flags, 6)}
478
-
479
- Examples
480
- $ ${name} webtorrent
481
- $ ${name} webtorrent@1.9.1
482
- `, {
483
- argv,
484
- description,
485
- importMeta,
486
- flags
487
- });
488
- const {
489
- all: includeAllIssues,
490
- json: outputJson,
491
- markdown: outputMarkdown,
492
- strict
493
- } = cli.flags;
494
- if (cli.input.length > 1) {
495
- throw new _errors$k.InputError('Only one package lookup supported at once');
496
- }
497
- const [rawPkgName = ''] = cli.input;
498
- if (!rawPkgName) {
499
- cli.showHelp();
500
- return;
501
- }
502
- const versionSeparator = rawPkgName.lastIndexOf('@');
503
- const pkgName = versionSeparator < 1 ? rawPkgName : rawPkgName.slice(0, versionSeparator);
504
- const pkgVersion = versionSeparator < 1 ? 'latest' : rawPkgName.slice(versionSeparator + 1);
505
- return {
506
- includeAllIssues,
507
- outputJson,
508
- outputMarkdown,
509
- pkgName,
510
- pkgVersion,
511
- strict
512
- };
513
- }
514
- async function fetchPackageData(pkgName, pkgVersion, {
515
- includeAllIssues
516
- }, spinner) {
517
- const socketSdk = await (0, _sdk$j.setupSdk)((0, _sdk$j.getDefaultKey)() || _sdk$j.FREE_API_KEY);
518
- const result = await (0, _apiHelpers$i.handleApiCall)(socketSdk.getIssuesByNPMPackage(pkgName, pkgVersion), 'looking up package');
519
- const scoreResult = await (0, _apiHelpers$i.handleApiCall)(socketSdk.getScoreByNPMPackage(pkgName, pkgVersion), 'looking up package score');
520
- if (result.success === false) {
521
- return (0, _apiHelpers$i.handleUnsuccessfulApiResponse)('getIssuesByNPMPackage', result, spinner);
522
- }
523
- if (scoreResult.success === false) {
524
- return (0, _apiHelpers$i.handleUnsuccessfulApiResponse)('getScoreByNPMPackage', scoreResult, spinner);
525
- }
526
- const severityCount = (0, _formatIssues$1.getSeverityCount)(result.data, includeAllIssues ? undefined : 'high');
527
- return {
528
- data: result.data,
529
- severityCount,
530
- score: scoreResult.data
531
- };
532
- }
533
- function formatPackageDataOutput({
534
- data,
535
- severityCount,
536
- score
537
- }, {
538
- name,
539
- outputJson,
540
- outputMarkdown,
541
- pkgName,
542
- pkgVersion,
543
- strict
544
- }, spinner) {
545
- if (outputJson) {
546
- console.log(JSON.stringify(data, undefined, 2));
547
- } else {
548
- console.log('\nPackage report card:');
549
- const scoreResult = {
550
- 'Supply Chain Risk': Math.floor(score.supplyChainRisk.score * 100),
551
- Maintenance: Math.floor(score.maintenance.score * 100),
552
- Quality: Math.floor(score.quality.score * 100),
553
- Vulnerabilities: Math.floor(score.vulnerability.score * 100),
554
- License: Math.floor(score.license.score * 100)
555
- };
556
- Object.entries(scoreResult).map(score => console.log(`- ${score[0]}: ${formatScore(score[1])}`));
557
- if ((0, _misc$2.objectSome)(severityCount)) {
558
- const issueSummary = (0, _formatIssues$1.formatSeverityCount)(severityCount);
559
- console.log('\n');
560
- spinner[strict ? 'fail' : 'succeed'](`Package has these issues: ${issueSummary}`);
561
- formatPackageIssuesDetails(data, outputMarkdown);
562
- } else {
563
- console.log('\n');
564
- spinner.succeed('Package has no issues');
565
- }
566
- const format = new _chalkMarkdown$3.ChalkOrMarkdown(!!outputMarkdown);
567
- const url = `https://socket.dev/npm/package/${pkgName}/overview/${pkgVersion}`;
568
- if (pkgVersion === 'latest') {
569
- console.log('\nDetailed info on socket.dev: ' + format.hyperlink(`${pkgName}`, url, {
570
- fallbackToUrl: true
571
- }));
572
- } else {
573
- console.log('\nDetailed info on socket.dev: ' + format.hyperlink(`${pkgName} v${pkgVersion}`, url, {
574
- fallbackToUrl: true
575
- }));
576
- }
577
- if (!outputMarkdown) {
578
- console.log(_chalk$h.default.dim('\nOr rerun', _chalk$h.default.italic(name), 'using the', _chalk$h.default.italic('--json'), 'flag to get full JSON output'));
579
- }
580
- }
581
- if (strict && (0, _misc$2.objectSome)(severityCount)) {
582
- process.exit(1);
583
- }
584
- }
585
- function formatPackageIssuesDetails(packageData, outputMarkdown) {
586
- const issueDetails = packageData.filter(d => d.value?.severity === 'high' || d.value?.severity === 'critical');
587
- const uniqueIssues = issueDetails.reduce((acc, issue) => {
588
- const {
589
- type
590
- } = issue;
591
- if (type) {
592
- if (acc[type] === undefined) {
593
- acc[type] = {
594
- label: issue.value?.label,
595
- count: 1
596
- };
597
- } else {
598
- acc[type].count += 1;
599
- }
600
- }
601
- return acc;
602
- }, {});
603
- const format = new _chalkMarkdown$3.ChalkOrMarkdown(!!outputMarkdown);
604
- for (const issue of Object.keys(uniqueIssues)) {
605
- const issueWithLink = format.hyperlink(`${uniqueIssues[issue]?.label}`, `https://socket.dev/npm/issue/${issue}`, {
606
- fallbackToUrl: true
607
- });
608
- if (uniqueIssues[issue]?.count === 1) {
609
- console.log(`- ${issueWithLink}`);
610
- } else {
611
- console.log(`- ${issueWithLink}: ${uniqueIssues[issue]?.count}`);
612
- }
613
- }
614
- }
615
- function formatScore(score) {
616
- const error = _chalk$h.default.hex('#de7c7b');
617
- const warning = _chalk$h.default.hex('#e59361');
618
- const success = _chalk$h.default.hex('#a4cb9d');
619
- if (score > 80) {
620
- return `${success(score)}`;
621
- } else if (score < 80 && score > 60) {
622
- return `${warning(score)}`;
623
- }
624
- return `${error(score)}`;
625
- }
626
-
627
- var login = {};
628
-
629
- var _interopRequireDefault$o = vendor.interopRequireDefault.default;
630
- Object.defineProperty(login, "__esModule", {
631
- value: true
632
- });
633
- login.login = void 0;
634
- var _prompts$1 = require$$1$1;
635
- var _isInteractive = _interopRequireDefault$o(vendor.isInteractive);
636
- var _meow$n = _interopRequireDefault$o(vendor.build);
637
- var _ora$j = _interopRequireDefault$o(vendor.ora);
638
- var _terminalLink = _interopRequireDefault$o(vendor.terminalLink);
639
- var _errors$j = sdk.errors;
640
- var _formatting$k = formatting;
641
- var _sdk$i = sdk.sdk;
642
- var _settings$1 = sdk.settings;
643
- const description$7 = 'Socket API login';
644
- login.login = {
645
- description: description$7,
646
- run: async (argv, importMeta, {
647
- parentName
648
- }) => {
649
- const flags = {
650
- apiBaseUrl: {
651
- type: 'string',
652
- description: 'API server to connect to for login'
653
- },
654
- apiProxy: {
655
- type: 'string',
656
- description: 'Proxy to use when making connection to API server'
657
- }
658
- };
659
- const name = `${parentName} login`;
660
- const cli = (0, _meow$n.default)(`
661
- Usage
662
- $ ${name}
663
-
664
- Logs into the Socket API by prompting for an API key
665
-
666
- Options
667
- ${(0, _formatting$k.printFlagList)({
668
- 'api-base-url': flags['apiBaseUrl'].description,
669
- 'api-proxy': flags['apiProxy'].description
670
- }, 8)}
671
-
672
- Examples
673
- $ ${name}
674
- `, {
675
- argv,
676
- description: description$7,
677
- importMeta,
678
- flags
679
- });
680
- if (cli.input.length) {
681
- cli.showHelp();
682
- }
683
- if (!(0, _isInteractive.default)()) {
684
- throw new _errors$j.InputError('Cannot prompt for credentials in a non-interactive shell');
685
- }
686
- const apiKey = (await (0, _prompts$1.password)({
687
- message: `Enter your ${(0, _terminalLink.default)('Socket.dev API key', 'https://docs.socket.dev/docs/api-keys')} (leave blank for a public key)`
688
- })) || _sdk$i.FREE_API_KEY;
689
- let apiBaseUrl = cli.flags['apiBaseUrl'];
690
- apiBaseUrl ??= (0, _settings$1.getSetting)('apiBaseUrl') ?? undefined;
691
- let apiProxy = cli.flags['apiProxy'];
692
- apiProxy ??= (0, _settings$1.getSetting)('apiProxy') ?? undefined;
693
- const spinner = (0, _ora$j.default)('Verifying API key...').start();
694
- let orgs;
695
- try {
696
- const sdk = await (0, _sdk$i.setupSdk)(apiKey, apiBaseUrl, apiProxy);
697
- const result = await sdk.getOrganizations();
698
- if (!result.success) {
699
- throw new _errors$j.AuthError();
700
- }
701
- orgs = result.data;
702
- spinner.succeed('API key verified\n');
703
- } catch {
704
- spinner.fail('Invalid API key');
705
- return;
706
- }
707
- const nonNullish = value => value != null;
708
- const enforcedChoices = Object.values(orgs.organizations).filter(nonNullish).filter(org => org.plan === 'enterprise').map(org => ({
709
- name: org.name,
710
- value: org.id
711
- }));
712
- let enforcedOrgs = [];
713
- if (enforcedChoices.length > 1) {
714
- const id = await (0, _prompts$1.select)({
715
- message: "Which organization's policies should Socket enforce system-wide?",
716
- choices: enforcedChoices.concat({
717
- name: 'None',
718
- value: '',
719
- description: 'Pick "None" if this is a personal device'
720
- })
721
- });
722
- if (id) {
723
- enforcedOrgs = [id];
724
- }
725
- } else if (enforcedChoices.length) {
726
- const confirmOrg = await (0, _prompts$1.confirm)({
727
- message: `Should Socket enforce ${enforcedChoices[0]?.name}'s security policies system-wide?`,
728
- default: true
729
- });
730
- if (confirmOrg) {
731
- const existing = enforcedChoices[0];
732
- if (existing) {
733
- enforcedOrgs = [existing.value];
734
- }
735
- }
736
- }
737
- (0, _settings$1.updateSetting)('enforcedOrgs', enforcedOrgs);
738
- const oldKey = (0, _settings$1.getSetting)('apiKey');
739
- (0, _settings$1.updateSetting)('apiKey', apiKey);
740
- (0, _settings$1.updateSetting)('apiBaseUrl', apiBaseUrl);
741
- (0, _settings$1.updateSetting)('apiProxy', apiProxy);
742
- spinner.succeed(`API credentials ${oldKey ? 'updated' : 'set'}`);
743
- }
744
- };
745
-
746
- var logout = {};
747
-
748
- var _interopRequireDefault$n = vendor.interopRequireDefault.default;
749
- Object.defineProperty(logout, "__esModule", {
750
- value: true
751
- });
752
- logout.logout = void 0;
753
- var _meow$m = _interopRequireDefault$n(vendor.build);
754
- var _ora$i = _interopRequireDefault$n(vendor.ora);
755
- var _settings = sdk.settings;
756
- const description$6 = 'Socket API logout';
757
- logout.logout = {
758
- description: description$6,
759
- run: async (argv, importMeta, {
760
- parentName
761
- }) => {
762
- const name = `${parentName} logout`;
763
- const cli = (0, _meow$m.default)(`
764
- Usage
765
- $ ${name}
766
-
767
- Logs out of the Socket API and clears all Socket credentials from disk
768
-
769
- Examples
770
- $ ${name}
771
- `, {
772
- argv,
773
- description: description$6,
774
- importMeta
775
- });
776
- if (cli.input.length) {
777
- cli.showHelp();
778
- }
779
- (0, _settings.updateSetting)('apiKey', null);
780
- (0, _settings.updateSetting)('apiBaseUrl', null);
781
- (0, _settings.updateSetting)('apiProxy', null);
782
- (0, _settings.updateSetting)('enforcedOrgs', null);
783
- (0, _ora$i.default)('Successfully logged out').succeed();
784
- }
785
- };
786
-
787
- var npm = {};
788
-
789
- Object.defineProperty(npm, "__esModule", {
790
- value: true
791
- });
792
- npm.npm = void 0;
793
- var _nodeChild_process$1 = require$$0$1;
794
- var _nodePath$3 = require$$1;
795
- const distPath$2 = __dirname;
796
- const description$5 = 'npm wrapper functionality';
797
- npm.npm = {
798
- description: description$5,
799
- run: async (argv, _importMeta, _ctx) => {
800
- const npmVersion = (0, _nodeChild_process$1.execSync)('npm -v').toString();
801
- const wrapperPath = _nodePath$3.join(distPath$2, 'npm-cli.js');
802
- process.exitCode = 1;
803
- (0, _nodeChild_process$1.spawn)(process.execPath, [wrapperPath, ...argv], {
804
- stdio: 'inherit',
805
- env: {
806
- ...process.env,
807
- NPM_VERSION: npmVersion
808
- }
809
- }).on('exit', (code, signal) => {
810
- if (signal) {
811
- process.kill(process.pid, signal);
812
- } else if (code !== null) {
813
- process.exit(code);
814
- }
815
- });
816
- }
817
- };
818
-
819
- var npx = {};
820
-
821
- Object.defineProperty(npx, "__esModule", {
822
- value: true
823
- });
824
- npx.npx = void 0;
825
- var _child_process$1 = require$$0$1;
826
- var _nodePath$2 = require$$1;
827
- const distPath$1 = __dirname;
828
- const description$4 = 'npx wrapper functionality';
829
- npx.npx = {
830
- description: description$4,
831
- run: async (argv, _importMeta, _ctx) => {
832
- const wrapperPath = _nodePath$2.join(distPath$1, 'npx-cli.js');
833
- process.exitCode = 1;
834
- (0, _child_process$1.spawn)(process.execPath, [wrapperPath, ...argv], {
835
- stdio: 'inherit'
836
- }).on('exit', (code, signal) => {
837
- if (signal) {
838
- process.kill(process.pid, signal);
839
- } else if (code !== null) {
840
- process.exit(code);
841
- }
842
- });
843
- }
844
- };
845
-
846
- var organization = {};
847
-
848
- var _interopRequireDefault$m = vendor.interopRequireDefault.default;
849
- Object.defineProperty(organization, "__esModule", {
850
- value: true
851
- });
852
- organization.organizations = void 0;
853
- var _chalk$g = _interopRequireDefault$m(vendor.source);
854
- var _meow$l = _interopRequireDefault$m(vendor.build);
855
- var _ora$h = _interopRequireDefault$m(vendor.ora);
856
- var _apiHelpers$h = apiHelpers;
857
- var _sdk$h = sdk.sdk;
858
- var _errors$i = sdk.errors;
859
- const organizations = organization.organizations = {
860
- description: 'List organizations associated with the API key used',
861
- async run(argv, importMeta, {
862
- parentName
863
- }) {
864
- const name = `${parentName} organizations`;
865
- setupCommand$k(name, organizations.description, argv, importMeta);
866
- await fetchOrganizations();
867
- }
868
- };
869
-
870
- // Internal functions
871
-
872
- function setupCommand$k(name, description, argv, importMeta) {
873
- (0, _meow$l.default)(`
874
- Usage
875
- $ ${name}
876
- `, {
877
- argv,
878
- description,
879
- importMeta
880
- });
881
- }
882
- async function fetchOrganizations() {
883
- const apiKey = (0, _sdk$h.getDefaultKey)();
884
- if (!apiKey) {
885
- throw new _errors$i.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
886
- }
887
- const socketSdk = await (0, _sdk$h.setupSdk)(apiKey);
888
- const spinner = (0, _ora$h.default)('Fetching organizations...').start();
889
- const result = await (0, _apiHelpers$h.handleApiCall)(socketSdk.getOrganizations(), 'looking up organizations');
890
- if (result.success === false) {
891
- (0, _apiHelpers$h.handleUnsuccessfulApiResponse)('getOrganizations', result, spinner);
892
- return;
893
- }
894
- spinner.stop();
895
- const organizations = Object.values(result.data.organizations);
896
- console.log(`List of organizations associated with your API key: ${_chalk$g.default.italic(apiKey)}`);
897
- for (const o of organizations) {
898
- console.log(`
899
- Name: ${o?.name}
900
- ID: ${o?.id}
901
- Plan: ${o?.plan}
902
- `);
903
- }
904
- }
905
-
906
- var rawNpm$1 = {};
907
-
908
- var _interopRequireDefault$l = vendor.interopRequireDefault.default;
909
- Object.defineProperty(rawNpm$1, "__esModule", {
910
- value: true
911
- });
912
- rawNpm$1.rawNpm = void 0;
913
- var _nodeChild_process = require$$0$1;
914
- var _meow$k = _interopRequireDefault$l(vendor.build);
915
- var _flags$h = flags;
916
- var _formatting$j = formatting;
917
- const rawNpm = rawNpm$1.rawNpm = {
918
- description: 'Temporarily disable the Socket npm wrapper',
919
- async run(argv, importMeta, {
920
- parentName
921
- }) {
922
- const name = `${parentName} raw-npm`;
923
- setupCommand$j(name, rawNpm.description, argv, importMeta);
924
- }
925
- };
926
- function setupCommand$j(name, description, argv, importMeta) {
927
- const flags = _flags$h.validationFlags;
928
- const cli = (0, _meow$k.default)(`
929
- Usage
930
- $ ${name} <npm command>
931
-
932
- Options
933
- ${(0, _formatting$j.printFlagList)(flags, 6)}
934
-
935
- Examples
936
- $ ${name} install
937
- `, {
938
- argv,
939
- description,
940
- importMeta,
941
- flags
942
- });
943
- if (!argv[0]) {
944
- cli.showHelp();
945
- return;
946
- }
947
- (0, _nodeChild_process.spawn)('npm', [argv.join(' ')], {
948
- stdio: 'inherit',
949
- shell: true
950
- }).on('exit', (code, signal) => {
951
- if (signal) {
952
- process.kill(process.pid, signal);
953
- } else if (code !== null) {
954
- process.exit(code);
955
- }
956
- });
957
- }
958
-
959
- var rawNpx$1 = {};
960
-
961
- var _interopRequireDefault$k = vendor.interopRequireDefault.default;
962
- Object.defineProperty(rawNpx$1, "__esModule", {
963
- value: true
964
- });
965
- rawNpx$1.rawNpx = void 0;
966
- var _child_process = require$$0$1;
967
- var _meow$j = _interopRequireDefault$k(vendor.build);
968
- var _flags$g = flags;
969
- var _formatting$i = formatting;
970
- const rawNpx = rawNpx$1.rawNpx = {
971
- description: 'Temporarily disable the Socket npm/npx wrapper',
972
- async run(argv, importMeta, {
973
- parentName
974
- }) {
975
- const name = `${parentName} raw-npx`;
976
- setupCommand$i(name, rawNpx.description, argv, importMeta);
977
- }
978
- };
979
- function setupCommand$i(name, description, argv, importMeta) {
980
- const flags = _flags$g.validationFlags;
981
- const cli = (0, _meow$j.default)(`
982
- Usage
983
- $ ${name} <npx command>
984
-
985
- Options
986
- ${(0, _formatting$i.printFlagList)(flags, 6)}
987
-
988
- Examples
989
- $ ${name} install
990
- `, {
991
- argv,
992
- description,
993
- importMeta,
994
- flags
995
- });
996
- if (!argv[0]) {
997
- cli.showHelp();
998
- return;
999
- }
1000
- (0, _child_process.spawn)('npx', [argv.join(' ')], {
1001
- stdio: 'inherit',
1002
- shell: true
1003
- }).on('exit', (code, signal) => {
1004
- if (signal) {
1005
- process.kill(process.pid, signal);
1006
- } else if (code !== null) {
1007
- process.exit(code);
1008
- }
1009
- });
1010
- }
1011
-
1012
- var report = {};
1013
-
1014
- var create$5 = {};
1015
-
1016
- var view$3 = {};
1017
-
1018
- var _interopRequireDefault$j = vendor.interopRequireDefault.default;
1019
- Object.defineProperty(view$3, "__esModule", {
1020
- value: true
1021
- });
1022
- view$3.fetchReportData = fetchReportData;
1023
- view$3.formatReportDataOutput = formatReportDataOutput;
1024
- view$3.view = void 0;
1025
- var _chalk$f = _interopRequireDefault$j(vendor.source);
1026
- var _meow$i = _interopRequireDefault$j(vendor.build);
1027
- var _ora$g = _interopRequireDefault$j(vendor.ora);
1028
- var _ponyCause$3 = require$$6;
1029
- var _flags$f = flags;
1030
- var _apiHelpers$g = apiHelpers;
1031
- var _chalkMarkdown$2 = sdk.chalkMarkdown;
1032
- var _errors$h = sdk.errors;
1033
- var _formatIssues = formatIssues;
1034
- var _formatting$h = formatting;
1035
- var _sdk$g = sdk.sdk;
1036
- const view$2 = view$3.view = {
1037
- description: 'View a project report',
1038
- async run(argv, importMeta, {
1039
- parentName
1040
- }) {
1041
- const name = `${parentName} view`;
1042
- const input = setupCommand$h(name, view$2.description, argv, importMeta);
1043
- const result = input ? await fetchReportData(input.reportId, input) : undefined;
1044
- if (result) {
1045
- formatReportDataOutput(result, {
1046
- name,
1047
- ...input
1048
- });
1049
- }
1050
- }
1051
- };
1052
-
1053
- // Internal functions
1054
-
1055
- function setupCommand$h(name, description, argv, importMeta) {
1056
- const flags = {
1057
- ..._flags$f.outputFlags,
1058
- ..._flags$f.validationFlags
1059
- };
1060
- const cli = (0, _meow$i.default)(`
1061
- Usage
1062
- $ ${name} <report-identifier>
1063
-
1064
- Options
1065
- ${(0, _formatting$h.printFlagList)(flags, 6)}
1066
-
1067
- Examples
1068
- $ ${name} QXU8PmK7LfH608RAwfIKdbcHgwEd_ZeWJ9QEGv05FJUQ
1069
- `, {
1070
- argv,
1071
- description,
1072
- importMeta,
1073
- flags
1074
- });
1075
-
1076
- // Extract the input
1077
-
1078
- const {
1079
- all: includeAllIssues,
1080
- json: outputJson,
1081
- markdown: outputMarkdown,
1082
- strict
1083
- } = cli.flags;
1084
- const [reportId, ...extraInput] = cli.input;
1085
- if (!reportId) {
1086
- cli.showHelp();
1087
- return;
1088
- }
1089
-
1090
- // Validate the input
1091
-
1092
- if (extraInput.length) {
1093
- throw new _errors$h.InputError(`Can only handle a single report ID at a time, but got ${cli.input.length} report ID:s: ${cli.input.join(', ')}`);
1094
- }
1095
- return {
1096
- includeAllIssues,
1097
- outputJson,
1098
- outputMarkdown,
1099
- reportId,
1100
- strict
1101
- };
1102
- }
1103
- const MAX_TIMEOUT_RETRY = 5;
1104
- async function fetchReportData(reportId, {
1105
- includeAllIssues,
1106
- strict
1107
- }) {
1108
- // Do the API call
1109
-
1110
- const socketSdk = await (0, _sdk$g.setupSdk)();
1111
- const spinner = (0, _ora$g.default)(`Fetching report with ID ${reportId} (this could take a while)`).start();
1112
- let result;
1113
- for (let retry = 1; !result; ++retry) {
1114
- try {
1115
- result = await (0, _apiHelpers$g.handleApiCall)(socketSdk.getReport(reportId), 'fetching report');
1116
- } catch (err) {
1117
- if (retry >= MAX_TIMEOUT_RETRY || !(err instanceof _ponyCause$3.ErrorWithCause) || err.cause?.cause?.response?.statusCode !== 524) {
1118
- throw err;
1119
- }
1120
- }
1121
- }
1122
- if (result.success === false) {
1123
- return (0, _apiHelpers$g.handleUnsuccessfulApiResponse)('getReport', result, spinner);
1124
- }
1125
-
1126
- // Conclude the status of the API call
1127
-
1128
- if (strict) {
1129
- if (result.data.healthy) {
1130
- spinner.succeed('Report result is healthy and great!');
1131
- } else {
1132
- spinner.fail('Report result deemed unhealthy for project');
1133
- }
1134
- } else if (result.data.healthy === false) {
1135
- const severityCount = (0, _formatIssues.getSeverityCount)(result.data.issues, includeAllIssues ? undefined : 'high');
1136
- const issueSummary = (0, _formatIssues.formatSeverityCount)(severityCount);
1137
- spinner.succeed(`Report has these issues: ${issueSummary}`);
1138
- } else {
1139
- spinner.succeed('Report has no issues');
1140
- }
1141
- return result.data;
1142
- }
1143
- function formatReportDataOutput(data, {
1144
- name,
1145
- outputJson,
1146
- outputMarkdown,
1147
- reportId,
1148
- strict
1149
- }) {
1150
- if (outputJson) {
1151
- console.log(JSON.stringify(data, undefined, 2));
1152
- } else {
1153
- const format = new _chalkMarkdown$2.ChalkOrMarkdown(!!outputMarkdown);
1154
- console.log('\nDetailed info on socket.dev: ' + format.hyperlink(reportId, data.url, {
1155
- fallbackToUrl: true
1156
- }));
1157
- if (!outputMarkdown) {
1158
- console.log(_chalk$f.default.dim('\nOr rerun', _chalk$f.default.italic(name), 'using the', _chalk$f.default.italic('--json'), 'flag to get full JSON output'));
1159
- }
1160
- }
1161
- if (strict && data.healthy === false) {
1162
- process.exit(1);
1163
- }
1164
- }
1165
-
1166
- var _interopRequireDefault$i = vendor.interopRequireDefault.default;
1167
- Object.defineProperty(create$5, "__esModule", {
1168
- value: true
1169
- });
1170
- create$5.create = void 0;
1171
- var _nodePath$1 = require$$1;
1172
- var _betterAjvErrors = require$$2;
1173
- var _config = require$$3;
1174
- var _meow$h = _interopRequireDefault$i(vendor.build);
1175
- var _ora$f = _interopRequireDefault$i(vendor.ora);
1176
- var _ponyCause$2 = require$$6;
1177
- var _view$2 = view$3;
1178
- var _flags$e = flags;
1179
- var _apiHelpers$f = apiHelpers;
1180
- var _chalkMarkdown$1 = sdk.chalkMarkdown;
1181
- var _errors$g = sdk.errors;
1182
- var _formatting$g = formatting;
1183
- var _misc$1 = misc;
1184
- var _pathResolve$1 = pathResolve.pathResolve;
1185
- var _sdk$f = sdk.sdk;
1186
- const create$4 = create$5.create = {
1187
- description: 'Create a project report',
1188
- async run(argv, importMeta, {
1189
- parentName
1190
- }) {
1191
- const name = `${parentName} create`;
1192
- const input = await setupCommand$g(name, create$4.description, argv, importMeta);
1193
- if (input) {
1194
- const {
1195
- config,
1196
- cwd,
1197
- debugLog,
1198
- dryRun,
1199
- includeAllIssues,
1200
- outputJson,
1201
- outputMarkdown,
1202
- packagePaths,
1203
- strict,
1204
- view
1205
- } = input;
1206
- const result = input && (await createReport(packagePaths, {
1207
- config,
1208
- cwd,
1209
- debugLog,
1210
- dryRun
1211
- }));
1212
- if (result && view) {
1213
- const reportId = result.data.id;
1214
- const reportData = input && (await (0, _view$2.fetchReportData)(reportId, {
1215
- includeAllIssues,
1216
- strict
1217
- }));
1218
- if (reportData) {
1219
- (0, _view$2.formatReportDataOutput)(reportData, {
1220
- includeAllIssues,
1221
- name,
1222
- outputJson,
1223
- outputMarkdown,
1224
- reportId,
1225
- strict
1226
- });
1227
- }
1228
- } else if (result) {
1229
- formatReportCreationOutput(result.data, {
1230
- outputJson,
1231
- outputMarkdown
1232
- });
1233
- }
1234
- }
1235
- }
1236
- };
1237
-
1238
- // Internal functions
1239
-
1240
- async function setupCommand$g(name, description, argv, importMeta) {
1241
- const flags = {
1242
- ..._flags$e.outputFlags,
1243
- ..._flags$e.validationFlags,
1244
- debug: {
1245
- type: 'boolean',
1246
- shortFlag: 'd',
1247
- default: false,
1248
- description: 'Output debug information'
1249
- },
1250
- dryRun: {
1251
- type: 'boolean',
1252
- default: false,
1253
- description: 'Only output what will be done without actually doing it'
1254
- },
1255
- view: {
1256
- type: 'boolean',
1257
- shortFlag: 'v',
1258
- default: false,
1259
- description: 'Will wait for and return the created report'
1260
- }
1261
- };
1262
- const cli = (0, _meow$h.default)(`
1263
- Usage
1264
- $ ${name} <paths-to-package-folders-and-files>
1265
-
1266
- Uploads the specified "package.json" and lock files for JavaScript, Python, and Go dependency manifests.
1267
- If any folder is specified, the ones found in there recursively are uploaded.
1268
-
1269
- Supports globbing such as "**/package.json", "**/requirements.txt", "**/pyproject.toml", and "**/go.mod".
1270
-
1271
- Ignores any file specified in your project's ".gitignore", your project's
1272
- "socket.yml" file's "projectIgnorePaths" and also has a sensible set of
1273
- default ignores from the "ignore-by-default" module.
1274
-
1275
- Options
1276
- ${(0, _formatting$g.printFlagList)({
1277
- all: 'Include all issues',
1278
- debug: 'Output debug information',
1279
- 'dry-run': 'Only output what will be done without actually doing it',
1280
- json: 'Output result as json',
1281
- markdown: 'Output result as markdown',
1282
- strict: 'Exits with an error code if any matching issues are found',
1283
- view: 'Will wait for and return the created report'
1284
- }, 6)}
1285
-
1286
- Examples
1287
- $ ${name} .
1288
- $ ${name} '**/package.json'
1289
- $ ${name} /path/to/a/package.json /path/to/another/package.json
1290
- $ ${name} . --view --json
1291
- `, {
1292
- argv,
1293
- description,
1294
- importMeta,
1295
- flags
1296
- });
1297
- const {
1298
- all: includeAllIssues,
1299
- dryRun,
1300
- json: outputJson,
1301
- markdown: outputMarkdown,
1302
- strict,
1303
- view
1304
- } = cli.flags;
1305
- if (!cli.input[0]) {
1306
- cli.showHelp();
1307
- return;
1308
- }
1309
- const debugLog = (0, _misc$1.createDebugLogger)(!dryRun || cli.flags['debug']);
1310
-
1311
- // TODO: Allow setting a custom cwd and/or configFile path?
1312
- const cwd = process.cwd();
1313
- const absoluteConfigPath = _nodePath$1.join(cwd, 'socket.yml');
1314
- const config = await (0, _config.readSocketConfig)(absoluteConfigPath).catch(cause => {
1315
- if (cause && typeof cause === 'object' && cause instanceof _config.SocketValidationError) {
1316
- // Inspired by workbox-build: https://github.com/GoogleChrome/workbox/blob/95f97a207fd51efb3f8a653f6e3e58224183a778/packages/workbox-build/src/lib/validate-options.ts#L68-L71
1317
- const betterErrors = (0, _betterAjvErrors.betterAjvErrors)({
1318
- basePath: 'config',
1319
- data: cause.data,
1320
- errors: cause.validationErrors,
1321
- schema: cause.schema
1322
- });
1323
- throw new _errors$g.InputError('The socket.yml config is not valid', betterErrors.map(err => `[${err.path}] ${err.message}.${err.suggestion ? err.suggestion : ''}`).join('\n'));
1324
- } else {
1325
- throw new _ponyCause$2.ErrorWithCause('Failed to read socket.yml config', {
1326
- cause
1327
- });
1328
- }
1329
- });
1330
- const socketSdk = await (0, _sdk$f.setupSdk)();
1331
- const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
1332
- if (!res.success) (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$f.default)());
1333
- return res.data;
1334
- }).catch(cause => {
1335
- throw new _ponyCause$2.ErrorWithCause('Failed getting supported files for report', {
1336
- cause
1337
- });
1338
- });
1339
- const packagePaths = await (0, _pathResolve$1.getPackageFiles)(cwd, cli.input, config, supportedFiles, debugLog);
1340
- return {
1341
- config,
1342
- cwd,
1343
- debugLog,
1344
- dryRun,
1345
- includeAllIssues,
1346
- outputJson,
1347
- outputMarkdown,
1348
- packagePaths,
1349
- strict,
1350
- view
1351
- };
1352
- }
1353
- async function createReport(packagePaths, {
1354
- config,
1355
- cwd,
1356
- debugLog,
1357
- dryRun
1358
- }) {
1359
- debugLog('Uploading:', packagePaths.join(`\n${_chalkMarkdown$1.logSymbols.info} Uploading: `));
1360
- if (dryRun) {
1361
- return;
1362
- }
1363
- const socketSdk = await (0, _sdk$f.setupSdk)();
1364
- const spinner = (0, _ora$f.default)(`Creating report with ${packagePaths.length} package files`).start();
1365
- const apiCall = socketSdk.createReportFromFilePaths(packagePaths, cwd, config?.issueRules);
1366
- const result = await (0, _apiHelpers$f.handleApiCall)(apiCall, 'creating report');
1367
- if (result.success === false) {
1368
- return (0, _apiHelpers$f.handleUnsuccessfulApiResponse)('createReport', result, spinner);
1369
- }
1370
-
1371
- // Conclude the status of the API call
1372
-
1373
- spinner.succeed();
1374
- return result;
1375
- }
1376
- function formatReportCreationOutput(data, {
1377
- outputJson,
1378
- outputMarkdown
1379
- }) {
1380
- if (outputJson) {
1381
- console.log(JSON.stringify(data, undefined, 2));
1382
- return;
1383
- }
1384
- const format = new _chalkMarkdown$1.ChalkOrMarkdown(!!outputMarkdown);
1385
- console.log('\nNew report: ' + format.hyperlink(data.id, data.url, {
1386
- fallbackToUrl: true
1387
- }));
1388
- }
1389
-
1390
- var meowWithSubcommands$1 = {};
1391
-
1392
- var _interopRequireDefault$h = vendor.interopRequireDefault.default;
1393
- Object.defineProperty(meowWithSubcommands$1, "__esModule", {
1394
- value: true
1395
- });
1396
- meowWithSubcommands$1.meowWithSubcommands = meowWithSubcommands;
1397
- var _meow$g = _interopRequireDefault$h(vendor.build);
1398
- var _formatting$f = formatting;
1399
- function sortKeys(object) {
1400
- return Object.fromEntries(Object.keys(object).sort().map(k => [k, object[k]]));
1401
- }
1402
- async function meowWithSubcommands(subcommands, options) {
1403
- const {
1404
- aliases = {},
1405
- argv,
1406
- name,
1407
- importMeta,
1408
- ...additionalOptions
1409
- } = options;
1410
- const [commandOrAliasName, ...rawCommandArgv] = argv;
1411
-
1412
- // If we got at least some args, then lets find out if we can find a command
1413
- if (commandOrAliasName) {
1414
- const alias = aliases[commandOrAliasName];
1415
-
1416
- // First: Resolve argv data from alias if its an alias that's been given
1417
- const [commandName, ...commandArgv] = alias ? [...alias.argv, ...rawCommandArgv] : [commandOrAliasName, ...rawCommandArgv];
1418
-
1419
- // Second: Find a command definition using that data
1420
- const commandDefinition = commandName ? subcommands[commandName] : undefined;
1421
-
1422
- // Third: If a valid command has been found, then we run it...
1423
- if (commandDefinition) {
1424
- return await commandDefinition.run(commandArgv, importMeta, {
1425
- parentName: name
1426
- });
1427
- }
1428
- }
1429
-
1430
- // ...else we provide basic instructions and help
1431
- const cli = (0, _meow$g.default)(`
1432
- Usage
1433
- $ ${name} <command>
1434
-
1435
- Commands
1436
- ${(0, _formatting$f.printHelpList)({
1437
- ...sortKeys(subcommands),
1438
- ...sortKeys(aliases)
1439
- }, 6)}
1440
-
1441
- Options
1442
- ${(0, _formatting$f.printFlagList)({}, 6)}
1443
-
1444
- Examples
1445
- $ ${name} --help
1446
- `, {
1447
- argv,
1448
- importMeta,
1449
- ...additionalOptions
1450
- });
1451
- cli.showHelp();
1452
- }
1453
-
1454
- Object.defineProperty(report, "__esModule", {
1455
- value: true
1456
- });
1457
- report.report = void 0;
1458
- var _create$2 = create$5;
1459
- var _view$1 = view$3;
1460
- var _meowWithSubcommands$4 = meowWithSubcommands$1;
1461
- const description$3 = '[Deprecated] Project report related commands';
1462
- report.report = {
1463
- description: description$3,
1464
- run: async (argv, importMeta, {
1465
- parentName
1466
- }) => {
1467
- await (0, _meowWithSubcommands$4.meowWithSubcommands)({
1468
- create: _create$2.create,
1469
- view: _view$1.view
1470
- }, {
1471
- argv,
1472
- description: description$3,
1473
- importMeta,
1474
- name: parentName + ' report'
1475
- });
1476
- }
1477
- };
1478
-
1479
- var wrapper$1 = {};
1480
-
1481
- var _interopRequireDefault$g = vendor.interopRequireDefault.default;
1482
- Object.defineProperty(wrapper$1, "__esModule", {
1483
- value: true
1484
- });
1485
- wrapper$1.wrapper = void 0;
1486
- var _nodeFs$1 = require$$0;
1487
- var _nodeOs = require$$0$2;
1488
- var _nodeReadline = require$$3$1;
1489
- var _meow$f = _interopRequireDefault$g(vendor.build);
1490
- var _flags$d = flags;
1491
- var _formatting$e = formatting;
1492
- const BASH_FILE = `${_nodeOs.homedir()}/.bashrc`;
1493
- const ZSH_BASH_FILE = `${_nodeOs.homedir()}/.zshrc`;
1494
- const wrapper = wrapper$1.wrapper = {
1495
- description: 'Enable or disable the Socket npm/npx wrapper',
1496
- async run(argv, importMeta, {
1497
- parentName
1498
- }) {
1499
- const name = `${parentName} wrapper`;
1500
- setupCommand$f(name, wrapper.description, argv, importMeta);
1501
- }
1502
- };
1503
- function setupCommand$f(name, description, argv, importMeta) {
1504
- const flags = _flags$d.commandFlags;
1505
- const cli = (0, _meow$f.default)(`
1506
- Usage
1507
- $ ${name} <flag>
1508
-
1509
- Options
1510
- ${(0, _formatting$e.printFlagList)(flags, 6)}
1511
-
1512
- Examples
1513
- $ ${name} --enable
1514
- $ ${name} --disable
1515
- `, {
1516
- argv,
1517
- description,
1518
- importMeta,
1519
- flags
1520
- });
1521
- const {
1522
- enable,
1523
- disable
1524
- } = cli.flags;
1525
- if (argv[0] === '--postinstall') {
1526
- const socketWrapperEnabled = _nodeFs$1.existsSync(BASH_FILE) && checkSocketWrapperAlreadySetup(BASH_FILE) || _nodeFs$1.existsSync(ZSH_BASH_FILE) && checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
1527
- if (!socketWrapperEnabled) {
1528
- installSafeNpm(`The Socket CLI is now successfully installed! 🎉
1529
-
1530
- To better protect yourself against supply-chain attacks, our "safe npm" wrapper can warn you about malicious packages whenever you run 'npm install'.
1531
-
1532
- Do you want to install "safe npm" (this will create an alias to the socket-npm command)? (y/n)`);
1533
- }
1534
- return;
1535
- }
1536
- if (!enable && !disable) {
1537
- cli.showHelp();
1538
- return;
1539
- }
1540
- if (enable) {
1541
- if (_nodeFs$1.existsSync(BASH_FILE)) {
1542
- const socketWrapperEnabled = checkSocketWrapperAlreadySetup(BASH_FILE);
1543
- !socketWrapperEnabled && addAlias(BASH_FILE);
1544
- }
1545
- if (_nodeFs$1.existsSync(ZSH_BASH_FILE)) {
1546
- const socketWrapperEnabled = checkSocketWrapperAlreadySetup(ZSH_BASH_FILE);
1547
- !socketWrapperEnabled && addAlias(ZSH_BASH_FILE);
1548
- }
1549
- } else if (disable) {
1550
- if (_nodeFs$1.existsSync(BASH_FILE)) {
1551
- removeAlias(BASH_FILE);
1552
- }
1553
- if (_nodeFs$1.existsSync(ZSH_BASH_FILE)) {
1554
- removeAlias(ZSH_BASH_FILE);
1555
- }
1556
- }
1557
- if (!_nodeFs$1.existsSync(BASH_FILE) && !_nodeFs$1.existsSync(ZSH_BASH_FILE)) {
1558
- console.error('There was an issue setting up the alias in your bash profile');
1559
- }
1560
- return;
1561
- }
1562
- const installSafeNpm = query => {
1563
- console.log(`
1564
- _____ _ _
1565
- | __|___ ___| |_ ___| |_
1566
- |__ | . | _| '_| -_| _|
1567
- |_____|___|___|_,_|___|_|
1568
-
1569
- `);
1570
- const rl = _nodeReadline.createInterface({
1571
- input: process.stdin,
1572
- output: process.stdout
1573
- });
1574
- return askQuestion(rl, query);
1575
- };
1576
- const askQuestion = (rl, query) => {
1577
- rl.question(query, ans => {
1578
- if (ans.toLowerCase() === 'y') {
1579
- try {
1580
- if (_nodeFs$1.existsSync(BASH_FILE)) {
1581
- addAlias(BASH_FILE);
1582
- }
1583
- if (_nodeFs$1.existsSync(ZSH_BASH_FILE)) {
1584
- addAlias(ZSH_BASH_FILE);
1585
- }
1586
- } catch (e) {
1587
- throw new Error(`There was an issue setting up the alias: ${e}`);
1588
- }
1589
- rl.close();
1590
- } else if (ans.toLowerCase() !== 'n') {
1591
- askQuestion(rl, 'Incorrect input: please enter either y (yes) or n (no): ');
1592
- } else {
1593
- rl.close();
1594
- }
1595
- });
1596
- };
1597
- const addAlias = file => {
1598
- return _nodeFs$1.appendFile(file, 'alias npm="socket npm"\nalias npx="socket npx"\n', err => {
1599
- if (err) {
1600
- return new Error(`There was an error setting up the alias: ${err}`);
1601
- }
1602
- console.log(`
1603
- The alias was added to ${file}. Running 'npm install' will now be wrapped in Socket's "safe npm" 🎉
1604
- If you want to disable it at any time, run \`socket wrapper --disable\`
1605
- `);
1606
- });
1607
- };
1608
- const removeAlias = file => {
1609
- return _nodeFs$1.readFile(file, 'utf8', function (err, data) {
1610
- if (err) {
1611
- console.error(`There was an error removing the alias: ${err}`);
1612
- return;
1613
- }
1614
- const linesWithoutSocketAlias = data.split('\n').filter(l => l !== 'alias npm="socket npm"' && l !== 'alias npx="socket npx"');
1615
- const updatedFileContent = linesWithoutSocketAlias.join('\n');
1616
- _nodeFs$1.writeFile(file, updatedFileContent, function (err) {
1617
- if (err) {
1618
- console.log(err);
1619
- return;
1620
- } else {
1621
- console.log(`\nThe alias was removed from ${file}. Running 'npm install' will now run the standard npm command.\n`);
1622
- }
1623
- });
1624
- });
1625
- };
1626
- const checkSocketWrapperAlreadySetup = file => {
1627
- const fileContent = _nodeFs$1.readFileSync(file, 'utf-8');
1628
- const linesWithSocketAlias = fileContent.split('\n').filter(l => l === 'alias npm="socket npm"' || l === 'alias npx="socket npx"');
1629
- if (linesWithSocketAlias.length) {
1630
- console.log(`The Socket npm/npx wrapper is set up in your bash profile (${file}).`);
1631
- return true;
1632
- }
1633
- return false;
1634
- };
1635
-
1636
- var scan = {};
1637
-
1638
- var create$3 = {};
1639
-
1640
- var _interopRequireDefault$f = vendor.interopRequireDefault.default;
1641
- Object.defineProperty(create$3, "__esModule", {
1642
- value: true
1643
- });
1644
- create$3.create = void 0;
1645
- var _nodeProcess = require$$0$3;
1646
- var _promises = require$$2$1;
1647
- var _chalk$e = _interopRequireDefault$f(vendor.source);
1648
- var _meow$e = _interopRequireDefault$f(vendor.build);
1649
- var _open = _interopRequireDefault$f(vendor.open);
1650
- var _ora$e = _interopRequireDefault$f(vendor.ora);
1651
- var _ponyCause$1 = require$$6;
1652
- var _apiHelpers$e = apiHelpers;
1653
- var _formatting$d = formatting;
1654
- var _misc = misc;
1655
- var _pathResolve = pathResolve.pathResolve;
1656
- var _sdk$e = sdk.sdk;
1657
- var _errors$f = sdk.errors;
1658
- const create$2 = create$3.create = {
1659
- description: 'Create a scan',
1660
- async run(argv, importMeta, {
1661
- parentName
1662
- }) {
1663
- const name = `${parentName} create`;
1664
- const input = await setupCommand$e(name, create$2.description, argv, importMeta);
1665
- if (input) {
1666
- const apiKey = (0, _sdk$e.getDefaultKey)();
1667
- if (!apiKey) {
1668
- throw new _errors$f.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
1669
- }
1670
- const spinnerText = 'Creating a scan... \n';
1671
- const spinner = (0, _ora$e.default)(spinnerText).start();
1672
- await createFullScan(input, spinner, apiKey);
1673
- }
1674
- }
1675
- };
1676
- const createFullScanFlags = {
1677
- repo: {
1678
- type: 'string',
1679
- shortFlag: 'r',
1680
- default: '',
1681
- description: 'Repository name'
1682
- },
1683
- branch: {
1684
- type: 'string',
1685
- shortFlag: 'b',
1686
- default: '',
1687
- description: 'Branch name'
1688
- },
1689
- commitMessage: {
1690
- type: 'string',
1691
- shortFlag: 'm',
1692
- default: '',
1693
- description: 'Commit message'
1694
- },
1695
- commitHash: {
1696
- type: 'string',
1697
- shortFlag: 'ch',
1698
- default: '',
1699
- description: 'Commit hash'
1700
- },
1701
- pullRequest: {
1702
- type: 'number',
1703
- shortFlag: 'pr',
1704
- description: 'Commit hash'
1705
- },
1706
- committers: {
1707
- type: 'string',
1708
- shortFlag: 'c',
1709
- default: '',
1710
- description: 'Committers'
1711
- },
1712
- defaultBranch: {
1713
- type: 'boolean',
1714
- shortFlag: 'db',
1715
- default: false,
1716
- description: 'Make default branch'
1717
- },
1718
- pendingHead: {
1719
- type: 'boolean',
1720
- shortFlag: 'ph',
1721
- default: false,
1722
- description: 'Set as pending head'
1723
- },
1724
- tmp: {
1725
- type: 'boolean',
1726
- shortFlag: 't',
1727
- default: false,
1728
- description: 'Set the visibility (true/false) of the scan in your dashboard'
1729
- }
1730
- };
1731
-
1732
- // Internal functions
1733
-
1734
- async function setupCommand$e(name, description, argv, importMeta) {
1735
- const flags = {
1736
- ...createFullScanFlags
1737
- };
1738
- const cli = (0, _meow$e.default)(`
1739
- Usage
1740
- $ ${name} [...options]
1741
-
1742
- Options
1743
- ${(0, _formatting$d.printFlagList)(flags, 6)}
1744
-
1745
- Examples
1746
- $ ${name} --org=FakeOrg --repo=test-repo --branch=main ./package.json
1747
- `, {
1748
- argv,
1749
- description,
1750
- importMeta,
1751
- flags
1752
- });
1753
- const {
1754
- repo: repoName,
1755
- branch: branchName,
1756
- commitMessage,
1757
- defaultBranch,
1758
- pendingHead,
1759
- tmp,
1760
- committers,
1761
- commitHash,
1762
- pullRequest
1763
- } = cli.flags;
1764
- if (!cli.input[0]) {
1765
- cli.showHelp();
1766
- return;
1767
- }
1768
- const {
1769
- 0: orgSlug = ''
1770
- } = cli.input;
1771
- const cwd = process.cwd();
1772
- const socketSdk = await (0, _sdk$e.setupSdk)();
1773
- const supportedFiles = await socketSdk.getReportSupportedFiles().then(res => {
1774
- if (!res.success) (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('getReportSupportedFiles', res, (0, _ora$e.default)());
1775
- return res.data;
1776
- }).catch( /** @type {(cause: Error) => never} */
1777
- cause => {
1778
- throw new _ponyCause$1.ErrorWithCause('Failed getting supported files for report', {
1779
- cause
1780
- });
1781
- });
1782
- const debugLog = (0, _misc.createDebugLogger)(false);
1783
- const packagePaths = await (0, _pathResolve.getPackageFilesFullScans)(cwd, cli.input, supportedFiles, debugLog);
1784
- if (!repoName || !branchName || !packagePaths.length) {
1785
- console.error(`${_chalk$e.default.bgRed('Input error')}: Please provide the required fields:\n
1786
- - Repository name using --repo,\n
1787
- - Branch name using --branch\n
1788
- - At least one file path (e.g. ./package.json).\n`);
1789
- cli.showHelp();
1790
- return;
1791
- }
1792
- return {
1793
- orgSlug,
1794
- repoName,
1795
- branchName,
1796
- commitMessage,
1797
- defaultBranch,
1798
- pendingHead,
1799
- tmp,
1800
- packagePaths,
1801
- commitHash,
1802
- committers,
1803
- pullRequest
1804
- };
1805
- }
1806
- async function createFullScan(input, spinner, apiKey) {
1807
- const socketSdk = await (0, _sdk$e.setupSdk)(apiKey);
1808
- const {
1809
- orgSlug,
1810
- repoName,
1811
- branchName,
1812
- commitMessage,
1813
- defaultBranch,
1814
- pendingHead,
1815
- tmp,
1816
- packagePaths
1817
- } = input;
1818
- const result = await (0, _apiHelpers$e.handleApiCall)(socketSdk.createOrgFullScan(orgSlug, {
1819
- repo: repoName,
1820
- branch: branchName,
1821
- commit_message: commitMessage,
1822
- make_default_branch: defaultBranch,
1823
- set_as_pending_head: pendingHead,
1824
- tmp
1825
- }, packagePaths), 'Creating scan');
1826
- if (!result.success) {
1827
- (0, _apiHelpers$e.handleUnsuccessfulApiResponse)('CreateOrgFullScan', result, spinner);
1828
- return;
1829
- }
1830
- spinner.stop();
1831
- console.log('\n✅ Scan created successfully\n');
1832
- const link = _chalk$e.default.hex('#00FFFF').underline(`${result.data.html_report_url}`);
1833
- console.log(`Available at: ${link}\n`);
1834
- const rl = _promises.createInterface({
1835
- input: _nodeProcess.stdin,
1836
- output: _nodeProcess.stdout
1837
- });
1838
- const answer = await rl.question('Would you like to open it in your browser? (y/n)');
1839
- if (answer.toLowerCase() === 'y') {
1840
- await (0, _open.default)(`${result.data.html_report_url}`);
1841
- }
1842
- rl.close();
1843
- }
1844
-
1845
- var _delete$3 = {};
1846
-
1847
- var _interopRequireDefault$e = vendor.interopRequireDefault.default;
1848
- Object.defineProperty(_delete$3, "__esModule", {
1849
- value: true
1850
- });
1851
- _delete$3.del = void 0;
1852
- var _chalk$d = _interopRequireDefault$e(vendor.source);
1853
- var _meow$d = _interopRequireDefault$e(vendor.build);
1854
- var _ora$d = _interopRequireDefault$e(vendor.ora);
1855
- var _flags$c = flags;
1856
- var _apiHelpers$d = apiHelpers;
1857
- var _formatting$c = formatting;
1858
- var _sdk$d = sdk.sdk;
1859
- var _errors$e = sdk.errors;
1860
- const del$1 = _delete$3.del = {
1861
- description: 'Delete a scan',
1862
- async run(argv, importMeta, {
1863
- parentName
1864
- }) {
1865
- const name = `${parentName} del`;
1866
- const input = setupCommand$d(name, del$1.description, argv, importMeta);
1867
- if (input) {
1868
- const apiKey = (0, _sdk$d.getDefaultKey)();
1869
- if (!apiKey) {
1870
- throw new _errors$e.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
1871
- }
1872
- const spinnerText = 'Deleting scan...';
1873
- const spinner = (0, _ora$d.default)(spinnerText).start();
1874
- await deleteOrgFullScan(input.orgSlug, input.fullScanId, spinner, apiKey);
1875
- }
1876
- }
1877
- };
1878
-
1879
- // Internal functions
1880
-
1881
- function setupCommand$d(name, description, argv, importMeta) {
1882
- const flags = {
1883
- ..._flags$c.outputFlags
1884
- };
1885
- const cli = (0, _meow$d.default)(`
1886
- Usage
1887
- $ ${name} <org slug> <scan ID>
1888
-
1889
- Options
1890
- ${(0, _formatting$c.printFlagList)(flags, 6)}
1891
-
1892
- Examples
1893
- $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
1894
- `, {
1895
- argv,
1896
- description,
1897
- importMeta,
1898
- flags
1899
- });
1900
- const {
1901
- json: outputJson,
1902
- markdown: outputMarkdown
1903
- } = cli.flags;
1904
- if (cli.input.length < 2) {
1905
- console.error(`${_chalk$d.default.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
1906
- cli.showHelp();
1907
- return;
1908
- }
1909
- const {
1910
- 0: orgSlug = '',
1911
- 1: fullScanId = ''
1912
- } = cli.input;
1913
- return {
1914
- outputJson,
1915
- outputMarkdown,
1916
- orgSlug,
1917
- fullScanId
1918
- };
1919
- }
1920
- async function deleteOrgFullScan(orgSlug, fullScanId, spinner, apiKey) {
1921
- const socketSdk = await (0, _sdk$d.setupSdk)(apiKey);
1922
- const result = await (0, _apiHelpers$d.handleApiCall)(socketSdk.deleteOrgFullScan(orgSlug, fullScanId), 'Deleting scan');
1923
- if (!result.success) {
1924
- (0, _apiHelpers$d.handleUnsuccessfulApiResponse)('deleteOrgFullScan', result, spinner);
1925
- return;
1926
- }
1927
- spinner.stop();
1928
- console.log('\n ✅ Scan deleted successfully\n');
1929
- }
1930
-
1931
- var list$3 = {};
1932
-
1933
- var _interopRequireDefault$d = vendor.interopRequireDefault.default;
1934
- Object.defineProperty(list$3, "__esModule", {
1935
- value: true
1936
- });
1937
- list$3.list = void 0;
1938
- var _chalk$c = _interopRequireDefault$d(vendor.source);
1939
- var _chalkTable$3 = require$$2$2;
1940
- var _meow$c = _interopRequireDefault$d(vendor.build);
1941
- var _ora$c = _interopRequireDefault$d(vendor.ora);
1942
- var _flags$b = flags;
1943
- var _apiHelpers$c = apiHelpers;
1944
- var _formatting$b = formatting;
1945
- var _sdk$c = sdk.sdk;
1946
- var _errors$d = sdk.errors;
1947
- // @ts-ignore
1948
-
1949
- const list$2 = list$3.list = {
1950
- description: 'List scans for an organization',
1951
- async run(argv, importMeta, {
1952
- parentName
1953
- }) {
1954
- const name = `${parentName} list`;
1955
- const input = setupCommand$c(name, list$2.description, argv, importMeta);
1956
- if (input) {
1957
- const apiKey = (0, _sdk$c.getDefaultKey)();
1958
- if (!apiKey) {
1959
- throw new _errors$d.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
1960
- }
1961
- const spinnerText = 'Listing scans... \n';
1962
- const spinner = (0, _ora$c.default)(spinnerText).start();
1963
- await listOrgFullScan(input.orgSlug, input, spinner, apiKey);
1964
- }
1965
- }
1966
- };
1967
- const listFullScanFlags = {
1968
- sort: {
1969
- type: 'string',
1970
- shortFlag: 's',
1971
- default: 'created_at',
1972
- description: 'Sorting option (`name` or `created_at`) - default is `created_at`'
1973
- },
1974
- direction: {
1975
- type: 'string',
1976
- shortFlag: 'd',
1977
- default: 'desc',
1978
- description: 'Direction option (`desc` or `asc`) - Default is `desc`'
1979
- },
1980
- perPage: {
1981
- type: 'number',
1982
- shortFlag: 'pp',
1983
- default: 30,
1984
- description: 'Results per page - Default is 30'
1985
- },
1986
- page: {
1987
- type: 'number',
1988
- shortFlag: 'p',
1989
- default: 1,
1990
- description: 'Page number - Default is 1'
1991
- },
1992
- fromTime: {
1993
- type: 'string',
1994
- shortFlag: 'f',
1995
- default: '',
1996
- description: 'From time - as a unix timestamp'
1997
- },
1998
- untilTime: {
1999
- type: 'string',
2000
- shortFlag: 'u',
2001
- default: '',
2002
- description: 'Until time - as a unix timestamp'
2003
- }
2004
- };
2005
-
2006
- // Internal functions
2007
-
2008
- function setupCommand$c(name, description, argv, importMeta) {
2009
- const flags = {
2010
- ..._flags$b.outputFlags,
2011
- ...listFullScanFlags
2012
- };
2013
- const cli = (0, _meow$c.default)(`
2014
- Usage
2015
- $ ${name} <org slug>
2016
-
2017
- Options
2018
- ${(0, _formatting$b.printFlagList)(flags, 6)}
2019
-
2020
- Examples
2021
- $ ${name} FakeOrg
2022
- `, {
2023
- argv,
2024
- description,
2025
- importMeta,
2026
- flags
2027
- });
2028
- const {
2029
- json: outputJson,
2030
- markdown: outputMarkdown,
2031
- sort,
2032
- direction,
2033
- perPage,
2034
- page,
2035
- fromTime,
2036
- untilTime
2037
- } = cli.flags;
2038
- if (!cli.input[0]) {
2039
- console.error(`${_chalk$c.default.bgRed('Input error')}: Please specify an organization slug.\n`);
2040
- cli.showHelp();
2041
- return;
2042
- }
2043
- const {
2044
- 0: orgSlug = ''
2045
- } = cli.input;
2046
- return {
2047
- outputJson,
2048
- outputMarkdown,
2049
- orgSlug,
2050
- sort,
2051
- direction,
2052
- per_page: perPage,
2053
- page,
2054
- from_time: fromTime,
2055
- until_time: untilTime
2056
- };
2057
- }
2058
- async function listOrgFullScan(orgSlug, input, spinner, apiKey) {
2059
- const socketSdk = await (0, _sdk$c.setupSdk)(apiKey);
2060
- const result = await (0, _apiHelpers$c.handleApiCall)(socketSdk.getOrgFullScanList(orgSlug, input), 'Listing scans');
2061
- if (!result.success) {
2062
- (0, _apiHelpers$c.handleUnsuccessfulApiResponse)('getOrgFullScanList', result, spinner);
2063
- return;
2064
- }
2065
- spinner.stop();
2066
- console.log(`\n Listing scans for: ${orgSlug}\n`);
2067
- const options = {
2068
- columns: [{
2069
- field: 'id',
2070
- name: _chalk$c.default.magenta('ID')
2071
- }, {
2072
- field: 'report_url',
2073
- name: _chalk$c.default.magenta('Scan URL')
2074
- }, {
2075
- field: 'branch',
2076
- name: _chalk$c.default.magenta('Branch')
2077
- }, {
2078
- field: 'created_at',
2079
- name: _chalk$c.default.magenta('Created at')
2080
- }]
2081
- };
2082
- const formattedResults = result.data.results.map(d => {
2083
- return {
2084
- id: d.id,
2085
- report_url: _chalk$c.default.underline(`${d.html_report_url}`),
2086
- created_at: d.created_at ? new Date(d.created_at).toLocaleDateString('en-us', {
2087
- year: 'numeric',
2088
- month: 'numeric',
2089
- day: 'numeric'
2090
- }) : '',
2091
- branch: d.branch
2092
- };
2093
- });
2094
- console.log(`${_chalkTable$3(options, formattedResults)}\n`);
2095
- }
2096
-
2097
- var metadata$1 = {};
2098
-
2099
- var _interopRequireDefault$c = vendor.interopRequireDefault.default;
2100
- Object.defineProperty(metadata$1, "__esModule", {
2101
- value: true
2102
- });
2103
- metadata$1.metadata = void 0;
2104
- var _chalk$b = _interopRequireDefault$c(vendor.source);
2105
- var _meow$b = _interopRequireDefault$c(vendor.build);
2106
- var _ora$b = _interopRequireDefault$c(vendor.ora);
2107
- var _flags$a = flags;
2108
- var _apiHelpers$b = apiHelpers;
2109
- var _formatting$a = formatting;
2110
- var _sdk$b = sdk.sdk;
2111
- var _errors$c = sdk.errors;
2112
- const metadata = metadata$1.metadata = {
2113
- description: "Get a scan's metadata",
2114
- async run(argv, importMeta, {
2115
- parentName
2116
- }) {
2117
- const name = `${parentName} metadata`;
2118
- const input = setupCommand$b(name, metadata.description, argv, importMeta);
2119
- if (input) {
2120
- const apiKey = (0, _sdk$b.getDefaultKey)();
2121
- if (!apiKey) {
2122
- throw new _errors$c.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2123
- }
2124
- const spinnerText = "Getting scan's metadata... \n";
2125
- const spinner = (0, _ora$b.default)(spinnerText).start();
2126
- await getOrgScanMetadata(input.orgSlug, input.scanID, spinner, apiKey);
2127
- }
2128
- }
2129
- };
2130
-
2131
- // Internal functions
2132
-
2133
- function setupCommand$b(name, description, argv, importMeta) {
2134
- const flags = {
2135
- ..._flags$a.outputFlags
2136
- };
2137
- const cli = (0, _meow$b.default)(`
2138
- Usage
2139
- $ ${name} <org slug> <scan id>
2140
-
2141
- Options
2142
- ${(0, _formatting$a.printFlagList)(flags, 6)}
2143
-
2144
- Examples
2145
- $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0
2146
- `, {
2147
- argv,
2148
- description,
2149
- importMeta,
2150
- flags
2151
- });
2152
- const {
2153
- json: outputJson,
2154
- markdown: outputMarkdown
2155
- } = cli.flags;
2156
- if (cli.input.length < 2) {
2157
- console.error(`${_chalk$b.default.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2158
- cli.showHelp();
2159
- return;
2160
- }
2161
- const {
2162
- 0: orgSlug = '',
2163
- 1: scanID = ''
2164
- } = cli.input;
2165
- return {
2166
- outputJson,
2167
- outputMarkdown,
2168
- orgSlug,
2169
- scanID
2170
- };
2171
- }
2172
- async function getOrgScanMetadata(orgSlug, scanId, spinner, apiKey) {
2173
- const socketSdk = await (0, _sdk$b.setupSdk)(apiKey);
2174
- const result = await (0, _apiHelpers$b.handleApiCall)(socketSdk.getOrgFullScanMetadata(orgSlug, scanId), 'Listing scans');
2175
- if (!result.success) {
2176
- (0, _apiHelpers$b.handleUnsuccessfulApiResponse)('getOrgFullScanMetadata', result, spinner);
2177
- return;
2178
- }
2179
- spinner.stop();
2180
- console.log('\nScan metadata:\n');
2181
- console.log(result.data);
2182
- }
2183
-
2184
- var stream$1 = {};
2185
-
2186
- var _interopRequireDefault$b = vendor.interopRequireDefault.default;
2187
- Object.defineProperty(stream$1, "__esModule", {
2188
- value: true
2189
- });
2190
- stream$1.stream = void 0;
2191
- var _chalk$a = _interopRequireDefault$b(vendor.source);
2192
- var _meow$a = _interopRequireDefault$b(vendor.build);
2193
- var _ora$a = _interopRequireDefault$b(vendor.ora);
2194
- var _flags$9 = flags;
2195
- var _apiHelpers$a = apiHelpers;
2196
- var _formatting$9 = formatting;
2197
- var _sdk$a = sdk.sdk;
2198
- var _errors$b = sdk.errors;
2199
- const stream = stream$1.stream = {
2200
- description: 'Stream the output of a scan',
2201
- async run(argv, importMeta, {
2202
- parentName
2203
- }) {
2204
- const name = `${parentName} stream`;
2205
- const input = setupCommand$a(name, stream.description, argv, importMeta);
2206
- if (input) {
2207
- const apiKey = (0, _sdk$a.getDefaultKey)();
2208
- if (!apiKey) {
2209
- throw new _errors$b.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2210
- }
2211
- const spinnerText = 'Streaming scan...\n';
2212
- const spinner = (0, _ora$a.default)(spinnerText).start();
2213
- await getOrgFullScan(input.orgSlug, input.fullScanId, input.file, spinner, apiKey);
2214
- }
2215
- }
2216
- };
2217
-
2218
- // Internal functions
2219
-
2220
- function setupCommand$a(name, description, argv, importMeta) {
2221
- const flags = {
2222
- ..._flags$9.outputFlags
2223
- };
2224
- const cli = (0, _meow$a.default)(`
2225
- Usage
2226
- $ ${name} <org slug> <scan ID> <path to output file>
2227
-
2228
- Options
2229
- ${(0, _formatting$9.printFlagList)(flags, 6)}
2230
-
2231
- Examples
2232
- $ ${name} FakeOrg 000aaaa1-0000-0a0a-00a0-00a0000000a0 ./stream.txt
2233
- `, {
2234
- argv,
2235
- description,
2236
- importMeta,
2237
- flags
2238
- });
2239
- const {
2240
- json: outputJson,
2241
- markdown: outputMarkdown
2242
- } = cli.flags;
2243
- if (cli.input.length < 2) {
2244
- console.error(`${_chalk$a.default.bgRed('Input error')}: Please specify an organization slug and a scan ID.\n`);
2245
- cli.showHelp();
2246
- return;
2247
- }
2248
- const {
2249
- 0: orgSlug = '',
2250
- 1: fullScanId = '',
2251
- 2: file
2252
- } = cli.input;
2253
- return {
2254
- outputJson,
2255
- outputMarkdown,
2256
- orgSlug,
2257
- fullScanId,
2258
- file
2259
- };
2260
- }
2261
- async function getOrgFullScan(orgSlug, fullScanId, file, spinner, apiKey) {
2262
- const socketSdk = await (0, _sdk$a.setupSdk)(apiKey);
2263
- const result = await (0, _apiHelpers$a.handleApiCall)(socketSdk.getOrgFullScan(orgSlug, fullScanId, file), 'Streaming a scan');
2264
- if (!result?.success) {
2265
- (0, _apiHelpers$a.handleUnsuccessfulApiResponse)('getOrgFullScan', result, spinner);
2266
- return;
2267
- }
2268
- spinner.stop();
2269
- console.log(file ? `\nFull scan details written to ${file}\n` : '\nFull scan details:\n');
2270
- }
2271
-
2272
- Object.defineProperty(scan, "__esModule", {
2273
- value: true
2274
- });
2275
- scan.scan = void 0;
2276
- var _create$1 = create$3;
2277
- var _delete$2 = _delete$3;
2278
- var _list$1 = list$3;
2279
- var _metadata = metadata$1;
2280
- var _stream = stream$1;
2281
- var _meowWithSubcommands$3 = meowWithSubcommands$1;
2282
- const description$2 = 'Scans related commands';
2283
- scan.scan = {
2284
- description: description$2,
2285
- run: async (argv, importMeta, {
2286
- parentName
2287
- }) => {
2288
- await (0, _meowWithSubcommands$3.meowWithSubcommands)({
2289
- create: _create$1.create,
2290
- stream: _stream.stream,
2291
- list: _list$1.list,
2292
- del: _delete$2.del,
2293
- metadata: _metadata.metadata
2294
- }, {
2295
- argv,
2296
- description: description$2,
2297
- importMeta,
2298
- name: parentName + ' scan'
2299
- });
2300
- }
2301
- };
2302
-
2303
- var auditLog$1 = {};
2304
-
2305
- var _interopRequireDefault$a = vendor.interopRequireDefault.default;
2306
- Object.defineProperty(auditLog$1, "__esModule", {
2307
- value: true
2308
- });
2309
- auditLog$1.auditLog = void 0;
2310
- var _prompts = require$$1$1;
2311
- var _chalk$9 = _interopRequireDefault$a(vendor.source);
2312
- var _meow$9 = _interopRequireDefault$a(vendor.build);
2313
- var _ora$9 = _interopRequireDefault$a(vendor.ora);
2314
- var _flags$8 = flags;
2315
- var _apiHelpers$9 = apiHelpers;
2316
- var _formatting$8 = formatting;
2317
- var _sdk$9 = sdk.sdk;
2318
- var _errors$a = sdk.errors;
2319
- const auditLog = auditLog$1.auditLog = {
2320
- description: 'Look up the audit log for an organization',
2321
- async run(argv, importMeta, {
2322
- parentName
2323
- }) {
2324
- const name = parentName + ' audit-log';
2325
- const input = setupCommand$9(name, auditLog.description, argv, importMeta);
2326
- if (input) {
2327
- const apiKey = (0, _sdk$9.getDefaultKey)();
2328
- if (!apiKey) {
2329
- throw new _errors$a.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2330
- }
2331
- const spinner = (0, _ora$9.default)(`Looking up audit log for ${input.orgSlug}\n`).start();
2332
- await fetchOrgAuditLog(input.orgSlug, input, spinner, apiKey);
2333
- }
2334
- }
2335
- };
2336
- const auditLogFlags = {
2337
- type: {
2338
- type: 'string',
2339
- shortFlag: 't',
2340
- default: '',
2341
- description: 'Type of log event'
2342
- },
2343
- perPage: {
2344
- type: 'number',
2345
- shortFlag: 'pp',
2346
- default: 30,
2347
- description: 'Results per page - default is 30'
2348
- },
2349
- page: {
2350
- type: 'number',
2351
- shortFlag: 'p',
2352
- default: 1,
2353
- description: 'Page number - default is 1'
2354
- }
2355
- };
2356
-
2357
- // Internal functions
2358
-
2359
- function setupCommand$9(name, description, argv, importMeta) {
2360
- const flags = {
2361
- ...auditLogFlags,
2362
- ..._flags$8.outputFlags
2363
- };
2364
- const cli = (0, _meow$9.default)(`
2365
- Usage
2366
- $ ${name} <org slug>
2367
-
2368
- Options
2369
- ${(0, _formatting$8.printFlagList)(flags, 6)}
2370
-
2371
- Examples
2372
- $ ${name} FakeOrg
2373
- `, {
2374
- argv,
2375
- description,
2376
- importMeta,
2377
- flags
2378
- });
2379
- const {
2380
- json: outputJson,
2381
- markdown: outputMarkdown,
2382
- page,
2383
- perPage
2384
- } = cli.flags;
2385
- const type = cli.flags['type'];
2386
- if (cli.input.length < 1) {
2387
- console.error(`${_chalk$9.default.bgRed('Input error')}: Please provide an organization slug \n`);
2388
- cli.showHelp();
2389
- return;
2390
- }
2391
- const [orgSlug = ''] = cli.input;
2392
- return {
2393
- outputJson,
2394
- outputMarkdown,
2395
- orgSlug,
2396
- type: type && type.charAt(0).toUpperCase() + type.slice(1),
2397
- page,
2398
- per_page: perPage
2399
- };
2400
- }
2401
- async function fetchOrgAuditLog(orgSlug, input, spinner, apiKey) {
2402
- const socketSdk = await (0, _sdk$9.setupSdk)(apiKey);
2403
- const result = await (0, _apiHelpers$9.handleApiCall)(socketSdk.getAuditLogEvents(orgSlug, input), `Looking up audit log for ${orgSlug}\n`);
2404
- if (!result.success) {
2405
- (0, _apiHelpers$9.handleUnsuccessfulApiResponse)('getAuditLogEvents', result, spinner);
2406
- return;
2407
- }
2408
- spinner.stop();
2409
- const data = [];
2410
- const logDetails = {};
2411
- for (const d of result.data.results) {
2412
- const {
2413
- created_at
2414
- } = d;
2415
- if (created_at) {
2416
- const name = `${new Date(created_at).toLocaleDateString('en-us', {
2417
- year: 'numeric',
2418
- month: 'numeric',
2419
- day: 'numeric'
2420
- })} - ${d.user_email} - ${d.type} - ${d.ip_address} - ${d.user_agent}`;
2421
- data.push({
2422
- name
2423
- }, new _prompts.Separator());
2424
- logDetails[name] = JSON.stringify(d.payload);
2425
- }
2426
- }
2427
- console.log(logDetails[await (0, _prompts.select)({
2428
- message: input.type ? `\n Audit log for: ${orgSlug} with type: ${input.type} \n` : `\n Audit log for: ${orgSlug} \n`,
2429
- choices: data,
2430
- pageSize: 30
2431
- })]);
2432
- }
2433
-
2434
- var repos = {};
2435
-
2436
- var create$1 = {};
2437
-
2438
- var _interopRequireDefault$9 = vendor.interopRequireDefault.default;
2439
- Object.defineProperty(create$1, "__esModule", {
2440
- value: true
2441
- });
2442
- create$1.create = void 0;
2443
- var _chalk$8 = _interopRequireDefault$9(vendor.source);
2444
- var _meow$8 = _interopRequireDefault$9(vendor.build);
2445
- var _ora$8 = _interopRequireDefault$9(vendor.ora);
2446
- var _flags$7 = flags;
2447
- var _apiHelpers$8 = apiHelpers;
2448
- var _formatting$7 = formatting;
2449
- var _sdk$8 = sdk.sdk;
2450
- var _errors$9 = sdk.errors;
2451
- const create = create$1.create = {
2452
- description: 'Create a repository in an organization',
2453
- async run(argv, importMeta, {
2454
- parentName
2455
- }) {
2456
- const name = `${parentName} create`;
2457
- const input = setupCommand$8(name, create.description, argv, importMeta);
2458
- if (input) {
2459
- const apiKey = (0, _sdk$8.getDefaultKey)();
2460
- if (!apiKey) {
2461
- throw new _errors$9.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2462
- }
2463
- const spinnerText = 'Creating repository... \n';
2464
- const spinner = (0, _ora$8.default)(spinnerText).start();
2465
- await createRepo(input.orgSlug, input, spinner, apiKey);
2466
- }
2467
- }
2468
- };
2469
- const repositoryCreationFlags = {
2470
- repoName: {
2471
- type: 'string',
2472
- shortFlag: 'n',
2473
- default: '',
2474
- description: 'Repository name'
2475
- },
2476
- repoDescription: {
2477
- type: 'string',
2478
- shortFlag: 'd',
2479
- default: '',
2480
- description: 'Repository description'
2481
- },
2482
- homepage: {
2483
- type: 'string',
2484
- shortFlag: 'h',
2485
- default: '',
2486
- description: 'Repository url'
2487
- },
2488
- defaultBranch: {
2489
- type: 'string',
2490
- shortFlag: 'b',
2491
- default: 'main',
2492
- description: 'Repository default branch'
2493
- },
2494
- visibility: {
2495
- type: 'string',
2496
- shortFlag: 'v',
2497
- default: 'private',
2498
- description: 'Repository visibility (Default Private)'
2499
- }
2500
- };
2501
-
2502
- // Internal functions
2503
-
2504
- function setupCommand$8(name, description, argv, importMeta) {
2505
- const flags = {
2506
- ..._flags$7.outputFlags,
2507
- ...repositoryCreationFlags
2508
- };
2509
- const cli = (0, _meow$8.default)(`
2510
- Usage
2511
- $ ${name} <org slug>
2512
-
2513
- Options
2514
- ${(0, _formatting$7.printFlagList)(flags, 6)}
2515
-
2516
- Examples
2517
- $ ${name} FakeOrg --repoName=test-repo
2518
- `, {
2519
- argv,
2520
- description,
2521
- importMeta,
2522
- flags
2523
- });
2524
- const {
2525
- json: outputJson,
2526
- markdown: outputMarkdown,
2527
- repoName,
2528
- repoDescription,
2529
- homepage,
2530
- defaultBranch,
2531
- visibility
2532
- } = cli.flags;
2533
- const [orgSlug = ''] = cli.input;
2534
- if (!orgSlug) {
2535
- console.error(`${_chalk$8.default.bgRed('Input error')}: Please provide an organization slug \n`);
2536
- cli.showHelp();
2537
- return;
2538
- }
2539
- if (!repoName) {
2540
- console.error(`${_chalk$8.default.bgRed('Input error')}: Repository name is required. \n`);
2541
- cli.showHelp();
2542
- return;
2543
- }
2544
- return {
2545
- outputJson,
2546
- outputMarkdown,
2547
- orgSlug,
2548
- name: repoName,
2549
- description: repoDescription,
2550
- homepage,
2551
- default_branch: defaultBranch,
2552
- visibility
2553
- };
2554
- }
2555
- async function createRepo(orgSlug, input, spinner, apiKey) {
2556
- const socketSdk = await (0, _sdk$8.setupSdk)(apiKey);
2557
- const result = await (0, _apiHelpers$8.handleApiCall)(socketSdk.createOrgRepo(orgSlug, input), 'creating repository');
2558
- if (!result.success) {
2559
- (0, _apiHelpers$8.handleUnsuccessfulApiResponse)('createOrgRepo', result, spinner);
2560
- return;
2561
- }
2562
- spinner.stop();
2563
- console.log('\n✅ Repository created successfully\n');
2564
- }
2565
-
2566
- var _delete$1 = {};
2567
-
2568
- var _interopRequireDefault$8 = vendor.interopRequireDefault.default;
2569
- Object.defineProperty(_delete$1, "__esModule", {
2570
- value: true
2571
- });
2572
- _delete$1.del = void 0;
2573
- var _chalk$7 = _interopRequireDefault$8(vendor.source);
2574
- var _meow$7 = _interopRequireDefault$8(vendor.build);
2575
- var _ora$7 = _interopRequireDefault$8(vendor.ora);
2576
- var _apiHelpers$7 = apiHelpers;
2577
- var _sdk$7 = sdk.sdk;
2578
- var _errors$8 = sdk.errors;
2579
- const del = _delete$1.del = {
2580
- description: 'Delete a repository in an organization',
2581
- async run(argv, importMeta, {
2582
- parentName
2583
- }) {
2584
- const name = `${parentName} del`;
2585
- const input = setupCommand$7(name, del.description, argv, importMeta);
2586
- if (input) {
2587
- const apiKey = (0, _sdk$7.getDefaultKey)();
2588
- if (!apiKey) {
2589
- throw new _errors$8.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2590
- }
2591
- const spinnerText = 'Deleting repository... \n';
2592
- const spinner = (0, _ora$7.default)(spinnerText).start();
2593
- await deleteRepository(input.orgSlug, input.repoName, spinner, apiKey);
2594
- }
2595
- }
2596
- };
2597
-
2598
- // Internal functions
2599
-
2600
- function setupCommand$7(name, description, argv, importMeta) {
2601
- const cli = (0, _meow$7.default)(`
2602
- Usage
2603
- $ ${name} <org slug> <repo slug>
2604
-
2605
- Examples
2606
- $ ${name} FakeOrg test-repo
2607
- `, {
2608
- argv,
2609
- description,
2610
- importMeta
2611
- });
2612
- const {
2613
- 0: orgSlug = '',
2614
- 1: repoName = ''
2615
- } = cli.input;
2616
- if (!orgSlug || !repoName) {
2617
- console.error(`${_chalk$7.default.bgRed('Input error')}: Please provide an organization slug and repository slug \n`);
2618
- cli.showHelp();
2619
- return;
2620
- }
2621
- return {
2622
- orgSlug,
2623
- repoName
2624
- };
2625
- }
2626
- async function deleteRepository(orgSlug, repoName, spinner, apiKey) {
2627
- const socketSdk = await (0, _sdk$7.setupSdk)(apiKey);
2628
- const result = await (0, _apiHelpers$7.handleApiCall)(socketSdk.deleteOrgRepo(orgSlug, repoName), 'deleting repository');
2629
- if (!result.success) {
2630
- (0, _apiHelpers$7.handleUnsuccessfulApiResponse)('deleteOrgRepo', result, spinner);
2631
- return;
2632
- }
2633
- spinner.stop();
2634
- console.log('\n✅ Repository deleted successfully\n');
2635
- }
2636
-
2637
- var list$1 = {};
2638
-
2639
- var _interopRequireDefault$7 = vendor.interopRequireDefault.default;
2640
- Object.defineProperty(list$1, "__esModule", {
2641
- value: true
2642
- });
2643
- list$1.list = void 0;
2644
- var _chalk$6 = _interopRequireDefault$7(vendor.source);
2645
- var _chalkTable$2 = require$$2$2;
2646
- var _meow$6 = _interopRequireDefault$7(vendor.build);
2647
- var _ora$6 = _interopRequireDefault$7(vendor.ora);
2648
- var _flags$6 = flags;
2649
- var _apiHelpers$6 = apiHelpers;
2650
- var _formatting$6 = formatting;
2651
- var _sdk$6 = sdk.sdk;
2652
- var _errors$7 = sdk.errors;
2653
- // @ts-ignore
2654
-
2655
- const list = list$1.list = {
2656
- description: 'List repositories in an organization',
2657
- async run(argv, importMeta, {
2658
- parentName
2659
- }) {
2660
- const name = `${parentName} list`;
2661
- const input = setupCommand$6(name, list.description, argv, importMeta);
2662
- if (input) {
2663
- const apiKey = (0, _sdk$6.getDefaultKey)();
2664
- if (!apiKey) {
2665
- throw new _errors$7.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2666
- }
2667
- const spinnerText = 'Listing repositories... \n';
2668
- const spinner = (0, _ora$6.default)(spinnerText).start();
2669
- await listOrgRepos(input.orgSlug, input, spinner, apiKey);
2670
- }
2671
- }
2672
- };
2673
- const listRepoFlags = {
2674
- sort: {
2675
- type: 'string',
2676
- shortFlag: 's',
2677
- default: 'created_at',
2678
- description: 'Sorting option'
2679
- },
2680
- direction: {
2681
- type: 'string',
2682
- default: 'desc',
2683
- description: 'Direction option'
2684
- },
2685
- perPage: {
2686
- type: 'number',
2687
- shortFlag: 'pp',
2688
- default: 30,
2689
- description: 'Number of results per page'
2690
- },
2691
- page: {
2692
- type: 'number',
2693
- shortFlag: 'p',
2694
- default: 1,
2695
- description: 'Page number'
2696
- }
2697
- };
2698
-
2699
- // Internal functions
2700
-
2701
- function setupCommand$6(name, description, argv, importMeta) {
2702
- const flags = {
2703
- ..._flags$6.outputFlags,
2704
- ...listRepoFlags
2705
- };
2706
- const cli = (0, _meow$6.default)(`
2707
- Usage
2708
- $ ${name} <org slug>
2709
-
2710
- Options
2711
- ${(0, _formatting$6.printFlagList)(flags, 6)}
2712
-
2713
- Examples
2714
- $ ${name} FakeOrg
2715
- `, {
2716
- argv,
2717
- description,
2718
- importMeta,
2719
- flags
2720
- });
2721
- const {
2722
- json: outputJson,
2723
- markdown: outputMarkdown,
2724
- perPage,
2725
- sort,
2726
- direction,
2727
- page
2728
- } = cli.flags;
2729
- if (!cli.input[0]) {
2730
- console.error(`${_chalk$6.default.bgRed('Input error')}: Please provide an organization slug \n`);
2731
- cli.showHelp();
2732
- return;
2733
- }
2734
- const {
2735
- 0: orgSlug = ''
2736
- } = cli.input;
2737
- return {
2738
- outputJson,
2739
- outputMarkdown,
2740
- orgSlug,
2741
- sort,
2742
- direction,
2743
- page,
2744
- per_page: perPage
2745
- };
2746
- }
2747
- async function listOrgRepos(orgSlug, input, spinner, apiKey) {
2748
- const socketSdk = await (0, _sdk$6.setupSdk)(apiKey);
2749
- const result = await (0, _apiHelpers$6.handleApiCall)(socketSdk.getOrgRepoList(orgSlug, input), 'listing repositories');
2750
- if (!result.success) {
2751
- (0, _apiHelpers$6.handleUnsuccessfulApiResponse)('getOrgRepoList', result, spinner);
2752
- return;
2753
- }
2754
- spinner.stop();
2755
- const options = {
2756
- columns: [{
2757
- field: 'id',
2758
- name: _chalk$6.default.magenta('ID')
2759
- }, {
2760
- field: 'name',
2761
- name: _chalk$6.default.magenta('Name')
2762
- }, {
2763
- field: 'visibility',
2764
- name: _chalk$6.default.magenta('Visibility')
2765
- }, {
2766
- field: 'default_branch',
2767
- name: _chalk$6.default.magenta('Default branch')
2768
- }, {
2769
- field: 'archived',
2770
- name: _chalk$6.default.magenta('Archived')
2771
- }]
2772
- };
2773
- console.log(`${_chalkTable$2(options, result.data.results)}\n`);
2774
- }
2775
-
2776
- var update$1 = {};
2777
-
2778
- var _interopRequireDefault$6 = vendor.interopRequireDefault.default;
2779
- Object.defineProperty(update$1, "__esModule", {
2780
- value: true
2781
- });
2782
- update$1.update = void 0;
2783
- var _chalk$5 = _interopRequireDefault$6(vendor.source);
2784
- var _meow$5 = _interopRequireDefault$6(vendor.build);
2785
- var _ora$5 = _interopRequireDefault$6(vendor.ora);
2786
- var _flags$5 = flags;
2787
- var _apiHelpers$5 = apiHelpers;
2788
- var _formatting$5 = formatting;
2789
- var _sdk$5 = sdk.sdk;
2790
- var _errors$6 = sdk.errors;
2791
- const update = update$1.update = {
2792
- description: 'Update a repository in an organization',
2793
- async run(argv, importMeta, {
2794
- parentName
2795
- }) {
2796
- const name = `${parentName} update`;
2797
- const input = setupCommand$5(name, update.description, argv, importMeta);
2798
- if (input) {
2799
- const apiKey = (0, _sdk$5.getDefaultKey)();
2800
- if (!apiKey) {
2801
- throw new _errors$6.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2802
- }
2803
- const spinnerText = 'Updating repository... \n';
2804
- const spinner = (0, _ora$5.default)(spinnerText).start();
2805
- await updateRepository(input.orgSlug, input, spinner, apiKey);
2806
- }
2807
- }
2808
- };
2809
- const repositoryUpdateFlags = {
2810
- repoName: {
2811
- type: 'string',
2812
- shortFlag: 'n',
2813
- default: '',
2814
- description: 'Repository name'
2815
- },
2816
- repoDescription: {
2817
- type: 'string',
2818
- shortFlag: 'd',
2819
- default: '',
2820
- description: 'Repository description'
2821
- },
2822
- homepage: {
2823
- type: 'string',
2824
- shortFlag: 'h',
2825
- default: '',
2826
- description: 'Repository url'
2827
- },
2828
- defaultBranch: {
2829
- type: 'string',
2830
- shortFlag: 'b',
2831
- default: 'main',
2832
- description: 'Repository default branch'
2833
- },
2834
- visibility: {
2835
- type: 'string',
2836
- shortFlag: 'v',
2837
- default: 'private',
2838
- description: 'Repository visibility (Default Private)'
2839
- }
2840
- };
2841
-
2842
- // Internal functions
2843
-
2844
- function setupCommand$5(name, description, argv, importMeta) {
2845
- const flags = {
2846
- ..._flags$5.outputFlags,
2847
- ...repositoryUpdateFlags
2848
- };
2849
- const cli = (0, _meow$5.default)(`
2850
- Usage
2851
- $ ${name} <org slug>
2852
-
2853
- Options
2854
- ${(0, _formatting$5.printFlagList)(flags, 6)}
2855
-
2856
- Examples
2857
- $ ${name} FakeOrg
2858
- `, {
2859
- argv,
2860
- description,
2861
- importMeta,
2862
- flags
2863
- });
2864
- const {
2865
- json: outputJson,
2866
- markdown: outputMarkdown,
2867
- repoName,
2868
- repoDescription,
2869
- homepage,
2870
- defaultBranch,
2871
- visibility
2872
- } = cli.flags;
2873
- const [orgSlug = ''] = cli.input;
2874
- if (!orgSlug) {
2875
- console.error(`${_chalk$5.default.bgRed('Input error')}: Please provide an organization slug and repository name \n`);
2876
- cli.showHelp();
2877
- return;
2878
- }
2879
- if (!repoName) {
2880
- console.error(`${_chalk$5.default.bgRed('Input error')}: Repository name is required. \n`);
2881
- cli.showHelp();
2882
- return;
2883
- }
2884
- return {
2885
- outputJson,
2886
- outputMarkdown,
2887
- orgSlug,
2888
- name: repoName,
2889
- description: repoDescription,
2890
- homepage,
2891
- default_branch: defaultBranch,
2892
- visibility
2893
- };
2894
- }
2895
- async function updateRepository(orgSlug, input, spinner, apiKey) {
2896
- const socketSdk = await (0, _sdk$5.setupSdk)(apiKey);
2897
- const result = await (0, _apiHelpers$5.handleApiCall)(socketSdk.updateOrgRepo(orgSlug, input.name, input), 'updating repository');
2898
- if (!result.success) {
2899
- (0, _apiHelpers$5.handleUnsuccessfulApiResponse)('updateOrgRepo', result, spinner);
2900
- return;
2901
- }
2902
- spinner.stop();
2903
- console.log('\n✅ Repository updated successfully\n');
2904
- }
2905
-
2906
- var view$1 = {};
2907
-
2908
- var _interopRequireDefault$5 = vendor.interopRequireDefault.default;
2909
- Object.defineProperty(view$1, "__esModule", {
2910
- value: true
2911
- });
2912
- view$1.view = void 0;
2913
- var _chalk$4 = _interopRequireDefault$5(vendor.source);
2914
- var _chalkTable$1 = require$$2$2;
2915
- var _meow$4 = _interopRequireDefault$5(vendor.build);
2916
- var _ora$4 = _interopRequireDefault$5(vendor.ora);
2917
- var _flags$4 = flags;
2918
- var _apiHelpers$4 = apiHelpers;
2919
- var _formatting$4 = formatting;
2920
- var _sdk$4 = sdk.sdk;
2921
- var _errors$5 = sdk.errors;
2922
- // @ts-ignore
2923
-
2924
- const view = view$1.view = {
2925
- description: 'View repositories in an organization',
2926
- async run(argv, importMeta, {
2927
- parentName
2928
- }) {
2929
- const name = `${parentName} view`;
2930
- const input = setupCommand$4(name, view.description, argv, importMeta);
2931
- if (input) {
2932
- const apiKey = (0, _sdk$4.getDefaultKey)();
2933
- if (!apiKey) {
2934
- throw new _errors$5.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
2935
- }
2936
- const spinnerText = 'Fetching repository... \n';
2937
- const spinner = (0, _ora$4.default)(spinnerText).start();
2938
- await viewRepository(input.orgSlug, input.repositoryName, spinner, apiKey);
2939
- }
2940
- }
2941
- };
2942
-
2943
- // Internal functions
2944
-
2945
- function setupCommand$4(name, description, argv, importMeta) {
2946
- const flags = {
2947
- ..._flags$4.outputFlags
2948
- };
2949
- const cli = (0, _meow$4.default)(`
2950
- Usage
2951
- $ ${name} <org slug>
2952
-
2953
- Options
2954
- ${(0, _formatting$4.printFlagList)(flags, 6)}
2955
-
2956
- Examples
2957
- $ ${name} FakeOrg
2958
- `, {
2959
- argv,
2960
- description,
2961
- importMeta,
2962
- flags
2963
- });
2964
- const {
2965
- json: outputJson,
2966
- markdown: outputMarkdown
2967
- } = cli.flags;
2968
- if (!cli.input[0]) {
2969
- console.error(`${_chalk$4.default.bgRed('Input error')}: Please provide an organization slug and repository name \n`);
2970
- cli.showHelp();
2971
- return;
2972
- }
2973
- const {
2974
- 0: orgSlug = '',
2975
- 1: repositoryName = ''
2976
- } = cli.input;
2977
- return {
2978
- outputJson,
2979
- outputMarkdown,
2980
- orgSlug,
2981
- repositoryName
2982
- };
2983
- }
2984
- async function viewRepository(orgSlug, repoName, spinner, apiKey) {
2985
- const socketSdk = await (0, _sdk$4.setupSdk)(apiKey);
2986
- const result = await (0, _apiHelpers$4.handleApiCall)(socketSdk.getOrgRepo(orgSlug, repoName), 'fetching repository');
2987
- if (!result.success) {
2988
- (0, _apiHelpers$4.handleUnsuccessfulApiResponse)('getOrgRepo', result, spinner);
2989
- return;
2990
- }
2991
- spinner.stop();
2992
- const options = {
2993
- columns: [{
2994
- field: 'id',
2995
- name: _chalk$4.default.magenta('ID')
2996
- }, {
2997
- field: 'name',
2998
- name: _chalk$4.default.magenta('Name')
2999
- }, {
3000
- field: 'visibility',
3001
- name: _chalk$4.default.magenta('Visibility')
3002
- }, {
3003
- field: 'default_branch',
3004
- name: _chalk$4.default.magenta('Default branch')
3005
- }, {
3006
- field: 'homepage',
3007
- name: _chalk$4.default.magenta('Homepage')
3008
- }, {
3009
- field: 'archived',
3010
- name: _chalk$4.default.magenta('Archived')
3011
- }, {
3012
- field: 'created_at',
3013
- name: _chalk$4.default.magenta('Created at')
3014
- }]
3015
- };
3016
- console.log(`${_chalkTable$1(options, [result.data])}\n`);
3017
- }
3018
-
3019
- Object.defineProperty(repos, "__esModule", {
3020
- value: true
3021
- });
3022
- repos.repo = void 0;
3023
- var _create = create$1;
3024
- var _delete = _delete$1;
3025
- var _list = list$1;
3026
- var _update = update$1;
3027
- var _view = view$1;
3028
- var _meowWithSubcommands$2 = meowWithSubcommands$1;
3029
- const description$1 = 'Repositories related commands';
3030
- repos.repo = {
3031
- description: description$1,
3032
- run: async (argv, importMeta, {
3033
- parentName
3034
- }) => {
3035
- await (0, _meowWithSubcommands$2.meowWithSubcommands)({
3036
- create: _create.create,
3037
- view: _view.view,
3038
- list: _list.list,
3039
- del: _delete.del,
3040
- update: _update.update
3041
- }, {
3042
- argv,
3043
- description: description$1,
3044
- importMeta,
3045
- name: `${parentName} repo`
3046
- });
3047
- }
3048
- };
3049
-
3050
- var dependencies$1 = {};
3051
-
3052
- var _interopRequireDefault$4 = vendor.interopRequireDefault.default;
3053
- Object.defineProperty(dependencies$1, "__esModule", {
3054
- value: true
3055
- });
3056
- dependencies$1.dependencies = void 0;
3057
- var _chalk$3 = _interopRequireDefault$4(vendor.source);
3058
- var _chalkTable = require$$2$2;
3059
- var _meow$3 = _interopRequireDefault$4(vendor.build);
3060
- var _ora$3 = _interopRequireDefault$4(vendor.ora);
3061
- var _flags$3 = flags;
3062
- var _apiHelpers$3 = apiHelpers;
3063
- var _formatting$3 = formatting;
3064
- var _sdk$3 = sdk.sdk;
3065
- var _errors$4 = sdk.errors;
3066
- // @ts-ignore
3067
-
3068
- const dependencies = dependencies$1.dependencies = {
3069
- description: 'Search for any dependency that is being used in your organization',
3070
- async run(argv, importMeta, {
3071
- parentName
3072
- }) {
3073
- const name = parentName + ' dependencies';
3074
- const input = setupCommand$3(name, dependencies.description, argv, importMeta);
3075
- if (input) {
3076
- await searchDeps(input);
3077
- }
3078
- }
3079
- };
3080
- const dependenciesFlags = {
3081
- limit: {
3082
- type: 'number',
3083
- shortFlag: 'l',
3084
- default: 50,
3085
- description: 'Maximum number of dependencies returned'
3086
- },
3087
- offset: {
3088
- type: 'number',
3089
- shortFlag: 'o',
3090
- default: 0,
3091
- description: 'Page number'
3092
- }
3093
- };
3094
-
3095
- // Internal functions
3096
-
3097
- function setupCommand$3(name, description, argv, importMeta) {
3098
- const flags = {
3099
- ..._flags$3.outputFlags,
3100
- ...dependenciesFlags
3101
- };
3102
- const cli = (0, _meow$3.default)(`
3103
- Usage
3104
- $ ${name}
3105
-
3106
- Options
3107
- ${(0, _formatting$3.printFlagList)(flags, 6)}
3108
-
3109
- Examples
3110
- $ ${name}
3111
- `, {
3112
- argv,
3113
- description,
3114
- importMeta,
3115
- flags
3116
- });
3117
- const {
3118
- json: outputJson,
3119
- markdown: outputMarkdown,
3120
- limit,
3121
- offset
3122
- } = cli.flags;
3123
- return {
3124
- outputJson,
3125
- outputMarkdown,
3126
- limit,
3127
- offset
3128
- };
3129
- }
3130
- async function searchDeps({
3131
- limit,
3132
- offset,
3133
- outputJson
3134
- }) {
3135
- const apiKey = (0, _sdk$3.getDefaultKey)();
3136
- if (!apiKey) {
3137
- throw new _errors$4.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
3138
- }
3139
- const spinnerText = 'Searching dependencies...';
3140
- const spinner = (0, _ora$3.default)(spinnerText).start();
3141
- const socketSdk = await (0, _sdk$3.setupSdk)(apiKey);
3142
- const result = await (0, _apiHelpers$3.handleApiCall)(socketSdk.searchDependencies({
3143
- limit,
3144
- offset
3145
- }), 'Searching dependencies');
3146
- if (!result.success) {
3147
- (0, _apiHelpers$3.handleUnsuccessfulApiResponse)('searchDependencies', result, spinner);
3148
- return;
3149
- }
3150
- spinner.stop();
3151
- console.log('Organization dependencies:\n');
3152
- if (outputJson) {
3153
- console.log(result.data);
3154
- return;
3155
- }
3156
- const options = {
3157
- columns: [{
3158
- field: 'namespace',
3159
- name: _chalk$3.default.cyan('Namespace')
3160
- }, {
3161
- field: 'name',
3162
- name: _chalk$3.default.cyan('Name')
3163
- }, {
3164
- field: 'version',
3165
- name: _chalk$3.default.cyan('Version')
3166
- }, {
3167
- field: 'repository',
3168
- name: _chalk$3.default.cyan('Repository')
3169
- }, {
3170
- field: 'branch',
3171
- name: _chalk$3.default.cyan('Branch')
3172
- }, {
3173
- field: 'type',
3174
- name: _chalk$3.default.cyan('Type')
3175
- }, {
3176
- field: 'direct',
3177
- name: _chalk$3.default.cyan('Direct')
3178
- }]
3179
- };
3180
- console.log(`${_chalkTable(options, result.data.rows)}\n`);
3181
- }
3182
-
3183
- var analytics$1 = {};
3184
-
3185
- var _interopRequireDefault$3 = vendor.interopRequireDefault.default;
3186
- Object.defineProperty(analytics$1, "__esModule", {
3187
- value: true
3188
- });
3189
- analytics$1.analytics = void 0;
3190
- var _blessed$1 = require$$1$2;
3191
- var _blessedContrib$1 = require$$2$3;
3192
- var _fs$1 = require$$0;
3193
- var _meow$2 = _interopRequireDefault$3(vendor.build);
3194
- var _ora$2 = _interopRequireDefault$3(vendor.ora);
3195
- var _flags$2 = flags;
3196
- var _apiHelpers$2 = apiHelpers;
3197
- var _errors$3 = sdk.errors;
3198
- var _formatting$2 = formatting;
3199
- var _sdk$2 = sdk.sdk;
3200
- var _chalk$2 = _interopRequireDefault$3(vendor.source);
3201
- // @ts-ignore
3202
-
3203
- // @ts-ignore
3204
-
3205
- const analytics = analytics$1.analytics = {
3206
- description: `Look up analytics data \n
3207
- Default parameters are set to show the organization-level analytics over the last 7 days.`,
3208
- async run(argv, importMeta, {
3209
- parentName
3210
- }) {
3211
- const name = parentName + ' analytics';
3212
- const input = setupCommand$2(name, analytics.description, argv, importMeta);
3213
- if (input) {
3214
- const apiKey = (0, _sdk$2.getDefaultKey)();
3215
- if (!apiKey) {
3216
- throw new _errors$3.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
3217
- }
3218
- const spinner = (0, _ora$2.default)('Fetching analytics data').start();
3219
- if (input.scope === 'org') {
3220
- await fetchOrgAnalyticsData(input.time, spinner, apiKey, input.outputJson, input.file);
3221
- } else {
3222
- if (input.repo) {
3223
- await fetchRepoAnalyticsData(input.repo, input.time, spinner, apiKey, input.outputJson, input.file);
3224
- }
3225
- }
3226
- }
3227
- }
3228
- };
3229
- const analyticsFlags = {
3230
- scope: {
3231
- type: 'string',
3232
- shortFlag: 's',
3233
- default: 'org',
3234
- description: "Scope of the analytics data - either 'org' or 'repo'"
3235
- },
3236
- time: {
3237
- type: 'number',
3238
- shortFlag: 't',
3239
- default: 7,
3240
- description: 'Time filter - either 7, 30 or 90'
3241
- },
3242
- repo: {
3243
- type: 'string',
3244
- shortFlag: 'r',
3245
- default: '',
3246
- description: "Name of the repository"
3247
- },
3248
- file: {
3249
- type: 'string',
3250
- shortFlag: 'f',
3251
- default: '',
3252
- description: "Path to a local file to save the output"
3253
- }
3254
- };
3255
-
3256
- // Internal functions
3257
-
3258
- function setupCommand$2(name, description, argv, importMeta) {
3259
- const flags = {
3260
- ..._flags$2.outputFlags,
3261
- ...analyticsFlags
3262
- };
3263
- const cli = (0, _meow$2.default)(`
3264
- Usage
3265
- $ ${name} --scope=<scope> --time=<time filter>
3266
-
3267
- Options
3268
- ${(0, _formatting$2.printFlagList)(flags, 6)}
3269
-
3270
- Examples
3271
- $ ${name} --scope=org --time=7
3272
- $ ${name} --scope=org --time=30
3273
- $ ${name} --scope=repo --repo=test-repo --time=30
3274
- `, {
3275
- argv,
3276
- description,
3277
- importMeta,
3278
- flags
3279
- });
3280
- const {
3281
- json: outputJson,
3282
- scope,
3283
- time,
3284
- repo,
3285
- file
3286
- } = cli.flags;
3287
- if (scope !== 'org' && scope !== 'repo') {
3288
- throw new _errors$3.InputError("The scope must either be 'org' or 'repo'");
3289
- }
3290
- if (time !== 7 && time !== 30 && time !== 90) {
3291
- throw new _errors$3.InputError('The time filter must either be 7, 30 or 90');
3292
- }
3293
- if (scope === 'repo' && !repo) {
3294
- console.error(`${_chalk$2.default.bgRed.white('Input error')}: Please provide a repository name when using the repository scope. \n`);
3295
- cli.showHelp();
3296
- return;
3297
- }
3298
- return {
3299
- scope,
3300
- time,
3301
- repo,
3302
- outputJson,
3303
- file
3304
- };
3305
- }
3306
- const METRICS = ['total_critical_alerts', 'total_high_alerts', 'total_medium_alerts', 'total_low_alerts', 'total_critical_added', 'total_medium_added', 'total_low_added', 'total_high_added', 'total_critical_prevented', 'total_high_prevented', 'total_medium_prevented', 'total_low_prevented'];
3307
- async function fetchOrgAnalyticsData(time, spinner, apiKey, outputJson, filePath) {
3308
- const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
3309
- const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getOrgAnalytics(time.toString()), 'fetching analytics data');
3310
- if (result.success === false) {
3311
- return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getOrgAnalytics', result, spinner);
3312
- }
3313
- spinner.stop();
3314
- if (!result.data.length) {
3315
- return console.log('No analytics data is available for this organization yet.');
3316
- }
3317
- const data = formatData(result.data, 'org');
3318
- if (outputJson && !filePath) {
3319
- return console.log(result.data);
3320
- }
3321
- if (filePath) {
3322
- _fs$1.writeFile(filePath, JSON.stringify(result.data), err => {
3323
- err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
3324
- });
3325
- return;
3326
- }
3327
- return displayAnalyticsScreen(data);
3328
- }
3329
- const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
3330
- const formatDate = date => {
3331
- return `${months[new Date(date).getMonth()]} ${new Date(date).getDate()}`;
3332
- };
3333
- const formatData = (data, scope) => {
3334
- let formattedData, sortedTopFivealerts;
3335
- if (scope === 'org') {
3336
- const topFiveAlerts = data.map(d => d['top_five_alert_types']);
3337
- const totalTopAlerts = topFiveAlerts.reduce((acc, current) => {
3338
- const alertTypes = Object.keys(current);
3339
- alertTypes.map(type => {
3340
- if (!acc[type]) {
3341
- acc[type] = current[type];
3342
- } else {
3343
- acc[type] += current[type];
3344
- }
3345
- return acc;
3346
- });
3347
- return acc;
3348
- }, {});
3349
- sortedTopFivealerts = Object.entries(totalTopAlerts).sort(([, a], [, b]) => b - a).slice(0, 5).reduce((r, [k, v]) => ({
3350
- ...r,
3351
- [k]: v
3352
- }), {});
3353
- const formatData = label => {
3354
- return data.reduce((acc, current) => {
3355
- const date = formatDate(current['created_at']);
3356
- if (!acc[date]) {
3357
- acc[date] = current[label];
3358
- } else {
3359
- acc[date] += current[label];
3360
- }
3361
- return acc;
3362
- }, {});
3363
- };
3364
- formattedData = METRICS.reduce((acc, current) => {
3365
- acc[current] = formatData(current);
3366
- return acc;
3367
- }, {});
3368
- } else if (scope === 'repo') {
3369
- const topAlerts = data.reduce((acc, current) => {
3370
- const alertTypes = Object.keys(current['top_five_alert_types']);
3371
- alertTypes.map(type => {
3372
- if (!acc[type]) {
3373
- acc[type] = current['top_five_alert_types'][type];
3374
- } else {
3375
- if (current['top_five_alert_types'][type] > (acc[type] || 0)) {
3376
- acc[type] = current['top_five_alert_types'][type];
3377
- }
3378
- }
3379
- return acc;
3380
- });
3381
- return acc;
3382
- }, {});
3383
- sortedTopFivealerts = Object.entries(topAlerts).sort(([, a], [, b]) => b - a).slice(0, 5).reduce((r, [k, v]) => ({
3384
- ...r,
3385
- [k]: v
3386
- }), {});
3387
- formattedData = data.reduce((acc, current) => {
3388
- METRICS.forEach(m => {
3389
- if (!acc[m]) {
3390
- acc[m] = {};
3391
- }
3392
- acc[m][formatDate(current['created_at'])] = current[m];
3393
- return acc;
3394
- });
3395
- return acc;
3396
- }, {});
3397
- }
3398
- return {
3399
- ...formattedData,
3400
- top_five_alert_types: sortedTopFivealerts
3401
- };
3402
- };
3403
- async function fetchRepoAnalyticsData(repo, time, spinner, apiKey, outputJson, filePath) {
3404
- const socketSdk = await (0, _sdk$2.setupSdk)(apiKey);
3405
- const result = await (0, _apiHelpers$2.handleApiCall)(socketSdk.getRepoAnalytics(repo, time.toString()), 'fetching analytics data');
3406
- if (result.success === false) {
3407
- return (0, _apiHelpers$2.handleUnsuccessfulApiResponse)('getRepoAnalytics', result, spinner);
3408
- }
3409
- spinner.stop();
3410
- if (!result.data.length) {
3411
- return console.log('No analytics data is available for this organization yet.');
3412
- }
3413
- const data = formatData(result.data, 'repo');
3414
- if (outputJson && !filePath) {
3415
- return console.log(result.data);
3416
- }
3417
- if (filePath) {
3418
- _fs$1.writeFile(filePath, JSON.stringify(result.data), err => {
3419
- err ? console.error(err) : console.log(`Data successfully written to ${filePath}`);
3420
- });
3421
- return;
3422
- }
3423
- return displayAnalyticsScreen(data);
3424
- }
3425
- const displayAnalyticsScreen = data => {
3426
- const screen = _blessed$1.screen();
3427
- // eslint-disable-next-line
3428
- const grid = new _blessedContrib$1.grid({
3429
- rows: 5,
3430
- cols: 4,
3431
- screen
3432
- });
3433
- renderLineCharts(grid, screen, 'Total critical alerts', [0, 0, 1, 2], data['total_critical_alerts']);
3434
- renderLineCharts(grid, screen, 'Total high alerts', [0, 2, 1, 2], data['total_high_alerts']);
3435
- renderLineCharts(grid, screen, 'Total critical alerts added to the main branch', [1, 0, 1, 2], data['total_critical_added']);
3436
- renderLineCharts(grid, screen, 'Total high alerts added to the main branch', [1, 2, 1, 2], data['total_high_added']);
3437
- renderLineCharts(grid, screen, 'Total critical alerts prevented from the main branch', [2, 0, 1, 2], data['total_critical_prevented']);
3438
- renderLineCharts(grid, screen, 'Total high alerts prevented from the main branch', [2, 2, 1, 2], data['total_high_prevented']);
3439
- renderLineCharts(grid, screen, 'Total medium alerts prevented from the main branch', [3, 0, 1, 2], data['total_medium_prevented']);
3440
- renderLineCharts(grid, screen, 'Total low alerts prevented from the main branch', [3, 2, 1, 2], data['total_low_prevented']);
3441
- const bar = grid.set(4, 0, 1, 2, _blessedContrib$1.bar, {
3442
- label: 'Top 5 alert types',
3443
- barWidth: 10,
3444
- barSpacing: 17,
3445
- xOffset: 0,
3446
- maxHeight: 9,
3447
- barBgColor: 'magenta'
3448
- });
3449
- screen.append(bar); //must append before setting data
3450
-
3451
- bar.setData({
3452
- titles: Object.keys(data.top_five_alert_types),
3453
- data: Object.values(data.top_five_alert_types)
3454
- });
3455
- screen.render();
3456
- screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
3457
- };
3458
- const renderLineCharts = (grid, screen, title, coords, data) => {
3459
- const line = grid.set(...coords, _blessedContrib$1.line, {
3460
- style: {
3461
- line: "cyan",
3462
- text: "cyan",
3463
- baseline: "black"
3464
- },
3465
- xLabelPadding: 0,
3466
- xPadding: 0,
3467
- xOffset: 0,
3468
- wholeNumbersOnly: true,
3469
- legend: {
3470
- width: 1
3471
- },
3472
- label: title
3473
- });
3474
- screen.append(line);
3475
- const lineData = {
3476
- x: Object.keys(data),
3477
- y: Object.values(data)
3478
- };
3479
- line.setData([lineData]);
3480
- };
3481
-
3482
- var diffScan = {};
3483
-
3484
- var get$1 = {};
3485
-
3486
- var _interopRequireDefault$2 = vendor.interopRequireDefault.default;
3487
- Object.defineProperty(get$1, "__esModule", {
3488
- value: true
3489
- });
3490
- get$1.get = void 0;
3491
- var _chalk$1 = _interopRequireDefault$2(vendor.source);
3492
- var _fs = require$$0;
3493
- var _meow$1 = _interopRequireDefault$2(vendor.build);
3494
- var _ora$1 = _interopRequireDefault$2(vendor.ora);
3495
- var _util = require$$0$4;
3496
- var _flags$1 = flags;
3497
- var _formatting$1 = formatting;
3498
- var _sdk$1 = sdk.sdk;
3499
- var _errors$2 = sdk.errors;
3500
- var _apiHelpers$1 = apiHelpers;
3501
- const get = get$1.get = {
3502
- description: 'Get a diff scan for an organization',
3503
- async run(argv, importMeta, {
3504
- parentName
3505
- }) {
3506
- const name = `${parentName} get`;
3507
- const input = setupCommand$1(name, get.description, argv, importMeta);
3508
- if (input) {
3509
- const apiKey = (0, _sdk$1.getDefaultKey)();
3510
- if (!apiKey) {
3511
- throw new _errors$2.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
3512
- }
3513
- const spinnerText = 'Getting diff scan... \n';
3514
- const spinner = (0, _ora$1.default)(spinnerText).start();
3515
- await getDiffScan(input, spinner, apiKey);
3516
- }
3517
- }
3518
- };
3519
- const getDiffScanFlags = {
3520
- before: {
3521
- type: 'string',
3522
- shortFlag: 'b',
3523
- default: '',
3524
- description: 'The full scan ID of the base scan'
3525
- },
3526
- after: {
3527
- type: 'string',
3528
- shortFlag: 'a',
3529
- default: '',
3530
- description: 'The full scan ID of the head scan'
3531
- },
3532
- preview: {
3533
- type: 'boolean',
3534
- shortFlag: 'p',
3535
- default: true,
3536
- description: 'A boolean flag to persist or not the diff scan result'
3537
- },
3538
- file: {
3539
- type: 'string',
3540
- shortFlag: 'f',
3541
- default: '',
3542
- description: 'Path to a local file where the output should be saved'
3543
- }
3544
- };
3545
-
3546
- // Internal functions
3547
-
3548
- function setupCommand$1(name, description, argv, importMeta) {
3549
- const flags = {
3550
- ..._flags$1.outputFlags,
3551
- ...getDiffScanFlags
3552
- };
3553
- const cli = (0, _meow$1.default)(`
3554
- Usage
3555
- $ ${name} <org slug> --before=<before> --after=<after>
3556
-
3557
- Options
3558
- ${(0, _formatting$1.printFlagList)(flags, 6)}
3559
-
3560
- Examples
3561
- $ ${name} FakeCorp --before=aaa0aa0a-aaaa-0000-0a0a-0000000a00a0 --after=aaa1aa1a-aaaa-1111-1a1a-1111111a11a1
3562
- `, {
3563
- argv,
3564
- description,
3565
- importMeta,
3566
- flags
3567
- });
3568
- const {
3569
- json: outputJson,
3570
- markdown: outputMarkdown,
3571
- before,
3572
- after,
3573
- preview,
3574
- file
3575
- } = cli.flags;
3576
- if (!before || !after) {
3577
- console.error(`${_chalk$1.default.bgRed.white('Input error')}: Please specify a before and after full scan ID. To get full scans IDs, you can run the command "socket scan list <your org slug>". \n`);
3578
- cli.showHelp();
3579
- return;
3580
- }
3581
- if (cli.input.length < 1) {
3582
- console.error(`${_chalk$1.default.bgRed.white('Input error')}: Please provide an organization slug \n`);
3583
- cli.showHelp();
3584
- return;
3585
- }
3586
- const [orgSlug = ''] = cli.input;
3587
- return {
3588
- outputJson,
3589
- outputMarkdown,
3590
- before,
3591
- after,
3592
- preview,
3593
- orgSlug,
3594
- file
3595
- };
3596
- }
3597
- async function getDiffScan({
3598
- before,
3599
- after,
3600
- orgSlug,
3601
- file,
3602
- outputJson
3603
- }, spinner, apiKey) {
3604
- const response = await (0, _apiHelpers$1.queryOrgsAPI)(`${orgSlug}/full-scans/diff?before=${before}&after=${after}&preview`, apiKey);
3605
- const data = await response.json();
3606
- if (!response.ok) {
3607
- spinner.stop();
3608
- const err = await (0, _apiHelpers$1.handleAPIError)(response.status);
3609
- console.error(`${_chalk$1.default.bgRed.white(response.statusText)}: ${err} \n`);
3610
- return;
3611
- }
3612
- spinner.stop();
3613
- if (file && !outputJson) {
3614
- _fs.writeFile(file, JSON.stringify(data), err => {
3615
- err ? console.error(err) : console.log(`Data successfully written to ${file}`);
3616
- });
3617
- return;
3618
- }
3619
- if (outputJson) {
3620
- console.log(`\n Diff scan result: \n`);
3621
- console.log(_util.inspect(data, {
3622
- showHidden: false,
3623
- depth: null,
3624
- colors: true
3625
- }));
3626
- // @ts-ignore
3627
- console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data.diff_report_url)} \n`);
3628
- return;
3629
- }
3630
- console.log("Diff scan result: ");
3631
- console.log(data);
3632
- console.log(`\n 📝 To display the detailed report in the terminal, use the --json flag \n`);
3633
- // @ts-ignore
3634
- console.log(`\n View this diff scan in the Socket dashboard: ${_chalk$1.default.cyan(data.diff_report_url)} \n`);
3635
- }
3636
-
3637
- Object.defineProperty(diffScan, "__esModule", {
3638
- value: true
3639
- });
3640
- diffScan.diffScan = void 0;
3641
- var _get = get$1;
3642
- var _meowWithSubcommands$1 = meowWithSubcommands$1;
3643
- const description = 'Diff scans related commands';
3644
- diffScan.diffScan = {
3645
- description,
3646
- run: async (argv, importMeta, {
3647
- parentName
3648
- }) => {
3649
- await (0, _meowWithSubcommands$1.meowWithSubcommands)({
3650
- get: _get.get
3651
- }, {
3652
- argv,
3653
- description,
3654
- importMeta,
3655
- name: parentName + ' diff-scan'
3656
- });
3657
- }
3658
- };
3659
-
3660
- var threatFeed$1 = {};
3661
-
3662
- var _interopRequireDefault$1 = vendor.interopRequireDefault.default;
3663
- Object.defineProperty(threatFeed$1, "__esModule", {
3664
- value: true
3665
- });
3666
- threatFeed$1.threatFeed = void 0;
3667
- var _blessed = require$$1$2;
3668
- var _blessedContrib = require$$2$3;
3669
- var _meow = _interopRequireDefault$1(vendor.build);
3670
- var _ora = _interopRequireDefault$1(vendor.ora);
3671
- var _flags = flags;
3672
- var _formatting = formatting;
3673
- var _sdk = sdk.sdk;
3674
- var _errors$1 = sdk.errors;
3675
- var _apiHelpers = apiHelpers;
3676
- /* Not a fan of adding the no-check, mainly doing it because
3677
- the types associated with the blessed packages
3678
- create some type errors
3679
- */
3680
- // @ts-nocheck
3681
- // @ts-ignore
3682
-
3683
- // @ts-ignore
3684
-
3685
- const threatFeed = threatFeed$1.threatFeed = {
3686
- description: 'Look up the threat feed',
3687
- async run(argv, importMeta, {
3688
- parentName
3689
- }) {
3690
- const name = parentName + ' threat-feed';
3691
- const input = setupCommand(name, threatFeed.description, argv, importMeta);
3692
- if (input) {
3693
- const apiKey = (0, _sdk.getDefaultKey)();
3694
- if (!apiKey) {
3695
- throw new _errors$1.AuthError("User must be authenticated to run this command. To log in, run the command `socket login` and enter your API key.");
3696
- }
3697
- const spinner = (0, _ora.default)(`Looking up the threat feed \n`).start();
3698
- await fetchThreatFeed(input, spinner, apiKey);
3699
- }
3700
- }
3701
- };
3702
- const threatFeedFlags = {
3703
- perPage: {
3704
- type: 'number',
3705
- shortFlag: 'pp',
3706
- default: 30,
3707
- description: 'Number of items per page'
3708
- },
3709
- page: {
3710
- type: 'string',
3711
- shortFlag: 'p',
3712
- default: '1',
3713
- description: 'Page token'
3714
- },
3715
- direction: {
3716
- type: 'string',
3717
- shortFlag: 'd',
3718
- default: 'desc',
3719
- description: 'Order asc or desc by the createdAt attribute.'
3720
- },
3721
- filter: {
3722
- type: 'string',
3723
- shortFlag: 'f',
3724
- default: 'mal',
3725
- description: 'Filter what type of threats to return'
3726
- }
3727
- };
3728
-
3729
- // Internal functions
3730
-
3731
- function setupCommand(name, description, argv, importMeta) {
3732
- const flags = {
3733
- ...threatFeedFlags,
3734
- ..._flags.outputFlags
3735
- };
3736
- const cli = (0, _meow.default)(`
3737
- Usage
3738
- $ ${name}
3739
-
3740
- Options
3741
- ${(0, _formatting.printFlagList)(flags, 6)}
3742
-
3743
- Examples
3744
- $ ${name}
3745
- $ ${name} --perPage=5 --page=2 --direction=asc --filter=joke
3746
- `, {
3747
- argv,
3748
- description,
3749
- importMeta,
3750
- flags
3751
- });
3752
- const {
3753
- json: outputJson,
3754
- markdown: outputMarkdown,
3755
- perPage: per_page,
3756
- page,
3757
- direction,
3758
- filter
3759
- } = cli.flags;
3760
- return {
3761
- outputJson,
3762
- outputMarkdown,
3763
- per_page,
3764
- page,
3765
- direction,
3766
- filter
3767
- };
3768
- }
3769
- async function fetchThreatFeed({
3770
- per_page,
3771
- page,
3772
- direction,
3773
- filter,
3774
- outputJson
3775
- }, spinner, apiKey) {
3776
- const formattedQueryParams = formatQueryParams({
3777
- per_page,
3778
- page,
3779
- direction,
3780
- filter
3781
- }).join('&');
3782
- const response = await (0, _apiHelpers.queryAPI)(`threat-feed?${formattedQueryParams}`, apiKey);
3783
- const data = await response.json();
3784
- spinner.stop();
3785
- if (outputJson) {
3786
- return console.log(data);
3787
- }
3788
- const screen = _blessed.screen();
3789
- var table = _blessedContrib.table({
3790
- keys: 'true',
3791
- fg: 'white',
3792
- selectedFg: 'white',
3793
- selectedBg: 'magenta',
3794
- interactive: 'true',
3795
- label: 'Threat feed',
3796
- width: '100%',
3797
- height: '100%',
3798
- border: {
3799
- type: "line",
3800
- fg: "cyan"
3801
- },
3802
- columnSpacing: 3,
3803
- //in chars
3804
- columnWidth: [9, 30, 10, 17, 13, 100] /*in chars*/
3805
- });
3806
-
3807
- // allow control the table with the keyboard
3808
- table.focus();
3809
- screen.append(table);
3810
- const formattedOutput = formatResults(data.results);
3811
- table.setData({
3812
- headers: ['Ecosystem', 'Name', 'Version', 'Threat type', 'Detected at', 'Details'],
3813
- data: formattedOutput
3814
- });
3815
- screen.render();
3816
- screen.key(['escape', 'q', 'C-c'], () => process.exit(0));
3817
- }
3818
- const formatResults = data => {
3819
- return data.map(d => {
3820
- const ecosystem = d.purl.split('pkg:')[1].split('/')[0];
3821
- const name = d.purl.split('/')[1].split('@')[0];
3822
- const version = d.purl.split('@')[1];
3823
- const timeStart = new Date(d.createdAt);
3824
- const timeEnd = new Date();
3825
- const diff = getHourDiff(timeStart, timeEnd);
3826
- const hourDiff = diff > 0 ? `${diff} hours ago` : `${getMinDiff(timeStart, timeEnd)} minutes ago`;
3827
- return [ecosystem, decodeURIComponent(name), version, d.threatType, hourDiff, d.locationHtmlUrl];
3828
- });
3829
- };
3830
- const formatQueryParams = params => Object.entries(params).map(entry => `${entry[0]}=${entry[1]}`);
3831
- const getHourDiff = (start, end) => Math.floor((end - start) / 3600000);
3832
- const getMinDiff = (start, end) => Math.floor((end - start) / 60000);
3833
-
3834
- (function (exports) {
3835
-
3836
- Object.defineProperty(exports, "__esModule", {
3837
- value: true
3838
- });
3839
- var _cdxgen = cdxgen;
3840
- Object.keys(_cdxgen).forEach(function (key) {
3841
- if (key === "default" || key === "__esModule") return;
3842
- if (key in exports && exports[key] === _cdxgen[key]) return;
3843
- Object.defineProperty(exports, key, {
3844
- enumerable: true,
3845
- get: function () {
3846
- return _cdxgen[key];
3847
- }
3848
- });
3849
- });
3850
- var _info = info$1;
3851
- Object.keys(_info).forEach(function (key) {
3852
- if (key === "default" || key === "__esModule") return;
3853
- if (key in exports && exports[key] === _info[key]) return;
3854
- Object.defineProperty(exports, key, {
3855
- enumerable: true,
3856
- get: function () {
3857
- return _info[key];
3858
- }
3859
- });
3860
- });
3861
- var _login = login;
3862
- Object.keys(_login).forEach(function (key) {
3863
- if (key === "default" || key === "__esModule") return;
3864
- if (key in exports && exports[key] === _login[key]) return;
3865
- Object.defineProperty(exports, key, {
3866
- enumerable: true,
3867
- get: function () {
3868
- return _login[key];
3869
- }
3870
- });
3871
- });
3872
- var _logout = logout;
3873
- Object.keys(_logout).forEach(function (key) {
3874
- if (key === "default" || key === "__esModule") return;
3875
- if (key in exports && exports[key] === _logout[key]) return;
3876
- Object.defineProperty(exports, key, {
3877
- enumerable: true,
3878
- get: function () {
3879
- return _logout[key];
3880
- }
3881
- });
3882
- });
3883
- var _npm = npm;
3884
- Object.keys(_npm).forEach(function (key) {
3885
- if (key === "default" || key === "__esModule") return;
3886
- if (key in exports && exports[key] === _npm[key]) return;
3887
- Object.defineProperty(exports, key, {
3888
- enumerable: true,
3889
- get: function () {
3890
- return _npm[key];
3891
- }
3892
- });
3893
- });
3894
- var _npx = npx;
3895
- Object.keys(_npx).forEach(function (key) {
3896
- if (key === "default" || key === "__esModule") return;
3897
- if (key in exports && exports[key] === _npx[key]) return;
3898
- Object.defineProperty(exports, key, {
3899
- enumerable: true,
3900
- get: function () {
3901
- return _npx[key];
3902
- }
3903
- });
3904
- });
3905
- var _organization = organization;
3906
- Object.keys(_organization).forEach(function (key) {
3907
- if (key === "default" || key === "__esModule") return;
3908
- if (key in exports && exports[key] === _organization[key]) return;
3909
- Object.defineProperty(exports, key, {
3910
- enumerable: true,
3911
- get: function () {
3912
- return _organization[key];
3913
- }
3914
- });
3915
- });
3916
- var _rawNpm = rawNpm$1;
3917
- Object.keys(_rawNpm).forEach(function (key) {
3918
- if (key === "default" || key === "__esModule") return;
3919
- if (key in exports && exports[key] === _rawNpm[key]) return;
3920
- Object.defineProperty(exports, key, {
3921
- enumerable: true,
3922
- get: function () {
3923
- return _rawNpm[key];
3924
- }
3925
- });
3926
- });
3927
- var _rawNpx = rawNpx$1;
3928
- Object.keys(_rawNpx).forEach(function (key) {
3929
- if (key === "default" || key === "__esModule") return;
3930
- if (key in exports && exports[key] === _rawNpx[key]) return;
3931
- Object.defineProperty(exports, key, {
3932
- enumerable: true,
3933
- get: function () {
3934
- return _rawNpx[key];
3935
- }
3936
- });
3937
- });
3938
- var _report = report;
3939
- Object.keys(_report).forEach(function (key) {
3940
- if (key === "default" || key === "__esModule") return;
3941
- if (key in exports && exports[key] === _report[key]) return;
3942
- Object.defineProperty(exports, key, {
3943
- enumerable: true,
3944
- get: function () {
3945
- return _report[key];
3946
- }
3947
- });
3948
- });
3949
- var _wrapper = wrapper$1;
3950
- Object.keys(_wrapper).forEach(function (key) {
3951
- if (key === "default" || key === "__esModule") return;
3952
- if (key in exports && exports[key] === _wrapper[key]) return;
3953
- Object.defineProperty(exports, key, {
3954
- enumerable: true,
3955
- get: function () {
3956
- return _wrapper[key];
3957
- }
3958
- });
3959
- });
3960
- var _scan = scan;
3961
- Object.keys(_scan).forEach(function (key) {
3962
- if (key === "default" || key === "__esModule") return;
3963
- if (key in exports && exports[key] === _scan[key]) return;
3964
- Object.defineProperty(exports, key, {
3965
- enumerable: true,
3966
- get: function () {
3967
- return _scan[key];
3968
- }
3969
- });
3970
- });
3971
- var _auditLog = auditLog$1;
3972
- Object.keys(_auditLog).forEach(function (key) {
3973
- if (key === "default" || key === "__esModule") return;
3974
- if (key in exports && exports[key] === _auditLog[key]) return;
3975
- Object.defineProperty(exports, key, {
3976
- enumerable: true,
3977
- get: function () {
3978
- return _auditLog[key];
3979
- }
3980
- });
3981
- });
3982
- var _repos = repos;
3983
- Object.keys(_repos).forEach(function (key) {
3984
- if (key === "default" || key === "__esModule") return;
3985
- if (key in exports && exports[key] === _repos[key]) return;
3986
- Object.defineProperty(exports, key, {
3987
- enumerable: true,
3988
- get: function () {
3989
- return _repos[key];
3990
- }
3991
- });
3992
- });
3993
- var _dependencies = dependencies$1;
3994
- Object.keys(_dependencies).forEach(function (key) {
3995
- if (key === "default" || key === "__esModule") return;
3996
- if (key in exports && exports[key] === _dependencies[key]) return;
3997
- Object.defineProperty(exports, key, {
3998
- enumerable: true,
3999
- get: function () {
4000
- return _dependencies[key];
4001
- }
4002
- });
4003
- });
4004
- var _analytics = analytics$1;
4005
- Object.keys(_analytics).forEach(function (key) {
4006
- if (key === "default" || key === "__esModule") return;
4007
- if (key in exports && exports[key] === _analytics[key]) return;
4008
- Object.defineProperty(exports, key, {
4009
- enumerable: true,
4010
- get: function () {
4011
- return _analytics[key];
4012
- }
4013
- });
4014
- });
4015
- var _diffScan = diffScan;
4016
- Object.keys(_diffScan).forEach(function (key) {
4017
- if (key === "default" || key === "__esModule") return;
4018
- if (key in exports && exports[key] === _diffScan[key]) return;
4019
- Object.defineProperty(exports, key, {
4020
- enumerable: true,
4021
- get: function () {
4022
- return _diffScan[key];
4023
- }
4024
- });
4025
- });
4026
- var _threatFeed = threatFeed$1;
4027
- Object.keys(_threatFeed).forEach(function (key) {
4028
- if (key === "default" || key === "__esModule") return;
4029
- if (key in exports && exports[key] === _threatFeed[key]) return;
4030
- Object.defineProperty(exports, key, {
4031
- enumerable: true,
4032
- get: function () {
4033
- return _threatFeed[key];
4034
- }
4035
- });
4036
- });
4037
- } (commands));
4038
-
4039
- var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4040
- var _interopRequireDefault = vendor.interopRequireDefault.default;
4041
- var _nodeFs = require$$0;
4042
- var _nodePath = require$$1;
4043
- var _nodeUrl = require$$2$4;
4044
- var _chalk = _interopRequireDefault(vendor.source);
4045
- var _ponyCause = require$$6;
4046
- var _updateNotifier = _interopRequireDefault(vendor.updateNotifier);
4047
- var cliCommands = _interopRequireWildcard(commands, true);
4048
- var _chalkMarkdown = sdk.chalkMarkdown;
4049
- var _errors = sdk.errors;
4050
- var _meowWithSubcommands = meowWithSubcommands$1;
4051
- const distPath = __dirname;
4052
- const rootPath = _nodePath.resolve(distPath, '..');
4053
- const formattedCliCommands = Object.fromEntries(Object.entries(cliCommands).map(entry => {
4054
- entry[0] = camelToHyphen(entry[0]);
4055
- return entry;
4056
- }));
4057
- function camelToHyphen(str) {
4058
- return str.replace(/[A-Z]+/g, '-$&').toLowerCase();
4059
- }
4060
- (async () => {
4061
- try {
4062
- (0, _updateNotifier.default)({
4063
- pkg: JSON.parse((0, _nodeFs.readFileSync)(_nodePath.join(rootPath, 'package.json'), 'utf8'))
4064
- }).notify();
4065
- } catch {}
4066
- try {
4067
- await (0, _meowWithSubcommands.meowWithSubcommands)(formattedCliCommands, {
4068
- aliases: {
4069
- ci: {
4070
- description: 'Alias for "report create --view --strict"',
4071
- argv: ['report', 'create', '--view', '--strict']
4072
- }
4073
- },
4074
- argv: process.argv.slice(2),
4075
- name: 'socket',
4076
- importMeta: {
4077
- url: `${(0, _nodeUrl.pathToFileURL)(__filename)}`
4078
- }
4079
- });
4080
- } catch (err) {
4081
- let errorTitle;
4082
- let errorMessage = '';
4083
- let errorBody;
4084
- if (err instanceof _errors.AuthError) {
4085
- errorTitle = 'Authentication error';
4086
- errorMessage = err.message;
4087
- } else if (err instanceof _errors.InputError) {
4088
- errorTitle = 'Invalid input';
4089
- errorMessage = err.message;
4090
- errorBody = err.body;
4091
- } else if (err instanceof Error) {
4092
- errorTitle = 'Unexpected error';
4093
- errorMessage = (0, _ponyCause.messageWithCauses)(err);
4094
- errorBody = (0, _ponyCause.stackWithCauses)(err);
4095
- } else {
4096
- errorTitle = 'Unexpected error with no details';
4097
- }
4098
- console.error(`${_chalkMarkdown.logSymbols.error} ${_chalk.default.white.bgRed(errorTitle + ':')} ${errorMessage}`);
4099
- if (errorBody) {
4100
- console.error(`\n${errorBody}`);
4101
- }
4102
- process.exit(1);
4103
- }
4104
- })();
4105
-
4106
- (function (exports) {
4107
-
4108
- var _interopRequireWildcard = vendor.interopRequireWildcard.default;
4109
- Object.defineProperty(exports, "__esModule", {
4110
- value: true
4111
- });
4112
- var _exportNames = {};
4113
- Object.defineProperty(exports, "default", {
4114
- enumerable: true,
4115
- get: function () {
4116
- return _cli.default;
4117
- }
4118
- });
4119
- var _cli = _interopRequireWildcard(cli, true);
4120
- Object.keys(_cli).forEach(function (key) {
4121
- if (key === "default" || key === "__esModule") return;
4122
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
4123
- if (key in exports && exports[key] === _cli[key]) return;
4124
- Object.defineProperty(exports, key, {
4125
- enumerable: true,
4126
- get: function () {
4127
- return _cli[key];
4128
- }
4129
- });
4130
- });
4131
- } (cli$1));
4132
-
4133
- module.exports = cli$1;