663.index.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. "use strict";
  2. exports.id = 663;
  3. exports.ids = [663,85];
  4. exports.modules = {
  5. /***/ 29430:
  6. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  7. Object.defineProperty(exports, "__esModule", ({ value: true }));
  8. exports.createApp = void 0;
  9. const Debug = __webpack_require__(15158);
  10. const apps_1 = __webpack_require__(14589);
  11. const promise_1 = __webpack_require__(90430);
  12. const spinner_1 = __webpack_require__(86766);
  13. const debug = Debug(apps_1.SNYK_APP_DEBUG);
  14. /**
  15. * Function to process the app creation request and
  16. * handle any errors that are request error and print
  17. * in a formatted string. It throws is error is unknown
  18. * or cannot be handled.
  19. * @param {ICreateAppRequest} data to create the app
  20. * @returns {String} response formatted string
  21. */
  22. async function createApp(data) {
  23. debug('App data', data);
  24. const { orgId, snykAppName: name, snykAppRedirectUris: redirectUris, snykAppScopes: scopes, } = data;
  25. const payload = {
  26. method: 'POST',
  27. url: apps_1.getAppsURL(apps_1.EAppsURL.CREATE_APP, { orgId }),
  28. body: {
  29. name,
  30. redirectUris,
  31. scopes,
  32. },
  33. qs: {
  34. version: '2021-08-11~experimental',
  35. },
  36. };
  37. try {
  38. await spinner_1.spinner('Creating your Snyk App');
  39. const response = await promise_1.makeRequestRest(payload);
  40. debug(response);
  41. spinner_1.spinner.clearAll();
  42. return apps_1.handleCreateAppRes(response);
  43. }
  44. catch (error) {
  45. spinner_1.spinner.clearAll();
  46. apps_1.handleRestError(error);
  47. }
  48. }
  49. exports.createApp = createApp;
  50. /***/ }),
  51. /***/ 68458:
  52. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  53. Object.defineProperty(exports, "__esModule", ({ value: true }));
  54. const Debug = __webpack_require__(15158);
  55. const process_command_args_1 = __webpack_require__(52369);
  56. const apps_1 = __webpack_require__(14589);
  57. const create_app_1 = __webpack_require__(29430);
  58. // import * as path from 'path';
  59. const create_app_2 = __webpack_require__(38276);
  60. const help_1 = __webpack_require__(21085);
  61. const debug = Debug(apps_1.SNYK_APP_DEBUG);
  62. async function apps(...args0) {
  63. debug('Snyk apps CLI called');
  64. const { options, paths } = process_command_args_1.processCommandArgs(...args0);
  65. debug(options, paths);
  66. const commandVerb1 = paths[0];
  67. const validCommandVerb = commandVerb1 && apps_1.validAppsSubCommands.includes(commandVerb1);
  68. if (!validCommandVerb) {
  69. // Display help md for apps
  70. debug(`Unknown subcommand: ${commandVerb1}`);
  71. return help_1.default('apps');
  72. }
  73. // Check if experimental flag is being used
  74. if (!options.experimental)
  75. throw new Error(apps_1.AppsErrorMessages.useExperimental);
  76. if (commandVerb1 === apps_1.EValidSubCommands.CREATE) {
  77. const createAppData = options.interactive
  78. ? await create_app_2.createAppDataInteractive()
  79. : create_app_2.createAppDataScriptable(options);
  80. return await create_app_1.createApp(createAppData);
  81. }
  82. }
  83. exports.default = apps;
  84. /***/ }),
  85. /***/ 21085:
  86. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  87. Object.defineProperty(exports, "__esModule", ({ value: true }));
  88. exports.findHelpFile = void 0;
  89. const fs = __webpack_require__(35747);
  90. const path = __webpack_require__(85622);
  91. const markdown_renderer_1 = __webpack_require__(99387);
  92. function findHelpFile(helpArgs, helpFolderPath = '../../help/cli-commands') {
  93. while (helpArgs.length > 0) {
  94. // cleanse the filename to only contain letters
  95. // aka: /\W/g but figured this was easier to read
  96. const file = `${helpArgs.join('-').replace(/[^a-z0-9-]/gi, '')}.md`;
  97. const testHelpAbsolutePath = path.resolve(__dirname, helpFolderPath, file);
  98. if (fs.existsSync(testHelpAbsolutePath)) {
  99. return testHelpAbsolutePath;
  100. }
  101. helpArgs = helpArgs.slice(0, -1);
  102. }
  103. return path.resolve(__dirname, helpFolderPath, `README.md`); // Default help file
  104. }
  105. exports.findHelpFile = findHelpFile;
  106. async function help(...args) {
  107. const helpArgs = args.filter((arg) => typeof arg === 'string');
  108. const helpFileAbsolutePath = findHelpFile(helpArgs);
  109. return markdown_renderer_1.renderMarkdown(fs.readFileSync(helpFileAbsolutePath, 'utf8'));
  110. }
  111. exports.default = help;
  112. /***/ }),
  113. /***/ 99387:
  114. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  115. Object.defineProperty(exports, "__esModule", ({ value: true }));
  116. exports.renderMarkdown = void 0;
  117. const marked_1 = __webpack_require__(30970);
  118. const chalk_1 = __webpack_require__(32589);
  119. const reflow_text_1 = __webpack_require__(67211);
  120. // stateful variable to control left-padding by header level
  121. let currentHeader = 1;
  122. const listItemSeparator = 'LISTITEMSEPARATOR'; // Helper string for rendering ListItems
  123. /**
  124. * @description get padding spaces depending on the last header level used
  125. * @returns string
  126. */
  127. function getLeftTextPadding() {
  128. return ' '.repeat(currentHeader === 1 || currentHeader === 2 ? 1 : currentHeader - 1);
  129. }
  130. /**
  131. * @description Reads current terminal width if available to limit column width for text-reflowing
  132. * @returns {number}
  133. */
  134. const defaultMaximumLineWidth = 100;
  135. function getIdealTextWidth(maximumLineWidth = defaultMaximumLineWidth) {
  136. if (typeof process.stdout.columns === 'number') {
  137. if (process.stdout.columns < maximumLineWidth) {
  138. return process.stdout.columns - getLeftTextPadding().length - 5;
  139. }
  140. }
  141. return maximumLineWidth - getLeftTextPadding().length;
  142. }
  143. // Marked custom renderer class
  144. const renderer = {
  145. em(text) {
  146. return chalk_1.default.italic(text);
  147. },
  148. strong(text) {
  149. return chalk_1.default.bold(text);
  150. },
  151. link(href, title, text) {
  152. // Don't render links to relative paths (like local files)
  153. if (href.startsWith('./') || !href.includes('://')) {
  154. return text;
  155. }
  156. const renderedLink = chalk_1.default.bold.blueBright(href);
  157. if (text && text !== href) {
  158. return `${text} ${renderedLink}`;
  159. }
  160. return renderedLink;
  161. },
  162. blockquote(quote) {
  163. return quote;
  164. },
  165. list(body, ordered, start) {
  166. return (body
  167. .split(listItemSeparator)
  168. .map((listItem, listItemIndex) => {
  169. const bulletPoint = ordered ? `${listItemIndex + start}. ` : '- ';
  170. return reflow_text_1.reflowText(listItem, getIdealTextWidth())
  171. .split('\n')
  172. .map((listItemLine, listItemLineIndex) => {
  173. if (!listItemLine) {
  174. return '';
  175. }
  176. return `${getLeftTextPadding()}${listItemLineIndex === 0 ? bulletPoint : ' '}${listItemLine}`;
  177. })
  178. .join('\n');
  179. })
  180. .join('\n') + '\n');
  181. },
  182. listitem(text) {
  183. return text + listItemSeparator;
  184. },
  185. paragraph(text) {
  186. return (reflow_text_1.reflowText(text, getIdealTextWidth())
  187. .split('\n')
  188. .map((s) => getLeftTextPadding() + chalk_1.default.reset() + s)
  189. .join('\n') + '\n\n');
  190. },
  191. codespan(text) {
  192. return chalk_1.default.italic.blueBright(`${text}`);
  193. },
  194. code(code) {
  195. return (code
  196. .split('\n')
  197. .map((s) => getLeftTextPadding() + chalk_1.default.reset() + s)
  198. .join('\n') + '\n\n');
  199. },
  200. heading(text, level) {
  201. currentHeader = level;
  202. let coloring;
  203. switch (level) {
  204. case 1:
  205. coloring = chalk_1.default.bold.underline;
  206. break;
  207. case 3:
  208. case 4:
  209. coloring = chalk_1.default;
  210. break;
  211. default:
  212. coloring = chalk_1.default.bold;
  213. break;
  214. }
  215. return `${' '.repeat(level === 1 ? 0 : currentHeader - 2)}${coloring(text)}\n`;
  216. },
  217. };
  218. marked_1.marked.use({ renderer });
  219. marked_1.marked.setOptions({
  220. mangle: false,
  221. });
  222. const htmlUnescapes = {
  223. '&amp;': '&',
  224. '&lt;': '<',
  225. '&gt;': '>',
  226. '&quot;': '"',
  227. '&#39;': "'",
  228. '&#96;': '`',
  229. '&#x20;': '',
  230. };
  231. /**
  232. * @description Replace HTML entities with their non-encoded variant
  233. * @param {string} text
  234. * @returns {string}
  235. */
  236. function unescape(text) {
  237. Object.entries(htmlUnescapes).forEach(([escapedChar, unescapedChar]) => {
  238. const escapedCharRegExp = new RegExp(escapedChar, 'g');
  239. text = text.replace(escapedCharRegExp, unescapedChar);
  240. });
  241. return text;
  242. }
  243. function renderMarkdown(markdown) {
  244. return unescape(marked_1.marked.parse(markdown));
  245. }
  246. exports.renderMarkdown = renderMarkdown;
  247. /***/ }),
  248. /***/ 67211:
  249. /***/ ((__unused_webpack_module, exports) => {
  250. /**
  251. Code in this file is adapted from mikaelbr/marked-terminal
  252. https://github.com/mikaelbr/marked-terminal/blob/7501b8bb24a5ed52ec7d9114d4aeefa14f1bf5e6/index.js#L234-L330
  253. MIT License
  254. Copyright (c) 2017 Mikael Brevik
  255. Permission is hereby granted, free of charge, to any person obtaining a copy
  256. of this software and associated documentation files (the "Software"), to deal
  257. in the Software without restriction, including without limitation the rights
  258. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  259. copies of the Software, and to permit persons to whom the Software is
  260. furnished to do so, subject to the following conditions:
  261. The above copyright notice and this permission notice shall be included in all
  262. copies or substantial portions of the Software.
  263. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  264. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  265. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  266. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  267. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  268. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  269. SOFTWARE.
  270. */
  271. Object.defineProperty(exports, "__esModule", ({ value: true }));
  272. exports.reflowText = void 0;
  273. // Compute length of str not including ANSI escape codes.
  274. // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  275. function textLength(str) {
  276. // eslint-disable-next-line no-control-regex
  277. return str.replace(/\u001b\[(?:\d{1,3})(?:;\d{1,3})*m/g, '').length;
  278. }
  279. // Munge \n's and spaces in "text" so that the number of
  280. // characters between \n's is less than or equal to "width".
  281. function reflowText(text, width) {
  282. const HARD_RETURN = '\r|\n';
  283. const HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br ?/?>');
  284. const splitRe = HARD_RETURN_GFM_RE;
  285. const sections = text.split(splitRe);
  286. const reflowed = [];
  287. sections.forEach((section) => {
  288. // Split the section by escape codes so that we can
  289. // deal with them separately.
  290. // eslint-disable-next-line no-control-regex
  291. const fragments = section.split(/(\u001b\[(?:\d{1,3})(?:;\d{1,3})*m)/g);
  292. let column = 0;
  293. let currentLine = '';
  294. let lastWasEscapeChar = false;
  295. while (fragments.length) {
  296. const fragment = fragments[0];
  297. if (fragment === '') {
  298. fragments.splice(0, 1);
  299. lastWasEscapeChar = false;
  300. continue;
  301. }
  302. // This is an escape code - leave it whole and
  303. // move to the next fragment.
  304. if (!textLength(fragment)) {
  305. currentLine += fragment;
  306. fragments.splice(0, 1);
  307. lastWasEscapeChar = true;
  308. continue;
  309. }
  310. const words = fragment.split(/[ \t\n]+/);
  311. for (let i = 0; i < words.length; i++) {
  312. let word = words[i];
  313. let addSpace = column != 0;
  314. if (lastWasEscapeChar)
  315. addSpace = false;
  316. // If adding the new word overflows the required width
  317. if (column + word.length > width) {
  318. if (word.length <= width) {
  319. // If the new word is smaller than the required width
  320. // just add it at the beginning of a new line
  321. reflowed.push(currentLine);
  322. currentLine = word;
  323. column = word.length;
  324. }
  325. else {
  326. // If the new word is longer than the required width
  327. // split this word into smaller parts.
  328. const w = word.substr(0, width - column);
  329. if (addSpace)
  330. currentLine += ' ';
  331. currentLine += w;
  332. reflowed.push(currentLine);
  333. currentLine = '';
  334. column = 0;
  335. word = word.substr(w.length);
  336. while (word.length) {
  337. const w = word.substr(0, width);
  338. if (!w.length)
  339. break;
  340. if (w.length < width) {
  341. currentLine = w;
  342. column = w.length;
  343. break;
  344. }
  345. else {
  346. reflowed.push(w);
  347. word = word.substr(width);
  348. }
  349. }
  350. }
  351. }
  352. else {
  353. if (addSpace) {
  354. currentLine += ' ';
  355. column++;
  356. }
  357. currentLine += word;
  358. column += word.length;
  359. }
  360. lastWasEscapeChar = false;
  361. }
  362. fragments.splice(0, 1);
  363. }
  364. if (textLength(currentLine))
  365. reflowed.push(currentLine);
  366. });
  367. return reflowed.join('\n');
  368. }
  369. exports.reflowText = reflowText;
  370. /***/ }),
  371. /***/ 52369:
  372. /***/ ((__unused_webpack_module, exports) => {
  373. Object.defineProperty(exports, "__esModule", ({ value: true }));
  374. exports.processCommandArgs = void 0;
  375. function processCommandArgs(...args) {
  376. let options = {};
  377. if (typeof args[args.length - 1] === 'object') {
  378. options = args.pop();
  379. }
  380. args = args.filter(Boolean);
  381. // For repository scanning, populate with default path (cwd) if no path given
  382. if (args.length === 0 && !options.docker) {
  383. args.unshift(process.cwd());
  384. }
  385. return { options, paths: args };
  386. }
  387. exports.processCommandArgs = processCommandArgs;
  388. /***/ }),
  389. /***/ 89019:
  390. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  391. Object.defineProperty(exports, "__esModule", ({ value: true }));
  392. exports.CreateAppPromptData = exports.AppsErrorMessages = exports.validAppsSubCommands = exports.EAppsURL = exports.EValidSubCommands = exports.SNYK_APP_DEBUG = exports.SNYK_APP_ORG_ID = exports.SNYK_APP_CLIENT_ID = exports.SNYK_APP_SCOPES = exports.SNYK_APP_REDIRECT_URIS = exports.SNYK_APP_NAME = void 0;
  393. const chalk_1 = __webpack_require__(32589);
  394. exports.SNYK_APP_NAME = 'snykAppName';
  395. exports.SNYK_APP_REDIRECT_URIS = 'snykAppRedirectUris';
  396. exports.SNYK_APP_SCOPES = 'snykAppScopes';
  397. exports.SNYK_APP_CLIENT_ID = 'snykAppClientId';
  398. exports.SNYK_APP_ORG_ID = 'snykAppOrgId';
  399. exports.SNYK_APP_DEBUG = 'snyk:apps';
  400. var EValidSubCommands;
  401. (function (EValidSubCommands) {
  402. EValidSubCommands["CREATE"] = "create";
  403. })(EValidSubCommands = exports.EValidSubCommands || (exports.EValidSubCommands = {}));
  404. var EAppsURL;
  405. (function (EAppsURL) {
  406. EAppsURL[EAppsURL["CREATE_APP"] = 0] = "CREATE_APP";
  407. })(EAppsURL = exports.EAppsURL || (exports.EAppsURL = {}));
  408. exports.validAppsSubCommands = Object.values(EValidSubCommands);
  409. exports.AppsErrorMessages = {
  410. orgRequired: `Option '--org' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,
  411. nameRequired: `Option '--name' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,
  412. redirectUrisRequired: `Option '--redirect-uris' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,
  413. scopesRequired: `Option '--scopes' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,
  414. useExperimental: `\n${chalk_1.default.redBright("All 'apps' commands are only accessible behind the '--experimental' flag.")}\n
  415. The behaviour can change at any time, without prior notice.
  416. You are kindly advised to use all the commands with caution.
  417. ${chalk_1.default.bold('Usage')}
  418. ${chalk_1.default.italic('snyk apps <COMMAND> --experimental')}\n`,
  419. };
  420. exports.CreateAppPromptData = {
  421. SNYK_APP_NAME: {
  422. name: exports.SNYK_APP_NAME,
  423. message: `Name of the Snyk App (visible to users when they install the Snyk App)?`,
  424. },
  425. SNYK_APP_REDIRECT_URIS: {
  426. name: exports.SNYK_APP_REDIRECT_URIS,
  427. message: `Your Snyk App's redirect URIs (comma seprated list. ${chalk_1.default.yellowBright(' Ex: https://example1.com,https://example2.com')})?: `,
  428. },
  429. SNYK_APP_SCOPES: {
  430. name: exports.SNYK_APP_SCOPES,
  431. message: `Your Snyk App's permission scopes (comma separated list. ${chalk_1.default.yellowBright(' Ex: org.read,org.report.read')})?: `,
  432. },
  433. SNYK_APP_ORG_ID: {
  434. name: exports.SNYK_APP_ORG_ID,
  435. message: 'Please provide the org id under which you want to create your Snyk App: ',
  436. },
  437. };
  438. /***/ }),
  439. /***/ 38276:
  440. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  441. Object.defineProperty(exports, "__esModule", ({ value: true }));
  442. exports.createAppDataInteractive = exports.createAppDataScriptable = void 0;
  443. const __1 = __webpack_require__(14589);
  444. const enquirer = __webpack_require__(84031);
  445. const errors_1 = __webpack_require__(55191);
  446. /**
  447. * Validates and parsed the data required to create app.
  448. * Throws error if option is not provided or is invalid
  449. * @param {ICreateAppOptions} options required to create an app
  450. * @returns {ICreateAppRequest} data that is used to make the request
  451. */
  452. function createAppDataScriptable(options) {
  453. if (!options.org) {
  454. throw new errors_1.ValidationError(__1.AppsErrorMessages.orgRequired);
  455. }
  456. else if (typeof __1.validateUUID(options.org) === 'string') {
  457. // Combines to form "Invalid UUID provided for org id"
  458. throw new errors_1.ValidationError(`${__1.validateUUID(options.org)} for org id`);
  459. }
  460. else if (!options.name) {
  461. throw new errors_1.ValidationError(__1.AppsErrorMessages.nameRequired);
  462. }
  463. else if (!options['redirect-uris']) {
  464. throw new errors_1.ValidationError(__1.AppsErrorMessages.redirectUrisRequired);
  465. }
  466. else if (typeof __1.validateAllURL(options['redirect-uris']) === 'string') {
  467. throw new errors_1.ValidationError(__1.validateAllURL(options['redirect-uris']));
  468. }
  469. else if (!options.scopes) {
  470. throw new errors_1.ValidationError(__1.AppsErrorMessages.scopesRequired);
  471. }
  472. else {
  473. return {
  474. orgId: options.org,
  475. snykAppName: options.name,
  476. snykAppRedirectUris: options['redirect-uris']
  477. .replace(/\s+/g, '')
  478. .split(','),
  479. snykAppScopes: options.scopes.replace(/\s+/g, '').split(','),
  480. };
  481. }
  482. }
  483. exports.createAppDataScriptable = createAppDataScriptable;
  484. // Interactive format
  485. async function createAppDataInteractive() {
  486. // Proceed with interactive
  487. const answers = await enquirer.prompt(__1.createAppPrompts);
  488. // Process answers
  489. const snykAppName = answers[__1.SNYK_APP_NAME].trim();
  490. const snykAppRedirectUris = answers[__1.SNYK_APP_REDIRECT_URIS].replace(/\s+/g, '').split(',');
  491. const snykAppScopes = answers[__1.SNYK_APP_SCOPES].replace(/\s+/g, '').split(',');
  492. const orgId = answers[__1.SNYK_APP_ORG_ID].trim();
  493. // POST: to create an app
  494. return {
  495. orgId,
  496. snykAppName,
  497. snykAppRedirectUris,
  498. snykAppScopes,
  499. };
  500. }
  501. exports.createAppDataInteractive = createAppDataInteractive;
  502. /***/ }),
  503. /***/ 14589:
  504. /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
  505. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  506. if (k2 === undefined) k2 = k;
  507. Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
  508. }) : (function(o, m, k, k2) {
  509. if (k2 === undefined) k2 = k;
  510. o[k2] = m[k];
  511. }));
  512. var __exportStar = (this && this.__exportStar) || function(m, exports) {
  513. for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
  514. };
  515. Object.defineProperty(exports, "__esModule", ({ value: true }));
  516. __exportStar(__webpack_require__(89019), exports);
  517. __exportStar(__webpack_require__(86950), exports);
  518. __exportStar(__webpack_require__(31940), exports);
  519. __exportStar(__webpack_require__(72511), exports);
  520. __exportStar(__webpack_require__(46693), exports);
  521. __exportStar(__webpack_require__(8864), exports);
  522. /***/ }),
  523. /***/ 8864:
  524. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  525. Object.defineProperty(exports, "__esModule", ({ value: true }));
  526. exports.validInput = exports.validateUUID = exports.validURL = exports.validateAllURL = void 0;
  527. const uuid = __webpack_require__(42277);
  528. /**
  529. *
  530. * @param {String} input of space separated URL/URI passed by
  531. * user for redirect URIs
  532. * @returns { String | Boolean } complying with enquirer return values, the function
  533. * separates the string on space and validates each to see
  534. * if a valid URL/URI. Return a string if invalid and
  535. * boolean true if valid
  536. */
  537. function validateAllURL(input) {
  538. const trimmedInput = input.trim();
  539. let errMessage = '';
  540. for (const i of trimmedInput.split(',')) {
  541. if (typeof validURL(i) == 'string')
  542. errMessage = errMessage + `\n${validURL(i)}`;
  543. }
  544. if (errMessage)
  545. return errMessage;
  546. return true;
  547. }
  548. exports.validateAllURL = validateAllURL;
  549. /**
  550. * Custom validation logic which takes in consideration
  551. * creation of Snyk Apps and thus allows localhost.com
  552. * as a valid URL.
  553. * @param {String} input of URI/URL value to validate using
  554. * regex
  555. * @returns {String | Boolean } string message is not valid
  556. * and boolean true if valid
  557. */
  558. function validURL(input) {
  559. try {
  560. new URL(input);
  561. return true;
  562. }
  563. catch (error) {
  564. return `${input} is not a valid URL`;
  565. }
  566. }
  567. exports.validURL = validURL;
  568. /**
  569. * Function validates if a valid UUID (version of UUID not tacken into account)
  570. * @param {String} input UUID to be validated
  571. * @returns {String | Boolean } string message is not valid
  572. * and boolean true if valid
  573. */
  574. function validateUUID(input) {
  575. return uuid.validate(input) ? true : 'Invalid UUID provided';
  576. }
  577. exports.validateUUID = validateUUID;
  578. /**
  579. * @param {String} input
  580. * @returns {String | Boolean } string message is not valid
  581. * and boolean true if valid
  582. */
  583. function validInput(input) {
  584. if (!input)
  585. return 'Please enter something';
  586. return true;
  587. }
  588. exports.validInput = validInput;
  589. /***/ }),
  590. /***/ 86950:
  591. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  592. Object.defineProperty(exports, "__esModule", ({ value: true }));
  593. exports.createAppPrompts = void 0;
  594. const constants_1 = __webpack_require__(89019);
  595. const input_validator_1 = __webpack_require__(8864);
  596. /**
  597. * Prompts for $snyk apps create command
  598. */
  599. exports.createAppPrompts = [
  600. {
  601. name: constants_1.CreateAppPromptData.SNYK_APP_NAME.name,
  602. type: 'input',
  603. message: constants_1.CreateAppPromptData.SNYK_APP_NAME.message,
  604. validate: input_validator_1.validInput,
  605. },
  606. {
  607. name: constants_1.CreateAppPromptData.SNYK_APP_REDIRECT_URIS.name,
  608. type: 'input',
  609. message: constants_1.CreateAppPromptData.SNYK_APP_REDIRECT_URIS.message,
  610. validate: input_validator_1.validateAllURL,
  611. },
  612. {
  613. name: constants_1.CreateAppPromptData.SNYK_APP_SCOPES.name,
  614. type: 'input',
  615. message: constants_1.CreateAppPromptData.SNYK_APP_SCOPES.message,
  616. validate: input_validator_1.validInput,
  617. },
  618. {
  619. name: constants_1.CreateAppPromptData.SNYK_APP_ORG_ID.name,
  620. type: 'input',
  621. message: constants_1.CreateAppPromptData.SNYK_APP_ORG_ID.message,
  622. validate: input_validator_1.validateUUID,
  623. },
  624. ];
  625. /***/ }),
  626. /***/ 72511:
  627. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  628. Object.defineProperty(exports, "__esModule", ({ value: true }));
  629. exports.handleCreateAppRes = exports.handleRestError = exports.getAppsURL = void 0;
  630. /**
  631. * Collection of utility function for the
  632. * $snyk apps commands
  633. */
  634. const _1 = __webpack_require__(14589);
  635. const chalk_1 = __webpack_require__(32589);
  636. const errors_1 = __webpack_require__(55191);
  637. const Debug = __webpack_require__(15158);
  638. const config_1 = __webpack_require__(25425);
  639. const debug = Debug(_1.SNYK_APP_DEBUG);
  640. function getAppsURL(selection, opts = {}) {
  641. // Get the rest URL from user config
  642. // Environment variable takes precendence over config
  643. const baseURL = config_1.default.API_REST_URL;
  644. debug(`API rest base URL => ${baseURL}`);
  645. switch (selection) {
  646. case _1.EAppsURL.CREATE_APP:
  647. return `${baseURL}/orgs/${opts.orgId}/apps`;
  648. default:
  649. throw new Error('Invalid selection for URL');
  650. }
  651. }
  652. exports.getAppsURL = getAppsURL;
  653. function handleRestError(error) {
  654. if (error.code) {
  655. if (error.code === 400) {
  656. // Bad request
  657. const responseJSON = error.body;
  658. const errString = errorsToDisplayString(responseJSON);
  659. throw new Error(errString);
  660. }
  661. else if (error.code === 401) {
  662. // Unauthorized
  663. throw errors_1.AuthFailedError();
  664. }
  665. else if (error.code === 403) {
  666. throw new Error('Forbidden! the authentication token does not have access to the resource.');
  667. }
  668. else if (error.code === 404) {
  669. const responseJSON = error.body;
  670. const errString = errorsToDisplayString(responseJSON);
  671. throw new Error(errString);
  672. }
  673. else if (error.code === 500) {
  674. throw new errors_1.InternalServerError('Internal server error');
  675. }
  676. else {
  677. throw new Error(error.message);
  678. }
  679. }
  680. else {
  681. throw error;
  682. }
  683. }
  684. exports.handleRestError = handleRestError;
  685. /**
  686. * @param errRes RestError response
  687. * @returns {String} Iterates over error and
  688. * converts them into a readible string
  689. */
  690. function errorsToDisplayString(errRes) {
  691. const resString = `Uh oh! an error occurred while trying to create the Snyk App.
  692. Please run the command with '--debug' or '-d' to get more information`;
  693. if (!errRes.errors)
  694. return resString;
  695. errRes.errors.forEach((e) => {
  696. let metaString = '', sourceString = '';
  697. if (e.meta) {
  698. for (const [key, value] of Object.entries(e.meta)) {
  699. metaString += `${key}: ${value}\n`;
  700. }
  701. }
  702. if (e.source) {
  703. for (const [key, value] of Object.entries(e.source)) {
  704. sourceString += `${key}: ${value}\n`;
  705. }
  706. }
  707. const meta = metaString || '-';
  708. const source = sourceString || '-';
  709. return `Uh oh! an error occured while trying to create the Snyk App.
  710. Error Description:\t${e.detail}
  711. Request Status:\t${e.status}
  712. Source:\t${source}
  713. Meta:\t${meta}`;
  714. });
  715. return resString;
  716. }
  717. function handleCreateAppRes(res) {
  718. const { name, clientId, redirectUris, scopes, isPublic, clientSecret, } = res.data.attributes;
  719. return `Snyk App created successfully!
  720. Please ensure you save the following details:
  721. App Name:\t${name}
  722. Client ID:\t${clientId}
  723. Redirect URIs:\t${redirectUris}
  724. Scopes:\t${scopes}
  725. Is App Public:\t${isPublic}
  726. Client Secret (${chalk_1.default.redBright('keep it safe and protected')}):\t${clientSecret}`;
  727. }
  728. exports.handleCreateAppRes = handleCreateAppRes;
  729. /***/ }),
  730. /***/ 31940:
  731. /***/ ((__unused_webpack_module, exports) => {
  732. Object.defineProperty(exports, "__esModule", ({ value: true }));
  733. /***/ }),
  734. /***/ 46693:
  735. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  736. Object.defineProperty(exports, "__esModule", ({ value: true }));
  737. exports.readAppsHelpMarkdown = void 0;
  738. const fs = __webpack_require__(35747);
  739. const markdown_renderer_1 = __webpack_require__(99387);
  740. function readAppsHelpMarkdown(filename) {
  741. const file = fs.readFileSync(filename, 'utf8');
  742. return markdown_renderer_1.renderMarkdown(file);
  743. }
  744. exports.readAppsHelpMarkdown = readAppsHelpMarkdown;
  745. /***/ }),
  746. /***/ 90430:
  747. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  748. Object.defineProperty(exports, "__esModule", ({ value: true }));
  749. exports.makeRequestRest = exports.makeRequest = void 0;
  750. const api_token_1 = __webpack_require__(95181);
  751. const request = __webpack_require__(52050);
  752. async function makeRequest(payload) {
  753. return new Promise((resolve, reject) => {
  754. request.makeRequest(payload, (error, res, body) => {
  755. if (error) {
  756. return reject(error);
  757. }
  758. if (res.statusCode !== 200) {
  759. return reject({
  760. code: res.statusCode,
  761. message: body === null || body === void 0 ? void 0 : body.message,
  762. });
  763. }
  764. resolve(body);
  765. });
  766. });
  767. }
  768. exports.makeRequest = makeRequest;
  769. /**
  770. * All rest request will essentially be the same and are JSON by default
  771. * Thus if no headers provided default headers are used
  772. * @param {any} payload for the request
  773. * @returns
  774. */
  775. async function makeRequestRest(payload) {
  776. return new Promise((resolve, reject) => {
  777. var _a;
  778. payload.headers = (_a = payload.headers) !== null && _a !== void 0 ? _a : {
  779. 'Content-Type': 'application/vnd.api+json',
  780. authorization: api_token_1.getAuthHeader(),
  781. };
  782. payload.json = true;
  783. request.makeRequest(payload, (error, res, body) => {
  784. if (error) {
  785. return reject(error);
  786. }
  787. if (res.statusCode >= 400) {
  788. return reject({
  789. code: res.statusCode,
  790. body: JSON.parse(body),
  791. });
  792. }
  793. resolve(JSON.parse(body));
  794. });
  795. });
  796. }
  797. exports.makeRequestRest = makeRequestRest;
  798. /***/ })
  799. };
  800. ;
  801. //# sourceMappingURL=663.index.js.map