|
| 1 | +import config from '../config'; |
| 2 | +import { getAuthHeader } from '../api-token'; |
| 3 | +import { FeatureFlagsEvaluationResponse } from './types'; |
| 4 | +import { makeRequest } from '../request'; |
| 5 | +import { AuthFailedError, ValidationError } from '../errors'; |
| 6 | +import { TestLimitReachedError } from '../../cli/commands/test/iac/local-execution/usage-tracking'; |
| 7 | + |
| 8 | +export const SHOW_MAVEN_BUILD_SCOPE = 'show-maven-build-scope'; |
| 9 | + |
| 10 | +export async function evaluateFeatureFlagsForOrg( |
| 11 | + flags: string[], |
| 12 | + orgId: string, |
| 13 | + version = '2024-10-15', |
| 14 | +): Promise<FeatureFlagsEvaluationResponse> { |
| 15 | + if (!orgId.trim()) { |
| 16 | + throw new Error('orgId is required'); |
| 17 | + } |
| 18 | + |
| 19 | + const url = |
| 20 | + `${config.API_HIDDEN_URL}/orgs/${encodeURIComponent(orgId)}` + |
| 21 | + `/feature_flags/evaluation?version=${encodeURIComponent(version)}`; |
| 22 | + |
| 23 | + const payload = { |
| 24 | + data: { |
| 25 | + type: 'feature_flags_evaluation', |
| 26 | + attributes: { flags }, |
| 27 | + }, |
| 28 | + }; |
| 29 | + |
| 30 | + const { res, body } = await makeRequest({ |
| 31 | + url, |
| 32 | + method: 'POST', |
| 33 | + headers: { |
| 34 | + 'Content-Type': 'application/vnd.api+json', |
| 35 | + Authorization: getAuthHeader(), |
| 36 | + }, |
| 37 | + body: payload, |
| 38 | + json: true, |
| 39 | + noCompression: true, |
| 40 | + }); |
| 41 | + |
| 42 | + switch (res.statusCode) { |
| 43 | + case 200: |
| 44 | + break; |
| 45 | + case 401: |
| 46 | + throw AuthFailedError(); |
| 47 | + case 429: |
| 48 | + throw new TestLimitReachedError(); |
| 49 | + default: |
| 50 | + throw new ValidationError( |
| 51 | + res.body?.error ?? 'An error occurred, please contact Snyk support', |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + if (body?.errors?.length) { |
| 56 | + const first = body.errors[0]; |
| 57 | + throw new Error( |
| 58 | + `Feature flag evaluation failed: ${first?.status ?? res.statusCode} ${ |
| 59 | + first?.detail ?? res.statusMessage |
| 60 | + }`, |
| 61 | + ); |
| 62 | + } |
| 63 | + |
| 64 | + return body as FeatureFlagsEvaluationResponse; |
| 65 | +} |
| 66 | + |
| 67 | +export async function getFeatureFlagValue( |
| 68 | + flag: string, |
| 69 | + orgId: string, |
| 70 | +): Promise<boolean> { |
| 71 | + try { |
| 72 | + const result = await evaluateFeatureFlagsForOrg([flag], orgId); |
| 73 | + |
| 74 | + return ( |
| 75 | + result.data.attributes.evaluations.find((e) => e.key === flag)?.value ?? |
| 76 | + false |
| 77 | + ); |
| 78 | + } catch (err) { |
| 79 | + return false; |
| 80 | + } |
| 81 | +} |
0 commit comments