utils.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. import {Query} from 'history';
  2. import cloneDeep from 'lodash/cloneDeep';
  3. import isObject from 'lodash/isObject';
  4. import ConfigStore from 'sentry/stores/configStore';
  5. import {Project} from 'sentry/types';
  6. import {EventTag} from 'sentry/types/event';
  7. import {formatNumberWithDynamicDecimalPoints} from 'sentry/utils/formatters';
  8. import {appendTagCondition} from 'sentry/utils/queryString';
  9. function arrayIsEqual(arr?: any[], other?: any[], deep?: boolean): boolean {
  10. // if the other array is a falsy value, return
  11. if (!arr && !other) {
  12. return true;
  13. }
  14. if (!arr || !other) {
  15. return false;
  16. }
  17. // compare lengths - can save a lot of time
  18. if (arr.length !== other.length) {
  19. return false;
  20. }
  21. return arr.every((val, idx) => valueIsEqual(val, other[idx], deep));
  22. }
  23. /**
  24. * Omit keys from an object. The return value will be a deep clone of the input,
  25. * meaning none of the references will be preserved. If you require faster shallow cloning,
  26. * use {prop, ...rest} = obj spread syntax instead.
  27. */
  28. export function omit<T extends object, K extends Extract<keyof T, string>>(
  29. obj: T | null | undefined,
  30. key: K | (string & {})
  31. ): Omit<T, K>;
  32. export function omit<T extends object, K extends Extract<keyof T, string>>(
  33. obj: T | null | undefined,
  34. key: (K | (string & {}))[] | readonly (K | (string & {}))[]
  35. ): Pick<T, Exclude<keyof T, K[]>>;
  36. export function omit<T extends object, K extends Extract<keyof T, string>>(
  37. obj: T | null | undefined,
  38. // @TODO: If keys can be statically known, we should provide a ts helper to
  39. // enforce it. I am fairly certain this will not work with generics as we'll
  40. // just end up blowing through the stack recursion, but it could be done on-demand.
  41. keys: (K | (string & {})) | (K | (string & {}))[]
  42. // T return type is wrong, but we cannot statically infer nested keys without
  43. // narrowing the type, which seems impossible for a generic implementation? Because
  44. // of this, allow users to type the return value and not
  45. ) {
  46. if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
  47. // It would have been more correct to throw and error, however
  48. // the lodash implementation we were using before did not do that
  49. // and we have a lot of code that relies on this behavior.
  50. return {};
  51. }
  52. let returnValue: T;
  53. try {
  54. returnValue = window.structuredClone(obj);
  55. } catch (e) {
  56. // structuredClone cannot clone functions. If this happens,
  57. // fallback to deep clone which will preseve the fn references
  58. returnValue = cloneDeep(obj);
  59. }
  60. if (typeof keys === 'string') {
  61. deepRemoveKey(returnValue, keys);
  62. return returnValue;
  63. }
  64. const normalizedKeys = Array.isArray(keys) ? keys : [keys];
  65. // @TODO: there is an optimization opportunity here. If we presort the keys,
  66. // then we can treat the traversal as a tree and avoid having to traverse the
  67. // entire object for each key. This would be a good idea if we expect to
  68. // omit many deep keys from an object.
  69. for (const key of normalizedKeys) {
  70. deepRemoveKey(returnValue, key);
  71. }
  72. return returnValue;
  73. }
  74. function deepRemoveKey(obj: Record<string, any>, key: string) {
  75. if (typeof key === 'string') {
  76. if (key in obj) {
  77. delete obj[key];
  78. }
  79. const components = key.split('.');
  80. const componentsSize = components.length;
  81. let componentIndex = 0;
  82. let v = obj;
  83. while (componentIndex < componentsSize - 1) {
  84. v = v[components[componentIndex]];
  85. if (v === undefined) {
  86. break;
  87. }
  88. componentIndex++;
  89. }
  90. // will only be defined if we traversed the entire path
  91. if (v !== undefined) {
  92. delete v[components[componentsSize - 1]];
  93. }
  94. }
  95. }
  96. export function valueIsEqual(value?: any, other?: any, deep?: boolean): boolean {
  97. if (value === other) {
  98. return true;
  99. }
  100. if (Array.isArray(value) || Array.isArray(other)) {
  101. if (arrayIsEqual(value, other, deep)) {
  102. return true;
  103. }
  104. } else if (isObject(value) || isObject(other)) {
  105. if (objectMatchesSubset(value, other, deep)) {
  106. return true;
  107. }
  108. }
  109. return false;
  110. }
  111. function objectMatchesSubset(obj?: object, other?: object, deep?: boolean): boolean {
  112. let k: string;
  113. if (obj === other) {
  114. return true;
  115. }
  116. if (!obj || !other) {
  117. return false;
  118. }
  119. if (deep !== true) {
  120. for (k in other) {
  121. if (obj[k] !== other[k]) {
  122. return false;
  123. }
  124. }
  125. return true;
  126. }
  127. for (k in other) {
  128. if (!valueIsEqual(obj[k], other[k], deep)) {
  129. return false;
  130. }
  131. }
  132. return true;
  133. }
  134. export function intcomma(x: number): string {
  135. return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  136. }
  137. export function lastOfArray<T extends Array<unknown> | ReadonlyArray<unknown>>(
  138. t: T
  139. ): T[number] {
  140. return t[t.length - 1];
  141. }
  142. export function sortArray<T>(arr: Array<T>, score_fn: (entry: T) => string): Array<T> {
  143. arr.sort((a, b) => {
  144. const a_score = score_fn(a),
  145. b_score = score_fn(b);
  146. for (let i = 0; i < a_score.length; i++) {
  147. if (a_score[i] > b_score[i]) {
  148. return 1;
  149. }
  150. if (a_score[i] < b_score[i]) {
  151. return -1;
  152. }
  153. }
  154. return 0;
  155. });
  156. return arr;
  157. }
  158. export function objectIsEmpty(obj = {}): boolean {
  159. for (const prop in obj) {
  160. if (obj.hasOwnProperty(prop)) {
  161. return false;
  162. }
  163. }
  164. return true;
  165. }
  166. export function trim(str: string): string {
  167. return str.replace(/^\s+|\s+$/g, '');
  168. }
  169. /**
  170. * Replaces slug special chars with a space
  171. */
  172. export function explodeSlug(slug: string): string {
  173. return trim(slug.replace(/[-_]+/g, ' '));
  174. }
  175. export function defined<T>(item: T): item is Exclude<T, null | undefined> {
  176. return item !== undefined && item !== null;
  177. }
  178. export function nl2br(str: string): string {
  179. return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
  180. }
  181. /**
  182. * This function has a critical security impact, make sure to check all usages before changing this function.
  183. * In some parts of our code we rely on that this only really is a string starting with http(s).
  184. */
  185. export function isUrl(str: any): boolean {
  186. return (
  187. typeof str === 'string' &&
  188. (str.indexOf('http://') === 0 || str.indexOf('https://') === 0)
  189. );
  190. }
  191. export function escape(str: string): string {
  192. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  193. }
  194. export function percent(value: number, totalValue: number): number {
  195. // prevent division by zero
  196. if (totalValue === 0) {
  197. return 0;
  198. }
  199. return (value / totalValue) * 100;
  200. }
  201. export function toTitleCase(str: string): string {
  202. return str.replace(
  203. /\w\S*/g,
  204. txt => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase()
  205. );
  206. }
  207. /**
  208. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  209. * means that:
  210. * - 1000 megabytes is equal to 1 gigabyte
  211. * - 1024 mebibytes is equal to 1 gibibytes
  212. *
  213. * We will use base 10 throughout billing for attachments. This function formats
  214. * quota/usage values for display.
  215. *
  216. * For storage/memory/file sizes, please take a look at formatBytesBase2
  217. */
  218. export function formatBytesBase10(bytes: number, u: number = 0) {
  219. const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  220. const threshold = 1000;
  221. while (bytes >= threshold) {
  222. bytes /= threshold;
  223. u += 1;
  224. }
  225. return formatNumberWithDynamicDecimalPoints(bytes) + ' ' + units[u];
  226. }
  227. /**
  228. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  229. * means that:
  230. * - 1000 megabytes is equal to 1 gigabyte
  231. * - 1024 mebibytes is equal to 1 gibibytes
  232. *
  233. * We will use base 2 to display storage/memory/file sizes as that is commonly
  234. * used by Windows or RAM or CPU cache sizes, and it is more familiar to the user
  235. *
  236. * For billing-related code around attachments. please take a look at
  237. * formatBytesBase10
  238. */
  239. export function formatBytesBase2(bytes: number, fixPoints: number | false = 1): string {
  240. const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  241. const thresh = 1024;
  242. if (bytes < thresh) {
  243. return (
  244. (fixPoints === false
  245. ? formatNumberWithDynamicDecimalPoints(bytes)
  246. : bytes.toFixed(fixPoints)) + ' B'
  247. );
  248. }
  249. let u = -1;
  250. do {
  251. bytes /= thresh;
  252. ++u;
  253. } while (bytes >= thresh);
  254. return (
  255. (fixPoints === false
  256. ? formatNumberWithDynamicDecimalPoints(bytes)
  257. : bytes.toFixed(fixPoints)) +
  258. ' ' +
  259. units[u]
  260. );
  261. }
  262. export function getShortCommitHash(hash: string): string {
  263. if (hash.match(/^[a-f0-9]{40}$/)) {
  264. hash = hash.substring(0, 7);
  265. }
  266. return hash;
  267. }
  268. export function parseRepo<T>(repo: T): T {
  269. if (typeof repo === 'string') {
  270. const re = /(?:github\.com|bitbucket\.org)\/([^\/]+\/[^\/]+)/i;
  271. const match = repo.match(re);
  272. const parsedRepo = match ? match[1] : repo;
  273. return parsedRepo as any;
  274. }
  275. return repo;
  276. }
  277. /**
  278. * Converts a multi-line textarea input value into an array,
  279. * eliminating empty lines
  280. */
  281. export function extractMultilineFields(value: string): string[] {
  282. return value
  283. .split('\n')
  284. .map(f => trim(f))
  285. .filter(f => f !== '');
  286. }
  287. /**
  288. * If the value is of type Array, converts it to type string, keeping the line breaks, if there is any
  289. */
  290. export function convertMultilineFieldValue<T extends string | string[]>(
  291. value: T
  292. ): string {
  293. if (Array.isArray(value)) {
  294. return value.join('\n');
  295. }
  296. if (typeof value === 'string') {
  297. return value.split('\n').join('\n');
  298. }
  299. return '';
  300. }
  301. function projectDisplayCompare(a: Project, b: Project): number {
  302. if (a.isBookmarked !== b.isBookmarked) {
  303. return a.isBookmarked ? -1 : 1;
  304. }
  305. return a.slug.localeCompare(b.slug);
  306. }
  307. // Sort a list of projects by bookmarkedness, then by id
  308. export function sortProjects(projects: Array<Project>): Array<Project> {
  309. return projects.sort(projectDisplayCompare);
  310. }
  311. // build actorIds
  312. export const buildUserId = (id: string) => `user:${id}`;
  313. export const buildTeamId = (id: string) => `team:${id}`;
  314. /**
  315. * Removes the organization / project scope prefix on feature names.
  316. */
  317. export function descopeFeatureName<T>(feature: T): T | string {
  318. if (typeof feature !== 'string') {
  319. return feature;
  320. }
  321. const results = feature.match(/(?:^(?:projects|organizations):)?(.*)/);
  322. if (results && results.length > 0) {
  323. return results.pop()!;
  324. }
  325. return feature;
  326. }
  327. export function isWebpackChunkLoadingError(error: Error): boolean {
  328. return (
  329. error &&
  330. typeof error.message === 'string' &&
  331. error.message.toLowerCase().includes('loading chunk')
  332. );
  333. }
  334. export function deepFreeze<T>(object: T) {
  335. // Retrieve the property names defined on object
  336. const propNames = Object.getOwnPropertyNames(object);
  337. // Freeze properties before freezing self
  338. for (const name of propNames) {
  339. const value = object[name];
  340. object[name] = value && typeof value === 'object' ? deepFreeze(value) : value;
  341. }
  342. return Object.freeze(object);
  343. }
  344. export function generateQueryWithTag(prevQuery: Query, tag: EventTag): Query {
  345. const query = {...prevQuery};
  346. // some tags are dedicated query strings since other parts of the app consumes this,
  347. // for example, the global selection header.
  348. switch (tag.key) {
  349. case 'environment':
  350. query.environment = tag.value;
  351. break;
  352. case 'project':
  353. query.project = tag.value;
  354. break;
  355. default:
  356. query.query = appendTagCondition(query.query, tag.key, tag.value);
  357. }
  358. return query;
  359. }
  360. export const isFunction = (value: any): value is Function => typeof value === 'function';
  361. // NOTE: only escapes a " if it's not already escaped
  362. export function escapeDoubleQuotes(str: string) {
  363. return str.replace(/\\([\s\S])|(")/g, '\\$1$2');
  364. }
  365. export function generateBaseControlSiloUrl() {
  366. return ConfigStore.get('links').sentryUrl || '';
  367. }
  368. export function generateOrgSlugUrl(orgSlug) {
  369. const sentryDomain = window.__initialData.links.sentryUrl.split('/')[2];
  370. return `${window.location.protocol}//${orgSlug}.${sentryDomain}${window.location.pathname}`;
  371. }