fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 99 lines 2.5 kB view raw
1import type { MaybeArray, MaybeFunc } from '@hey-api/types'; 2import colors from 'ansi-colors'; 3// @ts-expect-error 4import colorSupport from 'color-support'; 5 6colors.enabled = colorSupport().hasBasic; 7 8const DEBUG_NAMESPACE = 'heyapi'; 9 10const NO_WARNINGS = /^(1|true|yes|on)$/i.test(process.env.HEYAPI_DISABLE_WARNINGS ?? ''); 11 12const DebugGroups = { 13 analyzer: colors.greenBright, 14 dsl: colors.cyanBright, 15 file: colors.yellowBright, 16 registry: colors.blueBright, 17 symbol: colors.magentaBright, 18} as const; 19 20const WarnGroups = { 21 deprecated: colors.magentaBright, 22} as const; 23 24let cachedDebugGroups: Set<string> | undefined; 25function getDebugGroups(): Set<string> { 26 if (cachedDebugGroups) return cachedDebugGroups; 27 28 const value = process.env.DEBUG; 29 cachedDebugGroups = new Set(value ? value.split(',').map((x) => x.trim().toLowerCase()) : []); 30 31 return cachedDebugGroups; 32} 33 34/** 35 * Tracks which deprecations have been shown to avoid spam. 36 */ 37const shownDeprecations = new Set<string>(); 38 39function debug(message: string, group: keyof typeof DebugGroups) { 40 const groups = getDebugGroups(); 41 if ( 42 !( 43 groups.has('*') || 44 groups.has(`${DEBUG_NAMESPACE}:*`) || 45 groups.has(`${DEBUG_NAMESPACE}:${group}`) || 46 groups.has(group) 47 ) 48 ) { 49 return; 50 } 51 52 const color = DebugGroups[group] ?? colors.whiteBright; 53 const prefix = color(`${DEBUG_NAMESPACE}:${group}`); 54 55 console.debug(`${prefix} ${message}`); 56} 57 58function warn(message: string, group: keyof typeof WarnGroups) { 59 if (NO_WARNINGS) return; 60 61 const color = WarnGroups[group] ?? colors.yellowBright; 62 63 console.warn(color(`${message}`)); 64} 65 66function warnDeprecated({ 67 context, 68 field, 69 replacement, 70}: { 71 context?: string; 72 field: string; 73 replacement?: MaybeFunc<(field: string) => MaybeArray<string>>; 74}) { 75 const key = context 76 ? `${context}:${field}:${JSON.stringify(replacement)}` 77 : `${field}:${JSON.stringify(replacement)}`; 78 79 if (shownDeprecations.has(key)) return; 80 shownDeprecations.add(key); 81 82 let message = `\`${field}\` is deprecated.`; 83 84 if (replacement) { 85 const reps = typeof replacement === 'function' ? replacement(field) : replacement; 86 const repArray = reps instanceof Array ? reps : [reps]; 87 const repString = repArray.map((r) => `\`${r}\``).join(' or '); 88 message += ` Use ${repString} instead.`; 89 } 90 91 const prefix = context ? `[${context}] ` : ''; 92 warn(`${prefix}${message}`, 'deprecated'); 93} 94 95export const log = { 96 debug, 97 warn, 98 warnDeprecated, 99};