import { hasOwnProperty, isArray, isError, isFormData, isNullish, isNumber, isString } from '@posthog/core' import type { PostHogConfig, Properties } from '@posthog/types' import { logger } from './logger' export { trySafe } from '@posthog/core' export function find(value: T[], predicate: (value: T) => boolean): T | undefined { for (let i = 0; i < value.length; i++) { if (predicate(value[i]!)) { return value[i] } } return undefined } export function eachArray(obj: E[] | null | undefined, iterator: (value: E, key: number) => void): void { if (isArray(obj)) { obj.forEach(iterator) } } export function each(obj: any, iterator: (value: any, key: any) => void): void { if (isNullish(obj)) { return } if (isArray(obj)) { obj.forEach(iterator) return } if (isFormData(obj)) { obj.forEach((val: any, key: any) => iterator(val, key)) return } for (const key in obj) { if (hasOwnProperty.call(obj, key)) { iterator(obj[key], key) } } } export const extend = function (obj: Record, ...args: Record[]): Record { for (const source of args) { for (const prop in source) { if (source[prop] !== void 0) { obj[prop] = source[prop] } } } return obj } /** * Object.entries() polyfill * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries */ export function entries(obj: Record): [string, T][] { const ownProps = Object.keys(obj) let i = ownProps.length const resArray = new Array(i) // preallocate the Array while (i--) { resArray[i] = [ownProps[i]!, obj[ownProps[i]!] as T] } return resArray } export const safewrap = function any = (...args: any[]) => any>(f: F): F { return function (...args) { try { // oxlint-disable-next-line typescript/ban-ts-comment // @ts-ignore return f.apply(this, args) } catch (e) { logger.critical( 'Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A.' ) logger.critical(e) } } as F } // oxlint-disable-next-line typescript/no-unsafe-function-type export const safewrapClass = function (klass: Function, functions: string[]): void { for (let i = 0; i < functions.length; i++) { klass.prototype[functions[i]!] = safewrap(klass.prototype[functions[i]!]) } } export const stripEmptyProperties = function (p: Properties): Properties { const ret: Properties = {} each(p, function (v, k) { if ((isString(v) && v.length > 0) || isNumber(v)) { ret[k] = v } }) return ret } export function errorToProperties(error: Error & { cause?: unknown; errors?: unknown }): Record { const copy: Record = { ...error } for (const detail of ['name', 'message', 'stack', 'cause', 'errors'] as const) { try { if (detail in error) { copy[detail] = error[detail] } } catch { // An unreadable non-enumerable Error detail must not discard the rest of the event. } } return copy } /** * Deep copies an object. * It handles cycles by replacing all references to them with `undefined` * Also supports customizing native values * * @param value * @param customizer * @returns {{}|undefined|*} */ function deepCircularCopy = Record>( value: T, customizer?: (value: T[K], key?: K) => T[K] ): T | undefined { const COPY_IN_PROGRESS_SET = new Set() function internalDeepCircularCopy(value: T, key?: string): T | undefined { if (value !== Object(value)) return customizer ? customizer(value as any, key) : value // primitive value if (COPY_IN_PROGRESS_SET.has(value)) return undefined COPY_IN_PROGRESS_SET.add(value) let result: T if (isArray(value)) { result = [] as any as T eachArray(value, (it) => { result.push(internalDeepCircularCopy(it)) }) } else { const copy: Record = {} each(isError(value) ? errorToProperties(value) : value, (val, key) => { if (!COPY_IN_PROGRESS_SET.has(val)) { copy[key] = internalDeepCircularCopy(val, key) } }) result = copy as T } return result } return internalDeepCircularCopy(value) } export function _copyAndTruncateStrings = Record>( object: T, maxStringLength: number ): T { return deepCircularCopy(object, (value: any) => { if (isString(value)) { return (value as string).slice(0, maxStringLength) } return value }) as T } // NOTE: Update PostHogConfig docs if you change this list // We will not try to catch all bullets here, but we should make an effort to catch the most common ones // You should be highly against adding more to this list, because ultimately customers can configure // their `cross_subdomain_cookie` setting to anything they want. const EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE = ['herokuapp.com', 'vercel.app', 'netlify.app'] export function isCrossDomainCookie(documentLocation: Location | undefined) { const hostname = documentLocation?.hostname if (!isString(hostname)) { return false } // split and slice isn't a great way to match arbitrary domains, // but it's good enough for ensuring we only match herokuapp.com when it is the TLD // for the hostname const lastTwoParts = hostname.split('.').slice(-2).join('.') for (const excluded of EXCLUDED_FROM_CROSS_SUBDOMAIN_COOKIE) { if (lastTwoParts === excluded) { return false } } return true } // Use this instead of element.addEventListener to avoid lint errors // this properly implements the default options for passive event listeners export function addEventListener( element: Window | Document | Element | undefined, event: string, callback: EventListener, options?: AddEventListenerOptions ): void { const { capture = false, passive = true } = options ?? {} // This is the only place where we are allowed to call this function // because the whole idea is that we should be calling this instead of the built-in one // oxlint-disable-next-line posthog-js/no-add-event-listener element?.addEventListener(event, callback, { capture, passive }) } /** * Helper to migrate deprecated config fields to new field names with appropriate warnings * @param config - The config object to check * @param newField - The new field name to use * @param oldField - The deprecated field name to check for * @param defaultValue - The default value if neither field is set * @param loggerInstance - Optional logger instance for deprecation warnings * @returns The value to use (new field takes precedence over old field) */ export function migrateConfigField( config: Record, newField: string, oldField: string, defaultValue: T, loggerInstance?: { warn: (message: string) => void } ): T { const hasNewField = newField in config && !isNullish(config[newField]) const hasOldField = oldField in config && !isNullish(config[oldField]) if (hasNewField) { return config[newField] } if (hasOldField) { if (loggerInstance) { loggerInstance.warn( `Config field '${oldField}' is deprecated. Please use '${newField}' instead. ` + `The old field will be removed in a future major version.` ) } return config[oldField] } return defaultValue } const TOOLBAR_INTERNAL_INSTANCE_NAME = 'ph_toolbar_internal' export function isToolbarInstance(config: Pick): boolean { return config.name === TOOLBAR_INTERNAL_INSTANCE_NAME }