"Fossies" - the Fresh Open Source Software Archive

Member "cli-1.1280.1/packages/snyk-protect/src/lib/analytics.ts" (20 Feb 2024, 1658 Bytes) of package /linux/misc/snyk-cli-1.1280.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) TypeScript source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 import { AnalyticsPayload, ProtectResult } from './types';
    2 import { postJson } from './http';
    3 import { getApiBaseUrl } from './snyk-api';
    4 import * as os from 'os';
    5 import { readFileSync, existsSync } from 'fs';
    6 import * as path from 'path';
    7 
    8 function getVersion(): string {
    9   return JSON.parse(
   10     readFileSync(path.resolve(__dirname, '../../package.json'), 'utf-8'),
   11   ).version;
   12 }
   13 
   14 function getAnalyticsData(result: ProtectResult): AnalyticsPayload {
   15   return {
   16     command: `@snyk/protect`,
   17     args: [],
   18     version: getVersion(),
   19     nodeVersion: process.version,
   20     metadata: {
   21       protectResult: result,
   22     },
   23   };
   24 }
   25 
   26 export async function sendAnalytics(result: ProtectResult) {
   27   if (!allowAnalytics()) {
   28     return;
   29   }
   30   try {
   31     const apiBaseUrl = getApiBaseUrl();
   32     const apiUrl = `${apiBaseUrl}/v1/analytics/cli`;
   33     const data = {
   34       data: getAnalyticsData(result),
   35     };
   36     await postJson(apiUrl, data);
   37   } catch (err) {
   38     // do nothing and log nothing
   39   }
   40 }
   41 
   42 function allowAnalytics(): boolean {
   43   try {
   44     const snykConfigFile = getSnykConfigFilePath();
   45     if (existsSync(snykConfigFile)) {
   46       const config = JSON.parse(readFileSync(snykConfigFile, 'utf-8'));
   47       if (
   48         config['disable-analytics'] === '1' ||
   49         config['disable-analytics'] === 1
   50       ) {
   51         return false;
   52       }
   53     }
   54     if (process.env.SNYK_DISABLE_ANALYTICS) {
   55       return false;
   56     }
   57   } catch (err) {
   58     // do nothing and log nothing
   59   }
   60   return true;
   61 }
   62 
   63 function getSnykConfigFilePath(): string {
   64   return (
   65     process.env.SNYK_CONFIG_FILE ||
   66     path.resolve(os.homedir(), '.config', 'configstore', 'snyk.json')
   67   );
   68 }