o11y 2.1.2 → 236.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"collectors.js","sources":["../../../../../../node_modules/o11y_schema/sf_instrumentation/activity.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/core_envelope.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/error.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/instrumented_event.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/simple.js","../../../../../../node_modules/o11y_schema/version/version.js","../../../../src/collectors/core-collector/CoreEnvelopeBuilder.ts","../../../../src/collectors/protobuf-util.ts","../../../../src/library/PublicSafety.ts","../../../../src/library/Tracing.ts","../../../../src/library/ActivityImpl.ts","../../../../src/library/ActivityNoOp.ts","../../../../src/library/DomEventHelpers.ts","../../../../src/library/LogValidator.ts","../../../../src/library/UpCounterImpl.ts","../../../../src/library/ValueRecorderImpl.ts","../../../../src/library/SizeLimitedMap.ts","../../../../src/library/MetricsImpl.ts","../../../../src/library/MockEvent.ts","../../../../src/library/InstrumentationImpl.ts","../../../../src/library/RootActivityImpl.ts","../../../../src/library/RootActivityNoOp.ts","../../../../src/library/AppInstrumentationImpl.ts","../../../../src/library/AutomaticClickTracker.ts","../../../../src/library/NextgenImpl.ts","../../../../src/index.ts","../../../../src/collectors/core-collector/CoreCollector.ts","../../../../src/collectors/hybrid-collector/HybridCollector.ts"],"sourcesContent":["export const activity={namespace:\"sf.instrumentation\",name:\"Activity\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Activity\":{\"reserved\":[[5,5],[7,7]],\"fields\":{\"duration\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"stopReason\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"isRoot\":{\"options\":{},\"id\":8,\"type\":\"bool\"},\"name\":{\"options\":{\"(meta.max_length)\":25},\"id\":2,\"type\":\"string\"},\"isSampled\":{\"options\":{},\"id\":11,\"type\":\"bool\"},\"preRootId\":{\"options\":{},\"id\":9,\"type\":\"string\"},\"id\":{\"options\":{},\n\"id\":1,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":4,\"type\":\"Payload\"},\"errorCount\":{\"options\":{},\"id\":10,\"type\":\"uint32\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const core_envelope={namespace:\"sf.instrumentation\",name:\"CoreEnvelope\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"MessageBundle\":{\"fields\":{\"messages\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"LogMessage\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"Metrics\":{\"fields\":{\"valueRecorders\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"ValueRecorder\"},\"upCounters\":{\"options\":{},\"rule\":\"repeated\",\"id\":1,\"type\":\"UpCounter\"}}},\"CoreEnvelopeDiagnostics\":{\"fields\":{\"schemaVersion\":{\"options\":{},\n\"id\":6,\"type\":\"string\"},\"generatedTimestamp\":{\"options\":{},\"id\":2,\"type\":\"double\"},\"bundleCount\":{\"options\":{},\"id\":3,\"type\":\"uint32\"},\"upCounterCount\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"valueRecorderCount\":{\"options\":{},\"id\":5,\"type\":\"uint32\"},\"key\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"LogMessage\":{\"fields\":{\"appPayload\":{\"options\":{},\"id\":10,\"type\":\"Payload\"},\"data\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"rootId\":{\"options\":{},\"id\":4,\"type\":\"string\"},\"pagePayload\":{\"options\":{},\"id\":7,\"type\":\"Payload\"},\n\"loggerAppName\":{\"options\":{},\"id\":8,\"type\":\"string\"},\"loggerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"connectionType\":{\"options\":{},\"id\":9,\"type\":\"string\"},\"age\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"seq\":{\"options\":{},\"id\":5,\"type\":\"uint32\"},\"timestamp\":{\"options\":{},\"id\":1,\"type\":\"double\"}}},\"CoreEnvelope\":{\"options\":{\"(meta.msg.desc)\":\"This message is used to contain data that the Core ui-telemetry Connect API endpoint accepts.\"},\"fields\":{\"diagnostics\":{\"options\":{},\"id\":1,\"type\":\"CoreEnvelopeDiagnostics\"},\n\"bundles\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"MessageBundle\"},\"metrics\":{\"options\":{},\"id\":3,\"type\":\"Metrics\"},\"staticAttributes\":{\"options\":{},\"id\":4,\"type\":\"StaticAttributes\"}}},\"MetricTag\":{\"fields\":{\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"value\":{\"options\":{},\"id\":2,\"type\":\"string\"}}},\"ValueRecorder\":{\"fields\":{\"lastUpdatedTimestamp\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"ownerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"ownerAppName\":{\"options\":{},\"id\":7,\"type\":\"string\"},\"createdTimestamp\":{\"options\":{},\n\"id\":2,\"type\":\"double\"},\"values\":{\"options\":{},\"rule\":\"repeated\",\"id\":4,\"type\":\"double\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"tags\":{\"options\":{},\"rule\":\"repeated\",\"id\":5,\"type\":\"MetricTag\"}}},\"StaticAttributes\":{\"fields\":{\"appVersion\":{\"options\":{},\"id\":2,\"type\":\"string\"},\"appName\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"deviceModel\":{\"options\":{},\"id\":5,\"type\":\"string\"},\"sdkVersion\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"deviceId\":{\"options\":{},\"id\":4,\"type\":\"string\"},\"appExperience\":{\"options\":{},\n\"id\":3,\"type\":\"string\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"UpCounter\":{\"fields\":{\"lastUpdatedTimestamp\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"ownerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"ownerAppName\":{\"options\":{},\"id\":7,\"type\":\"string\"},\"createdTimestamp\":{\"options\":{},\"id\":2,\"type\":\"double\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"value\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"tags\":{\"options\":{},\n\"rule\":\"repeated\",\"id\":5,\"type\":\"MetricTag\"}}}}}}}}}};","export const error={namespace:\"sf.instrumentation\",name:\"Error\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Error\":{\"reserved\":[[5,5],[7,7]],\"fields\":{\"activityId\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"stack\":{\"options\":{},\"id\":3,\"type\":\"string\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"message\":{\"options\":{\"(meta.max_length)\":200},\"id\":2,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":4,\"type\":\"Payload\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\n\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const instrumented_event={namespace:\"sf.instrumentation\",name:\"InstrumentedEvent\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"MouseEvent\":{\"fields\":{\"cancelable\":{\"options\":{},\"id\":5,\"type\":\"bool\"},\"ctrlKey\":{\"options\":{},\"id\":9,\"type\":\"bool\"},\"type\":{\"options\":{},\"id\":25,\"type\":\"string\"},\"button\":{\"options\":{},\"id\":3,\"type\":\"uint32\"},\"offsetX\":{\"options\":{},\"id\":17,\"type\":\"uint32\"},\"eventPhase\":{\"options\":{},\"id\":12,\"type\":\"uint32\"},\"shiftKey\":{\"options\":{},\"id\":23,\n\"type\":\"bool\"},\"offsetY\":{\"options\":{},\"id\":18,\"type\":\"uint32\"},\"composed\":{\"options\":{},\"id\":8,\"type\":\"bool\"},\"altKey\":{\"options\":{},\"id\":1,\"type\":\"bool\"},\"isTrusted\":{\"options\":{},\"id\":13,\"type\":\"bool\"},\"buttons\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"movementY\":{\"options\":{},\"id\":16,\"type\":\"uint32\"},\"clientY\":{\"options\":{},\"id\":7,\"type\":\"uint32\"},\"clientX\":{\"options\":{},\"id\":6,\"type\":\"uint32\"},\"movementX\":{\"options\":{},\"id\":15,\"type\":\"uint32\"},\"defaultPrevented\":{\"options\":{},\"id\":10,\"type\":\"bool\"},\n\"metaKey\":{\"options\":{},\"id\":14,\"type\":\"bool\"},\"timeStamp\":{\"options\":{},\"id\":24,\"type\":\"double\"},\"bubbles\":{\"options\":{},\"id\":2,\"type\":\"bool\"},\"detail\":{\"options\":{},\"id\":11,\"type\":\"int64\"},\"pageY\":{\"options\":{},\"id\":20,\"type\":\"uint32\"},\"pageX\":{\"options\":{},\"id\":19,\"type\":\"uint32\"},\"screenX\":{\"options\":{},\"id\":21,\"type\":\"uint32\"},\"screenY\":{\"options\":{},\"id\":22,\"type\":\"uint32\"}}},\"InstrumentedEvent\":{\"oneofs\":{\"event\":{\"oneof\":[\"mouseEvent\"]}},\"reserved\":[[4,4],\"xpath\",[6,6],[8,8]],\"fields\":{\"mouseEvent\":{\"options\":{},\n\"id\":7,\"type\":\"MouseEvent\"},\"auto\":{\"options\":{},\"id\":3,\"type\":\"bool\"},\"parentComponent\":{\"options\":{},\"id\":2,\"type\":\"string\"},\"ownerComponent\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":5,\"type\":\"Payload\"},\"simplePath\":{\"options\":{},\"id\":9,\"type\":\"string\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const simple={namespace:\"sf.instrumentation\",name:\"Simple\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Simple\":{\"options\":{\"(meta.msg.desc)\":\"This message is used internally to allow convenient logging of simple text via the API without requiring a schema.\"},\"fields\":{\"text\":{\"options\":{\"(meta.max_length)\":25},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const version='2.6.0'","import { Metric } from '../../interfaces';\nimport { MetricsTags, utility } from 'o11y/shared';\nimport { CoreEnvelope } from './CoreEnvelope';\nimport { LogMessage } from './LogMessage';\nimport { MessageBundle } from './MessageBundle';\nimport { StaticAttributes } from './StaticAttributes';\nimport { UpCounter } from '../metrics/UpCounter';\nimport { ValueRecorder } from '../metrics/ValueRecorder';\nimport { version as schemaVersion } from 'o11y_schema/version';\nimport { MetricTag } from '../metrics/MetricTag';\n\nexport const coreEnvelopeKey = 'o11y';\nexport class CoreEnvelopeBuilder {\n private _envelope: CoreEnvelope;\n\n constructor() {\n this._envelope = {\n diagnostics: {\n key: coreEnvelopeKey,\n generatedTimestamp: undefined,\n bundleCount: 0,\n upCounterCount: 0,\n valueRecorderCount: 0,\n schemaVersion\n },\n bundles: [] as MessageBundle[],\n metrics: {\n upCounters: [] as UpCounter[],\n valueRecorders: [] as ValueRecorder[]\n },\n staticAttributes: {}\n };\n }\n\n withStaticAttributes(staticAttributes: StaticAttributes): CoreEnvelopeBuilder {\n this._envelope.staticAttributes = staticAttributes;\n return this;\n }\n\n withLogs(schemaName: string, logs: LogMessage[]): CoreEnvelopeBuilder {\n let msgBundle: MessageBundle = this._envelope.bundles.find(\n (bundle) => bundle.schemaName === schemaName\n );\n\n if (msgBundle) {\n for (const log of logs) {\n msgBundle.messages.push(log);\n }\n } else {\n msgBundle = {\n schemaName: schemaName,\n messages: logs\n };\n this._envelope.bundles.push(msgBundle);\n }\n this._envelope.diagnostics.bundleCount = this._envelope.bundles.length;\n return this;\n }\n\n private _getMetricTags<T>(metric: Metric<T>): MetricTag[] {\n const tags: MetricsTags = metric.getTags();\n if (tags) {\n return Object.entries(tags).map((entry) => {\n const mt: MetricTag = {\n name: entry[0],\n value: entry[1].toString()\n };\n return mt;\n });\n }\n return undefined;\n }\n\n withUpCounters(metrics: Metric<number>[]): CoreEnvelopeBuilder {\n for (const metric of metrics) {\n const data: UpCounter = {\n name: metric.getName(),\n createdTimestamp: metric.getCreatedOn(),\n lastUpdatedTimestamp: metric.getLastUpdatedOn(),\n value: metric.getData(),\n ownerName: metric.getOwnerName(),\n ownerAppName: metric.getOwnerAppName(),\n tags: this._getMetricTags(metric)\n };\n this._envelope.metrics.upCounters.push(data);\n metric.reset();\n }\n this._envelope.diagnostics.upCounterCount = this._envelope.metrics.upCounters.length;\n return this;\n }\n\n withValueRecorders(metrics: Metric<number[]>[]): CoreEnvelopeBuilder {\n for (const metric of metrics) {\n const data: ValueRecorder = {\n name: metric.getName(),\n createdTimestamp: metric.getCreatedOn(),\n lastUpdatedTimestamp: metric.getLastUpdatedOn(),\n values: metric.getData(),\n ownerName: metric.getOwnerName(),\n ownerAppName: metric.getOwnerAppName(),\n tags: this._getMetricTags(metric)\n };\n this._envelope.metrics.valueRecorders.push(data);\n metric.reset();\n }\n this._envelope.diagnostics.valueRecorderCount =\n this._envelope.metrics.valueRecorders.length;\n return this;\n }\n\n build(): CoreEnvelope {\n this._envelope.diagnostics.generatedTimestamp = utility.time().tsNow;\n return this._envelope;\n }\n}\n","import { Message, Root, Type } from 'protobufjs';\n\nimport { LogMeta, Schema, SchematizedPayload } from '../interfaces';\nimport { EncodedSchematizedPayload } from './EncodedSchematizedPayload';\nimport { SchematizedData, schemaUtil, utility } from 'o11y/shared';\nimport { LogMessage } from './core-collector/LogMessage';\n\nclass ProtobufUtil {\n private readonly _typeStore = new Map<string, Type>();\n\n public getSchemaType(schema: Schema): Type {\n utility.requireArgument(schema, 'schema');\n const schemaPath = schemaUtil.getSchemaId(schema);\n let type = this._typeStore.get(schemaPath);\n\n if (!type) {\n // Lazy add to the type store\n const schemaInstance = Root.fromJSON(schema.pbjsSchema);\n // this will throw if it can't find it\n type = schemaInstance.lookupType(schemaPath);\n this._typeStore.set(schemaPath, type);\n }\n\n return type;\n }\n\n public validate(schema: Schema, data: SchematizedData): Type {\n utility.requireArgument(schema, 'schema');\n utility.requireArgument(data, 'data');\n const type: Type = this.getSchemaType(schema);\n\n const errorText = type.verify(data);\n if (errorText) {\n throw new Error(`Data is invalid for ${type.fullName}: ${errorText}`);\n }\n return type;\n }\n\n public encode(schema: Schema, data: SchematizedData): Uint8Array {\n const type: Type = this.validate(schema, data);\n const message: Message = type.fromObject(data);\n const encoded: Uint8Array = type.encode(message).finish();\n return encoded;\n }\n\n public encodePayload(rawPayload: SchematizedPayload): EncodedSchematizedPayload {\n if (rawPayload && rawPayload.schema && rawPayload.payload) {\n return {\n schemaName: schemaUtil.getSchemaId(rawPayload.schema),\n payload: this.encode(rawPayload.schema, rawPayload.payload)\n };\n }\n return undefined;\n }\n\n // This method generates a LogMessage (used in the CoreEnvelope) from the provided arguments.\n public getLogMessage(schema: Schema, data: SchematizedData, logMeta: LogMeta): LogMessage {\n return {\n timestamp: logMeta.timestamp,\n data: this.encode(schema, data),\n age: utility.getAge(logMeta.timestamp),\n rootId: logMeta.rootId,\n seq: logMeta.sequence,\n loggerName: logMeta.loggerName,\n pagePayload: this.encodePayload(logMeta.pagePayload),\n loggerAppName: logMeta.loggerAppName,\n connectionType: logMeta.connectionType,\n appPayload: this.encodePayload(logMeta.appPayload)\n };\n }\n}\n\nexport const protobufUtil = new ProtobufUtil();\n","import { UpCounter } from '../interfaces';\nimport { utility } from 'o11y/shared';\n\nexport class PublicSafety {\n private _safeCatchMode = false;\n\n constructor(private readonly _errorCounter?: UpCounter) {}\n\n /**\n * Instrumentation should never throw in production. Therefore, we need to include in\n * all our public methods a top-most try/catch wrapper. Simply use this function\n * as your first and only top-level call in the function block and sleep well at night.\n *\n * @param fn The body of the unsafe function that doesn't return a value but can throw\n */\n tryCatch(fn: () => void): void {\n try {\n fn();\n } catch (err) {\n this._prodSafeCatch(err);\n }\n }\n\n /**\n *\n * @param fn The body of the unsafe function that returns a value and that can throw\n * @param noopValue A static, noop instance of V (like a mock) that will be returned in case\n * the function could not be called.\n */\n tryCatchReturn<V>(fn: () => V, noopValue: V): V {\n try {\n utility.requireArgument(noopValue, 'noopValue');\n return fn();\n } catch (err) {\n this._prodSafeCatch(err);\n return noopValue;\n }\n }\n\n /**\n * Safely handles exceptions. Suppresses throws in a production environment.\n * This method is intended to be called inside a catch block.\n *\n * @param error The error that was caught\n */\n private _prodSafeCatch(error: unknown): void {\n let allowThrow;\n try {\n allowThrow = !utility.isProduction;\n if (allowThrow) {\n // Just throw the error in development\n throw error;\n }\n\n if (this._safeCatchMode) {\n // If we're here, that means code in the try block of prodSafeCatch itself is throwing an error\n // (i.e. prodSafeCatch is already on the stack). Break out now to prevent infinite loop.\n this._safeCatchMode = false;\n\n throw new Error('Internal error in prodSafeCatch.');\n }\n\n this._safeCatchMode = true;\n if (this._errorCounter) {\n this._errorCounter.increment();\n }\n\n if (!(error instanceof Error)) {\n const errorText =\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n (error && (error as any).message) ||\n (typeof error.toString === 'function' ? error.toString() : '');\n error = new Error(errorText);\n }\n\n // If not allowed to throw the error, at least try to log it\n // TODO: This error should be attributed to the global Instrumentation (not to \"this\")\n // this.error(error);\n this._safeCatchMode = false;\n } catch (internalError) {\n // Do not call any methods in this catch block except for console.error\n\n if (allowThrow) {\n // pass it along\n throw internalError;\n }\n\n // eslint-disable-next-line no-console\n if (internalError && console && typeof console.error === 'function') {\n try {\n // eslint-disable-next-line no-console\n console.error(internalError);\n } catch {\n // Nothing we can do at this point\n }\n }\n this._safeCatchMode = false;\n }\n }\n}\n","import {\n Instrumentation,\n TracingHeadersOptions,\n NetworkInstrumentationOptions,\n Activity\n} from '../interfaces';\nimport { utility } from 'o11y/shared';\n\ntype FetchType = (input: RequestInfo, init?: RequestInit) => Promise<Response>;\ntype XhrType = {\n prototype: XMLHttpRequest;\n new (): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\ntype XhrSendType = (body?: Document | BodyInit | null) => void;\ninterface O11yXhr extends XMLHttpRequest {\n _o11yActivity: Activity;\n}\n\nconst defaultTraceIdLengthW3 = 32; // 32 Characters = 128 bits\nconst defaultTraceIdLengthB3 = 16; // 16 Characters = 64 bits\nconst defaultSpanIdLength = 16; // 16 Characters = 64 bits\n\n// Headers for W3 tracing (https://www.w3.org/TR/trace-context/#traceparent-header)\nconst headerTraceParent = 'traceparent';\n\n// Headers for B3 tracing (https://github.com/openzipkin/b3-propagation)\nconst headerB3 = 'b3';\nconst headerTraceId = 'X-B3-TraceId';\nconst headerSpanId = 'X-B3-SpanId';\nconst headerSampled = 'X-B3-Sampled';\nconst headerParentSpanId = 'X-B3-ParentSpanId';\n\nconst defaultActivityNameForFetch = 'fetch';\nconst defaultActivityNameForXhrSend = 'xhr_send';\n\nexport class Tracing {\n private static _global = utility.getGlobal();\n private static _originalFetch: FetchType;\n private static _originalXhr: XhrType;\n private static _originalXhrSend: XhrSendType;\n private static _isNetworkInstrumentationEnabled = false;\n\n constructor(private readonly instr: Instrumentation) {\n utility.requireArgument(instr, 'instr', 'object');\n }\n\n private static _getB3CompactFormat(\n traceId: string,\n spanId: string,\n isSampled?: boolean,\n parentSpanId?: string\n ): string {\n // b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}\n // Note: last two fields are optional\n\n let b3 = `${traceId}-${spanId}`;\n\n if (isSampled !== undefined || parentSpanId !== undefined) {\n b3 += isSampled ? '-1' : '-0';\n if (parentSpanId !== undefined) {\n b3 += `-${parentSpanId}`;\n }\n }\n return b3;\n }\n\n private static _getW3CompactFormat(\n traceId: string,\n spanId: string,\n isSampled: boolean\n ): string {\n // traceparent={version}-{trace-id}-{parent-id}-{trace-flags}\n // \"in some tracing systems, parent-id is known as the span-id, where a span is the execution of a client request\"\n return `00-${traceId}-${spanId}-${isSampled ? '01' : '00'}`;\n }\n\n private static _conformTextAsId(text: string, numChars: number): string {\n // First validate\n text = text.toLowerCase();\n const len: number = text.length;\n for (let i = 0; i < len; i += 1) {\n const c = text[i];\n if (!(c >= 'a' && c <= 'f') && !(c >= '0' && c <= '9')) {\n throw new Error(`The text '${text}' has an invalid character at index #${i}`);\n }\n }\n\n if (len > numChars) {\n // Use the right-most characters per spec\n return text.substr(len - numChars);\n }\n if (len < numChars) {\n // Pad left with 0s per spec\n return text.padStart(numChars, '0');\n }\n return text;\n }\n\n public static getHeaders(\n traceId: string,\n spanId: string,\n isSampled?: boolean,\n options?: TracingHeadersOptions\n ): Record<string, string> {\n utility.requireArgument(traceId, 'traceId', 'string');\n utility.requireArgument(spanId, 'spanId', 'string');\n\n const useB3Headers: boolean = options && options.useB3Headers;\n\n traceId = this._conformTextAsId(\n traceId,\n options && options.traceIdEffectiveLength !== undefined\n ? options.traceIdEffectiveLength\n : useB3Headers\n ? defaultTraceIdLengthB3\n : defaultTraceIdLengthW3\n );\n spanId = this._conformTextAsId(spanId, defaultSpanIdLength);\n\n const parentSpanId =\n (options &&\n options.parentSpanId !== undefined &&\n this._conformTextAsId(options.parentSpanId, defaultSpanIdLength)) ||\n undefined;\n\n const headers: Record<string, string> = {};\n\n if (useB3Headers) {\n // By default, use non-compact\n const isCompact: boolean = options && options.useCompactHeader;\n if (isCompact) {\n headers[headerB3] = this._getB3CompactFormat(\n traceId,\n spanId,\n isSampled,\n parentSpanId\n );\n } else {\n headers[headerTraceId] = traceId;\n headers[headerSpanId] = spanId;\n if (parentSpanId !== undefined) {\n headers[headerParentSpanId] = parentSpanId;\n }\n if (isSampled !== undefined) {\n headers[headerSampled] = isSampled ? '1' : '0';\n }\n }\n } else {\n headers[headerTraceParent] = this._getW3CompactFormat(traceId, spanId, isSampled);\n }\n\n return headers;\n }\n\n private _disableNetworkInstrumentation(): void {\n if (Tracing._isNetworkInstrumentationEnabled) {\n if (Tracing._originalFetch) {\n Tracing._global.fetch = Tracing._originalFetch;\n Tracing._originalFetch = undefined;\n }\n if (Tracing._originalXhr) {\n Tracing._global.XMLHttpRequest = Tracing._originalXhr;\n Tracing._originalXhr = undefined;\n }\n if (Tracing._originalXhrSend) {\n Tracing._global.XMLHttpRequest.prototype.send = Tracing._originalXhrSend;\n Tracing._originalXhrSend = undefined;\n }\n Tracing._isNetworkInstrumentationEnabled = false;\n }\n }\n\n private _enableNetworkInstrumentation(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n if (typeof Tracing._global.fetch === 'function') {\n this._overrideFetch(instr, logErrors, activityName, useTracing, options);\n Tracing._isNetworkInstrumentationEnabled = true;\n }\n\n if (typeof Tracing._global.XMLHttpRequest === 'function') {\n this._overrideXhr(instr, logErrors, activityName, useTracing, options);\n Tracing._isNetworkInstrumentationEnabled = true;\n }\n }\n\n private _overrideFetch(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n Tracing._originalFetch = Tracing._global.fetch;\n const o11yFetch: FetchType = async (url, reqOptions, ...restArgs) => {\n let activity: Activity;\n try {\n activity = instr.startActivity(activityName || defaultActivityNameForFetch);\n\n if (useTracing) {\n reqOptions = reqOptions || {};\n const traceHeaders = activity.getTraceHeaders(options);\n reqOptions.headers = Object.assign(reqOptions.headers || {}, traceHeaders);\n }\n return await Tracing._originalFetch.call(\n Tracing._global,\n url,\n reqOptions,\n ...restArgs\n );\n } catch (ex) {\n if (logErrors) {\n if (activity) {\n activity.error(ex);\n } else {\n instr.error(ex);\n }\n }\n throw ex;\n } finally {\n if (activity) {\n activity.stop();\n }\n }\n };\n Tracing._global.fetch = o11yFetch;\n }\n\n private _overrideXhr(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n Tracing._originalXhr = Tracing._global.XMLHttpRequest;\n Tracing._originalXhrSend = Tracing._originalXhr.prototype.send;\n\n Tracing._originalXhr.prototype.send = function (this: O11yXhr, ...args) {\n let activity: Activity;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr: O11yXhr = this;\n try {\n xhr._o11yActivity = activity = instr.startActivity(\n activityName || defaultActivityNameForXhrSend\n );\n if (useTracing) {\n const headers = activity.getTraceHeaders(options);\n\n Object.entries(headers).forEach((entry) => {\n xhr.setRequestHeader(entry[0], entry[1]);\n });\n }\n Tracing._originalXhrSend.call(this, ...args);\n } catch (ex) {\n if (logErrors) {\n if (activity) {\n activity.error(ex);\n } else {\n instr.error(ex);\n }\n }\n if (activity) {\n activity.stop();\n }\n throw ex;\n }\n };\n\n const xhrProxy = new Proxy<XhrType>(Tracing._originalXhr, {\n construct(target: XhrType) {\n const newXhr = new target() as O11yXhr;\n\n // Be the first in the event chain\n newXhr.addEventListener('load', () => {\n const activity = newXhr._o11yActivity;\n if (activity) {\n activity.stop();\n }\n });\n newXhr.addEventListener(\n 'error',\n (__err: ProgressEvent<XMLHttpRequestEventTarget>) => {\n const error = new Error('XHR Network-Level Error');\n const activity = newXhr._o11yActivity;\n if (activity) {\n if (logErrors) {\n activity.error(error);\n }\n activity.stop();\n } else if (logErrors) {\n instr.error(error);\n }\n }\n );\n newXhr.addEventListener('abort', () => {\n const activity = newXhr._o11yActivity;\n if (activity) {\n activity.discard();\n }\n });\n return newXhr;\n }\n });\n\n Tracing._global.XMLHttpRequest = xhrProxy;\n }\n\n networkInstrumentation(options: boolean | NetworkInstrumentationOptions): void {\n utility.requireArgument(options, 'options', ['boolean', 'object']);\n\n if (options) {\n // First disable it if necessary, so we can use the new options if it was already enabled\n this._disableNetworkInstrumentation();\n\n const tracingOptions: NetworkInstrumentationOptions =\n typeof options === 'object' ? options : {};\n\n this._enableNetworkInstrumentation(\n utility.definedValueOrDefault(tracingOptions.instrumentation, this.instr),\n utility.definedValueOrDefault(tracingOptions.logErrors, true),\n tracingOptions.activityName,\n utility.definedValueOrDefault(tracingOptions.useTracing, true),\n tracingOptions.tracingHeadersOptions\n );\n } else {\n // Options is falsy, disable.\n this._disableNetworkInstrumentation();\n }\n }\n}\n","import { Activity, ActivityDetail, Schema, TracingHeadersOptions } from '../interfaces';\nimport { PublicSafety } from './PublicSafety';\nimport { Tracing } from './Tracing';\nimport { SchematizedData, utility } from 'o11y/shared';\n\nexport const timedout = 'timedout';\nexport const terminated = 'terminated';\nexport const discarded = 'discarded';\n\nconst stopReason = {\n timedout,\n terminated,\n discarded\n};\n\nexport type onActivityStop = (detail: ActivityDetail) => void;\nexport type onActivityError = (error: Error, detail: ActivityDetail) => void;\n\nexport class ActivityImpl implements Activity {\n protected readonly _id: string;\n private readonly _startTimestamp: number;\n private readonly _startPerfTime: number;\n private readonly _safety: PublicSafety;\n private readonly _usePerf: boolean;\n protected static _count = 0;\n private readonly _perfId: string;\n private readonly _perfName: string;\n private _stopPerfTime: number;\n private _stopReason: string;\n private _timer: NodeJS.Timer;\n private _errorCount = 0;\n\n constructor(\n protected readonly _name: string,\n protected readonly _rootId: string,\n private readonly _onStopped: onActivityStop,\n private readonly _onError: onActivityError,\n timeout?: number,\n id?: string,\n protected readonly _isSampled?: boolean\n ) {\n const { tsNow, perfNow } = utility.time();\n\n ActivityImpl._count += 1;\n this._id = id || utility.generateUniqueId();\n\n this._usePerf =\n typeof performance !== 'undefined' &&\n typeof performance.mark === 'function' &&\n typeof performance.measure === 'function';\n if (this._usePerf) {\n this._perfName = `${this._name}__${ActivityImpl._count}`;\n this._perfId = `${this._name}__${this.id}`;\n try {\n performance.mark(this._perfId);\n } catch {\n this._usePerf = false;\n }\n }\n\n this._startTimestamp = tsNow;\n this._startPerfTime = perfNow;\n\n if (timeout > 0) {\n this._timer = setTimeout(() => {\n this._stopReason = this._stopReason || stopReason.timedout;\n this.stop();\n }, timeout);\n }\n this._safety = new PublicSafety();\n }\n\n get id(): string {\n return this._id;\n }\n\n getId(): string {\n return this.id;\n }\n\n getRootId(): string {\n return this._rootId;\n }\n\n get stopReason(): string {\n return this._stopReason;\n }\n\n error(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData\n ): void {\n this._safety.tryCatch(() => {\n this._errorCount += 1;\n if (typeof error === 'string') {\n error = new Error(error);\n }\n this._onError(error, this._getDetail(userSchemaOrText, userData));\n });\n }\n\n stop(userSchemaOrText?: Schema | string, userData?: SchematizedData): void {\n this._safety.tryCatch(() => this._stopInternal(userSchemaOrText, userData));\n }\n\n private _stopInternal(userSchemaOrText: Schema | string, userData: SchematizedData): void {\n // First things first.\n const stopPerfTime = utility.perfNow();\n if (this._usePerf) {\n try {\n // Use a more user-friendly name for measure.\n performance.measure(this._perfName, this._perfId);\n performance.clearMarks(this._perfId);\n performance.clearMeasures(this._perfName);\n } catch {}\n }\n\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n if (this.isStopped) {\n // Already stopped\n return;\n }\n this._stopPerfTime = stopPerfTime;\n\n const activityDetail: ActivityDetail = this._getDetail(userSchemaOrText, userData);\n this._onStopped(activityDetail);\n }\n\n get isStopped(): boolean {\n return this._stopPerfTime !== undefined;\n }\n\n discard(): void {\n this._safety.tryCatch(() => {\n this._stopReason = this._stopReason || stopReason.discarded;\n this.stop();\n });\n }\n\n terminate(): void {\n this._safety.tryCatch(() => {\n this._stopReason = this._stopReason || stopReason.terminated;\n this.stop();\n });\n }\n\n getIsSampled(): boolean {\n return this._isSampled || false;\n }\n\n protected _getDetail(\n userSchemaOrText: Schema | string,\n userData: SchematizedData\n ): ActivityDetail {\n return {\n id: this._id,\n rootId: this._rootId,\n name: this._name,\n userSchemaOrText: userSchemaOrText,\n userData,\n stopReason: this._stopReason,\n startTimestamp: this._startTimestamp,\n startPerfTime: this._startPerfTime,\n stopPerfTime: this._stopPerfTime,\n errorCount: this._errorCount,\n isSampled: this.getIsSampled()\n };\n }\n\n public getTraceHeaders(options: TracingHeadersOptions): Record<string, string> {\n // Normally, the root activity ID is the traceId.\n // If the activity is root, it's ID is (also) the traceId.\n // If the activity has no root, it's ID is (also) the traceId. i.e. It creates its own trace.\n const spanId = this.id;\n const traceId = this._rootId || spanId;\n\n return Tracing.getHeaders(traceId, spanId, this.getIsSampled(), options);\n }\n\n getStartTimestamp(): number {\n return this._startTimestamp;\n }\n\n getStartPerfTime(): number {\n return this._startPerfTime;\n }\n\n getStopPerfTime(): number {\n return this._stopPerfTime;\n }\n}\n","import { Activity, TracingHeadersOptions } from '../interfaces';\n\nconst id: string = new Array(16).fill(0).join('');\nclass ActivityNoOp implements Activity {\n getId(): string {\n return id;\n }\n getRootId(): string {\n return undefined;\n }\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n error(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n stop(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n discard(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n terminate(): void {}\n\n getIsSampled(): boolean {\n return false;\n }\n getTraceHeaders(__options: TracingHeadersOptions): Record<string, string> {\n return {};\n }\n getStartTimestamp(): number {\n return undefined;\n }\n getStartPerfTime(): number {\n return undefined;\n }\n getStopPerfTime(): number {\n return undefined;\n }\n}\n\nexport const activityNoOp = Object.freeze(new ActivityNoOp());\n","import { SchematizedPayload } from '../interfaces';\nimport { InstrumentedEventData, MouseEventData } from '../interfaces-private';\nimport { DomEventData } from '../types/TypeDefinitions-Private';\nimport { schemaUtil, utility } from 'o11y/shared';\n\nexport class DomEventHelpers {\n getInstrumentedEventData(\n eventData: DomEventData,\n handledBy: HTMLElement,\n userPayload: SchematizedPayload\n ): InstrumentedEventData {\n const instrumentedEvent: InstrumentedEventData = {\n ownerComponent: handledBy.tagName,\n parentComponent:\n (handledBy.parentElement && handledBy.parentElement.tagName) || undefined,\n event: eventData,\n simplePath: utility.getXpath(handledBy)\n };\n\n if (userPayload) {\n instrumentedEvent.userPayload = schemaUtil.makePayload(\n userPayload.schema,\n userPayload.payload,\n true\n );\n }\n\n return instrumentedEvent;\n }\n\n getMouseEventData(e: MouseEvent): MouseEventData {\n return {\n altKey: e.altKey,\n bubbles: e.bubbles,\n button: e.button,\n buttons: e.buttons,\n cancelable: e.cancelable,\n clientX: e.clientX,\n clientY: e.clientY,\n composed: e.composed,\n defaultPrevented: e.defaultPrevented,\n detail: e.detail,\n eventPhase: e.eventPhase,\n isTrusted: e.isTrusted,\n timeStamp: e.timeStamp,\n type: e.type,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n movementX: e.movementX,\n movementY: e.movementY,\n offsetX: e.offsetX,\n offsetY: e.offsetY,\n pageX: e.pageX,\n pageY: e.pageY,\n screenX: e.screenX,\n screenY: e.screenY,\n shiftKey: e.shiftKey\n };\n }\n}\n\nconst singleton = new DomEventHelpers();\nexport const domEventHelpers = singleton;\n","import { IType, Schema, SchemaTokens } from '../interfaces';\nimport { PbjsNestedObjectDescriptor, SchematizedData, SchematizedDataValue, schemaUtil, utility } from 'o11y/shared';\n\n// These are temporary fields, the max value should be specified as an option on the schema. We may\n// keep some default values like this in the future\nconst maxFieldLength = 10000;\nconst minFieldLength = 0;\n\nconst maxFourBytesPos = 2147483647;\nconst maxFourBytesNeg = -2147483648;\nconst maxFourBytesUnsigned = 4294967295;\nconst maxEightBytesPos = 9223372036854776000;\nconst maxEightBytesNeg = -9223372036854776001;\nconst maxEightBytesUnsigned = 18446744073709552000;\n\nclass LogValidator {\n public validate(schema: Schema, data: SchematizedData): void {\n const schemaTokens: SchemaTokens = schemaUtil.checkSchema(schema);\n utility.requireArgument(data, 'data', 'object');\n\n const nestedSchema: PbjsNestedObjectDescriptor = schemaUtil.getTypes(schema);\n const errorMessage = this.validateFields(\n data,\n nestedSchema[schemaTokens.message] as IType,\n nestedSchema,\n schemaUtil.getSchemaId(schema)\n );\n\n if (errorMessage) {\n throw new Error(errorMessage);\n }\n }\n\n private validateFields(\n data: SchematizedData,\n message: IType,\n custom: PbjsNestedObjectDescriptor,\n schemaId: string\n ): string {\n const oneofs = message.oneofs || {};\n const fields = message.fields || {};\n let errorMessage = undefined;\n for (const key in data) {\n const value = data[key];\n if (!this.isNullOrUndefinedOrEmpty(value)) {\n // if it's null or undefined we don't need to match\n if (oneofs[key]) {\n errorMessage = this.matchFieldTypes(\n value,\n oneofs[key].oneof[0],\n custom,\n schemaId,\n key\n );\n } else if (fields[key]) {\n errorMessage = this.matchFieldTypes(\n value,\n fields[key].type,\n custom,\n schemaId,\n key,\n fields[key].rule\n );\n }\n // if the field is not present in the schema then we ignore it and will drop it later\n }\n if (errorMessage) {\n return errorMessage;\n }\n }\n return undefined;\n }\n\n private isNullOrUndefinedOrEmpty(val: SchematizedDataValue): boolean {\n return val === undefined || val === null || val === '';\n }\n\n private matchFieldTypes(\n fieldData: SchematizedDataValue,\n fieldType: string,\n descriptor: PbjsNestedObjectDescriptor,\n schemaId: string,\n key: string,\n rule?: string\n ): string {\n let convertedSchemaType;\n // this field can generically track specific conditions for each type\n let extraContext = undefined;\n if (rule === 'repeated') {\n let errorMessage = undefined;\n if (Array.isArray(fieldData)) {\n for (const index in fieldData) {\n // if it's repeated they should all be the same type so we can just run it as is\n errorMessage = this.matchFieldTypes(\n fieldData[index],\n fieldType,\n descriptor,\n schemaId,\n key\n );\n if (errorMessage) {\n // we should fail if any values are not validated\n break;\n }\n }\n } else {\n errorMessage = `Schema ${schemaId} on field: ${key}, repeated field should be an array`;\n }\n // this means that every value in the array was validated and we can finish\n return errorMessage;\n }\n switch (fieldType) {\n case 'string':\n convertedSchemaType = 'string';\n break;\n case 'bytes':\n convertedSchemaType = 'object';\n if (!(fieldData instanceof Uint8Array)) {\n extraContext = `Schema ${schemaId} on field: ${key}, bytes array is malformed`;\n }\n break;\n case 'bool':\n convertedSchemaType = 'boolean';\n break;\n case 'uint32':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxFourBytesUnsigned,\n 0,\n schemaId,\n key\n );\n break;\n case 'int32':\n case 'sint32':\n case 'fixed32':\n case 'sfixed32':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxFourBytesPos,\n maxFourBytesNeg,\n schemaId,\n key\n );\n break;\n case 'uint64':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxEightBytesUnsigned,\n 0,\n schemaId,\n key\n );\n break;\n case 'fixed64':\n case 'sfixed64':\n case 'int64':\n case 'sint64':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxEightBytesPos,\n maxEightBytesNeg,\n schemaId,\n key\n );\n break;\n case 'double':\n case 'float':\n convertedSchemaType = 'number';\n if (!Number.isFinite(fieldData)) {\n extraContext = `Schema ${schemaId} on field: ${key}. Value must be finite`;\n }\n break;\n default:\n const ref: Record<string, string> = {};\n const keys = Object.keys(descriptor);\n for (const x in keys) {\n ref[keys[x].toLowerCase()] = keys[x];\n }\n if (ref[fieldType.toLowerCase()]) {\n //now we check this schema\n extraContext = this.validateFields(\n fieldData,\n descriptor[ref[fieldType.toLowerCase()]] as IType,\n descriptor,\n schemaId\n );\n convertedSchemaType = 'object';\n }\n break;\n }\n\n const fieldLength = (fieldData + '').length;\n if (typeof fieldData !== convertedSchemaType) {\n return `Schema ${schemaId} on field: ${key}. Expected type ${fieldType} but received type ${typeof fieldData}`;\n } else if (fieldLength < minFieldLength || fieldLength > maxFieldLength) {\n return `Schema ${schemaId} on field: ${key}, exceeded maximum or minimum field length`;\n } else if (extraContext) {\n return extraContext;\n }\n return undefined;\n }\n\n private checkNumberRange(\n value: number,\n max: number,\n min: number,\n schemaId: string,\n key: string\n ): string {\n if (value > max || value < min) {\n return `Schema ${schemaId} on field: ${key}, number value is too large or small`;\n }\n return undefined;\n }\n}\n\nexport const logValidator = new LogValidator();\n","import { Metric } from '../interfaces/Metric';\nimport { UpCounter } from '../interfaces/UpCounter';\nimport { MetricsTags, utility } from 'o11y/shared';\n\nexport class UpCounterImpl implements Metric<number>, UpCounter {\n private readonly _createdOn: number;\n private _lastUpdatedOn: number;\n private _value = 0;\n\n constructor(\n private readonly _name: string,\n private readonly _ownerName: string,\n private readonly _ownerAppName: string,\n private readonly _tags: MetricsTags\n ) {\n this._createdOn = utility.time().tsNow;\n }\n\n getName(): string {\n return this._name;\n }\n\n getCreatedOn(): number {\n return this._createdOn;\n }\n\n getLastUpdatedOn(): number {\n return this._lastUpdatedOn;\n }\n\n getData(): number {\n return this._value;\n }\n\n increment(value = 1): void {\n if (typeof value === 'number' && value > 0) {\n this._value += Math.round(value);\n this._lastUpdatedOn = utility.time().tsNow;\n return;\n }\n\n throw new Error('UpCounter can only increment positive numbers.');\n }\n\n reset(): void {\n this._lastUpdatedOn = undefined;\n this._value = 0;\n }\n\n getOwnerName(): string {\n return this._ownerName;\n }\n\n getOwnerAppName(): string {\n return this._ownerAppName;\n }\n\n getTags(): Readonly<MetricsTags> {\n return this._tags;\n }\n}\n","import { Metric } from '../interfaces/Metric';\nimport { ValueRecorder } from '../interfaces/ValueRecorder';\nimport { MetricsTags, utility } from 'o11y/shared';\n\nexport class ValueRecorderImpl implements Metric<number[]>, ValueRecorder {\n private readonly _createdOn: number;\n private _lastUpdatedOn: number;\n private _values = new Array<number>();\n\n constructor(\n private readonly _name: string,\n private readonly _ownerName: string,\n private readonly _ownerAppName: string,\n private readonly _tags: MetricsTags\n ) {\n this._createdOn = utility.time().tsNow;\n // TODO: Add sampling/throttling to put a cap on the size of the array\n }\n\n getName(): string {\n return this._name;\n }\n\n getCreatedOn(): number {\n return this._createdOn;\n }\n\n getLastUpdatedOn(): number {\n return this._lastUpdatedOn;\n }\n\n getData(): number[] {\n return this.values;\n }\n\n get values(): number[] {\n return this._values.slice(0, this._values.length);\n }\n\n record(value: number): void {\n if (typeof value === 'number') {\n this._values.push(value);\n this._lastUpdatedOn = utility.time().tsNow;\n return;\n }\n\n throw new Error('ValueRecorder can only record numbers.');\n }\n\n reset(): void {\n this._lastUpdatedOn = undefined;\n this._values = [];\n }\n\n getOwnerName(): string {\n return this._ownerName;\n }\n\n getOwnerAppName(): string {\n return this._ownerAppName;\n }\n\n getTags(): MetricsTags {\n return this._tags;\n }\n}\n","export class SizeLimitedMap<K, V> {\n private readonly _map = new Map<K, V>();\n\n private _maxSize: number;\n constructor(maxSize: number) {\n if (typeof maxSize === 'number' && maxSize > 0) {\n this._maxSize = Math.ceil(maxSize);\n return;\n }\n throw new Error('maxSize must be a positive number');\n }\n\n get maxSize(): number {\n return this._maxSize;\n }\n\n get(key: K): V {\n return this._map.get(key);\n }\n\n has(key: K): boolean {\n return this._map.has(key);\n }\n\n set(key: K, value: V): boolean {\n if (this.has(key) || this._map.size < this.maxSize) {\n this._map.set(key, value);\n return true;\n }\n return false;\n }\n\n getElements(): V[] {\n return Array.from(this._map.values());\n }\n\n clear(): void {\n this._map.clear();\n }\n}\n","import { MetricsReporter, UpCounter, ValueRecorder } from '../interfaces';\n\nimport { UpCounterImpl } from './UpCounterImpl';\nimport { ValueRecorderImpl } from './ValueRecorderImpl';\nimport { SizeLimitedMap } from './SizeLimitedMap';\nimport { MetricsTags } from 'o11y/shared';\n\nconst maxCounters = 1000;\nconst maxValueRecorders = 500;\n\nenum MetricType {\n Counter,\n Percentile\n}\n\nexport class MetricsImpl implements MetricsReporter {\n private readonly _upCounters = new SizeLimitedMap<string, UpCounterImpl>(maxCounters);\n private readonly _valueRecorders = new SizeLimitedMap<string, ValueRecorderImpl>(\n maxValueRecorders\n );\n\n constructor(private readonly _ownerName: string, private readonly _ownerAppName: string) {}\n\n incrementCounter(\n operation: string,\n increment: number,\n hasError = false,\n tags: MetricsTags = {}\n ): void {\n this._tagError(tags, hasError);\n this._upCounter(operation, tags).increment(increment);\n }\n\n trackValue(operation: string, value: number, hasError = false, tags: MetricsTags = {}): void {\n this._tagError(tags, hasError);\n this._valueRecorder(operation, tags).record(value);\n }\n\n private _upCounter(name: string, tags: MetricsTags): UpCounter {\n const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Counter);\n let instrument = this._upCounters.get(key);\n if (!instrument) {\n instrument = new UpCounterImpl(name, this._ownerName, this._ownerAppName, sortedTags);\n if (!this._upCounters.set(key, instrument)) {\n throw new Error(`Max size of ${maxCounters} exceeeded for UpCounters`);\n }\n }\n return instrument;\n }\n\n private _valueRecorder(name: string, tags: MetricsTags): ValueRecorder {\n const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Percentile);\n let instrument = this._valueRecorders.get(key);\n if (!instrument) {\n instrument = new ValueRecorderImpl(\n name,\n this._ownerName,\n this._ownerAppName,\n sortedTags\n );\n if (!this._valueRecorders.set(key, instrument)) {\n throw new Error(`Max size of ${maxValueRecorders} exceeeded for ValueRecorders`);\n }\n }\n return instrument;\n }\n\n getUpCounters(): UpCounterImpl[] {\n return this._upCounters.getElements();\n }\n\n getValueRecorders(): ValueRecorderImpl[] {\n return this._valueRecorders.getElements();\n }\n\n private _tagError(tags: MetricsTags, hasError: boolean): void {\n tags.status = hasError === true ? 'error' : 'success';\n }\n\n private _getKeyAndSortedTags(\n operation: string,\n tags: MetricsTags,\n metricType: MetricType\n ): { key: string; sortedTags: MetricsTags } {\n // This method should be called after any manipulation of tags\n const sortedTags = Object.keys(tags)\n .sort()\n .reduce((prev: MetricsTags, curr: string) => {\n prev[curr] = tags[curr];\n return prev;\n }, {});\n const key = `${MetricType[metricType]}:${operation}${JSON.stringify(sortedTags)}`;\n return {\n key,\n sortedTags\n };\n }\n}\n","export class MockEvent {\n constructor(\n public readonly type: string,\n public readonly composed: boolean,\n private readonly _composedPaths: unknown[]\n ) {}\n composedPath(): unknown[] {\n return this._composedPaths;\n }\n}\n","import {\n activitySchema,\n errorSchema,\n instrumentedEventSchema,\n simpleSchema\n} from 'o11y_schema/sf_instrumentation';\n\nimport {\n Activity,\n ActivityDetail,\n Instrumentation,\n Metric,\n MetricsReporter,\n PayloadProvider,\n Schema,\n SchematizedPayload\n} from '../interfaces';\nimport { ActivityData, ErrorData, InstrumentedEventData } from '../interfaces-private';\n\nimport { ActivityImpl, discarded, onActivityError, onActivityStop } from './ActivityImpl';\nimport { activityNoOp } from './ActivityNoOp';\nimport { AutomaticClickTracker } from './AutomaticClickTracker';\nimport { domEventHelpers } from './DomEventHelpers';\nimport { logValidator } from './LogValidator';\nimport { MetricsImpl } from './MetricsImpl';\nimport { MockEvent } from './MockEvent';\nimport { NextgenImpl } from './NextgenImpl';\nimport { PublicSafety } from './PublicSafety';\nimport { LightningElement, MetricsTags, SchematizedData, schemaUtil, utility } from 'o11y/shared';\n\nconst maxActivityDurationMsecs = 30000;\n\nconst reservedMetricCharacters = ['`'];\nconst reservedMetricNames = {\n internalError: 'o11y-error'\n};\nconst denyListMetricNames = Object.freeze(Array.from(Object.values(reservedMetricNames)));\n\nexport class InstrumentationImpl implements Instrumentation, MetricsReporter {\n private readonly _metrics: MetricsImpl;\n private readonly _onActivityStoppedCallback: onActivityStop =\n this._handleActivityStop.bind(this);\n protected readonly _onActivityErrorCallback: onActivityError =\n this._handleActivityError.bind(this);\n protected readonly _safety: PublicSafety;\n private readonly _simpleTextMaxLength: number;\n\n constructor(private readonly _nextGen: NextgenImpl, private readonly _name: string) {\n for (const reservedChar of reservedMetricCharacters) {\n if (this._name.indexOf(reservedChar) >= 0) {\n throw new Error(`Name cannot include the reserved character \"${reservedChar}\"`);\n }\n }\n\n this._safety = new PublicSafety({\n increment: (increment) => this._incrementError(increment)\n });\n\n this._metrics = new MetricsImpl(this.name, this._nextGen.appName);\n\n const simpleTextOptions = schemaUtil.getOptions(simpleSchema, 'Simple', 'text');\n this._simpleTextMaxLength = simpleTextOptions\n ? simpleTextOptions['(meta.max_length)']\n : Number.MAX_VALUE;\n }\n\n private _incrementError(increment = 1): void {\n this._metrics.incrementCounter(reservedMetricNames.internalError, increment, false);\n }\n\n get name(): string {\n return this._name;\n }\n\n /**\n * This function is to allow for convenience calls to our API, where a string can\n * be provided instead of an actual Schema. In that case, we wrap the text in\n * a built-in simple schema.\n * @param userSchemaOrText Schema or string.\n * @param userData\n * @param onlyIfBoth If true, then both the schema and the data must be specified.\n * @returns\n */\n protected _wrapUserPayload(\n userSchemaOrText: Schema | string,\n userData: SchematizedData,\n onlyIfBoth = false\n ): SchematizedPayload {\n let userSchema: Schema;\n if (typeof userSchemaOrText === 'string') {\n userSchema = simpleSchema;\n if (userSchemaOrText) {\n userData = {\n text: userSchemaOrText.substr(0, this._simpleTextMaxLength)\n };\n } else {\n userData = undefined;\n }\n } else {\n userSchema = userSchemaOrText;\n }\n\n return schemaUtil.makePayload(userSchema, userData, onlyIfBoth);\n }\n\n /**\n *\n * @param userSchema The schema of the second argument. Also used as the basis for auto-generated\n * counters for log calls using the same schema.\n * @param userData Optional data that complies with the provided schema\n */\n log(userSchemaOrText: Schema | string, userData?: SchematizedData): void {\n this._safety.tryCatch(() => {\n const timestamp = utility.time().tsNow;\n utility.requireArgument(userSchemaOrText, 'userSchemaOrText', ['object', 'string']);\n\n const userPayload = this._wrapUserPayload(userSchemaOrText, userData);\n\n if (userPayload && userPayload.payload) {\n this._logInternal(\n this.name,\n userPayload.schema,\n userPayload.payload,\n timestamp,\n this._nextGen.getRootActivityId()\n );\n }\n });\n }\n\n protected _logInternal(\n loggerName: string,\n schema: Schema,\n data: SchematizedData,\n timestamp: number,\n rootId?: string\n ): number {\n this._checkInputs(schema, data);\n const appPayload: SchematizedPayload = this._getPayloadFromProvider(\n this._nextGen.appPayloadProvider\n );\n const pagePayload: SchematizedPayload = this._getPayloadFromProvider(\n this._nextGen.pagePayloadProvider\n );\n\n return this._nextGen.addLog(\n loggerName,\n schema,\n data,\n timestamp,\n rootId,\n pagePayload,\n appPayload\n );\n }\n\n error(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData\n ): void {\n return this._safety.tryCatch(() => this._errorInternal(error, userSchemaOrText, userData));\n }\n\n protected _errorInternal(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData,\n activityId?: string\n ): number {\n const loggedTimestamp = utility.time().tsNow;\n this._incrementError();\n utility.requireArgument(error, 'error', [Error, 'string']);\n\n if (typeof error === 'string') {\n error = new Error(error);\n }\n\n const userPayload = this._wrapUserPayload(userSchemaOrText, userData, true);\n\n const errorData: ErrorData = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n userPayload,\n activityId\n };\n\n return this._logInternal(\n this.name,\n errorSchema,\n errorData,\n loggedTimestamp,\n this._nextGen.getRootActivityId()\n );\n }\n\n startActivity(name: string): Activity {\n return this._safety.tryCatchReturn(() => {\n utility.requireArgument(name, 'name');\n\n const activity: Activity = new ActivityImpl(\n name,\n this._nextGen.getRootActivityId(),\n this._onActivityStoppedCallback,\n this._onActivityErrorCallback,\n maxActivityDurationMsecs,\n undefined,\n // By definition, an activity is sampled if root activity is sampled\n this._nextGen.isRootActivitySampled()\n );\n return activity;\n }, activityNoOp);\n }\n\n protected _getActivityData(detail: ActivityDetail): ActivityData {\n const userPayload = this._wrapUserPayload(detail.userSchemaOrText, detail.userData, true);\n\n return {\n id: detail.id,\n name: detail.name,\n duration: detail.stopPerfTime - detail.startPerfTime,\n stopReason: detail.stopReason,\n userPayload,\n errorCount: detail.errorCount,\n isSampled: detail.isSampled\n };\n }\n\n private _handleActivityStop(detail: ActivityDetail): void {\n if (detail.stopReason === discarded) {\n return;\n }\n const activityData: ActivityData = this._getActivityData(detail);\n\n this._logActivity(activityData, detail.startTimestamp, detail.rootId);\n }\n\n protected _logActivity(\n activityData: ActivityData,\n startTimestamp: number,\n rootId?: string\n ): void {\n this._logInternal(this.name, activitySchema, activityData, startTimestamp, rootId);\n }\n\n private _handleActivityError(error: Error, detail: ActivityDetail): void {\n this._errorInternal(error, detail.userSchemaOrText, detail.userData, detail.id);\n }\n\n private _getPayloadFromProvider(provider: PayloadProvider): SchematizedPayload {\n if (provider) {\n const payload: SchematizedPayload = provider.getPayload();\n if (payload) {\n this._checkInputs(payload.schema, payload.payload);\n return payload;\n }\n }\n return undefined;\n }\n\n domEvent(\n event: Event,\n handledBy: HTMLElement | LightningElement,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData,\n auto?: boolean\n ): void {\n this._safety.tryCatch(() => {\n const tsNow = utility.time().tsNow;\n\n utility.requireArgument(event, 'event', [Event, MockEvent]);\n // TODO: Using 'object' instead of 'LightningElement' for now (no imports)\n utility.requireArgument(handledBy, 'handledBy', [HTMLElement, 'object']);\n\n let htmlElement;\n if (handledBy instanceof HTMLElement) {\n htmlElement = handledBy;\n } else {\n handledBy = handledBy as LightningElement;\n // Convenience for LightningElement developers who pass \"this\" in handledBy.\n // Get the underlying HTML element\n if (handledBy.template && handledBy.template.host instanceof HTMLElement) {\n htmlElement = handledBy.template.host;\n } else {\n utility.requireArgument(undefined, 'handledBy');\n }\n }\n\n const userPayload: SchematizedPayload = this._wrapUserPayload(\n userSchemaOrText,\n userData,\n true\n );\n\n switch (event.type) {\n case 'click': {\n const mouseEvent = event as MouseEvent;\n\n // If the user has called domEvent API on this event explicitly,\n // then we don't need to log it by default.\n const acd: AutomaticClickTracker = this._nextGen.getClickTracker();\n if (acd) {\n acd.markEventHandled(mouseEvent);\n }\n\n const mouseEventData = domEventHelpers.getMouseEventData(mouseEvent);\n\n const instrumentedEvent: InstrumentedEventData =\n domEventHelpers.getInstrumentedEventData(\n mouseEventData,\n htmlElement,\n userPayload\n );\n instrumentedEvent.auto = auto;\n\n this._logInternal(\n this.name,\n instrumentedEventSchema,\n instrumentedEvent,\n tsNow,\n this._nextGen.getRootActivityId()\n );\n break;\n }\n default:\n throw new Error(utility.notImplemented);\n }\n });\n }\n\n incrementCounter(\n operation: string,\n increment = 1,\n hasError = false,\n tags: MetricsTags = {}\n ): void {\n this._safety.tryCatch(() => {\n utility.requireArgument(operation, 'operation', 'string');\n utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);\n utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);\n utility.requireArgument(increment, 'increment', 'number');\n utility.requireArgument(hasError, 'hasError', 'boolean');\n utility.requireArgument(tags, 'tags', 'object');\n Object.entries(tags).forEach((entry) => {\n utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [\n 'string',\n 'number',\n 'boolean'\n ]);\n });\n this._metrics.incrementCounter(operation, increment, hasError, tags);\n });\n }\n\n trackValue(operation: string, value: number, hasError = false, tags: MetricsTags = {}): void {\n this._safety.tryCatch(() => {\n utility.requireArgument(operation, 'operation', 'string');\n utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);\n utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);\n utility.requireArgument(value, 'value', 'number');\n utility.requireArgument(hasError, 'hasError', 'boolean');\n utility.requireArgument(tags, 'tags', 'object');\n Object.entries(tags).forEach((entry) => {\n utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [\n 'string',\n 'number',\n 'boolean'\n ]);\n });\n\n this._metrics.trackValue(operation, value, hasError, tags);\n });\n }\n\n private _checkInputs(schema: Schema, data: SchematizedData): void {\n schemaUtil.checkSchema(schema);\n utility.requireArgument(data, 'data', 'object');\n\n // TODO: Protobuf-free Validation.\n // Until then, do a best-case effort.\n let savedUserPayload: SchematizedPayload;\n if (data.userPayload !== undefined && schemaUtil.isInternal(schema)) {\n savedUserPayload = data.userPayload;\n logValidator.validate(savedUserPayload.schema, savedUserPayload.payload);\n // userPayload needs to be temporarily removed, since it's not yet encoded.\n data.userPayload = undefined;\n }\n logValidator.validate(schema, data);\n if (savedUserPayload !== undefined) {\n // Restore userPayload\n data.userPayload = savedUserPayload;\n }\n }\n\n getUpCounters(): Metric<number>[] {\n return this._metrics.getUpCounters().filter((m) => m.getLastUpdatedOn());\n }\n\n getValueRecorders(): Metric<number[]>[] {\n return this._metrics.getValueRecorders().filter((m) => m.getLastUpdatedOn());\n }\n}\n","import { RootActivity, Schema } from '../interfaces';\nimport { ActivityDetail } from '../interfaces/ActivityDetail';\nimport { ActivityImpl, onActivityError, onActivityStop } from './ActivityImpl';\nimport { SchematizedData, utility } from 'o11y/shared';\n\nexport class RootActivityImpl extends ActivityImpl implements RootActivity {\n constructor(\n name: string,\n onStopped: onActivityStop,\n onError: onActivityError,\n rootId?: string,\n _isSampled?: boolean\n ) {\n super(\n name,\n undefined,\n onStopped,\n onError,\n undefined,\n rootId || utility.generateUniqueId(32),\n _isSampled\n );\n }\n\n private _preRootId: string;\n get preRootId(): string {\n return this._preRootId;\n }\n set preRootId(value: string) {\n this._preRootId = value;\n }\n\n protected _getDetail(userSchema: Schema, userData: SchematizedData): ActivityDetail {\n const detail = super._getDetail(userSchema, userData);\n detail.isRoot = true;\n detail.preRootId = this.preRootId;\n return detail;\n }\n}\n","import { RootActivity, TracingHeadersOptions } from '../interfaces';\n\nconst rootId: string = new Array(32).fill(0).join('');\nclass RootActivityNoOp implements RootActivity {\n getId(): string {\n return rootId;\n }\n getRootId(): string {\n return undefined;\n }\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n error(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n stop(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n discard(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n terminate(): void {}\n\n getIsSampled(): boolean {\n return false;\n }\n getTraceHeaders(__options: TracingHeadersOptions): Record<string, string> {\n return {};\n }\n getStartTimestamp(): number {\n return undefined;\n }\n getStartPerfTime(): number {\n return undefined;\n }\n getStopPerfTime(): number {\n return undefined;\n }\n}\n\nexport const rootActivityNoOp = Object.freeze(new RootActivityNoOp());\n","import { ActivityDetail, RootActivity } from '../interfaces';\nimport { ActivityData } from '../interfaces-private';\nimport { discarded, onActivityStop } from './ActivityImpl';\nimport { InstrumentationImpl } from './InstrumentationImpl';\nimport { RootActivityImpl } from './RootActivityImpl';\nimport { rootActivityNoOp } from './RootActivityNoOp';\nimport { utility } from 'o11y/shared';\n\nexport class AppInstrumentationImpl extends InstrumentationImpl {\n private rootActivity: RootActivityImpl;\n\n private readonly _onRootActivityStoppedCallback: onActivityStop =\n this.handleRootActivityStop.bind(this);\n\n startRootActivity(name: string, rootId?: string, isSampled?: boolean): RootActivity {\n return this._safety.tryCatchReturn(() => {\n utility.requireArgument(name, 'name');\n\n const newRootActivity = new RootActivityImpl(\n name,\n this._onRootActivityStoppedCallback,\n this._onActivityErrorCallback,\n rootId,\n isSampled\n );\n\n if (this.rootActivity && !this.rootActivity.isStopped) {\n const preRootId = this.rootActivity.getId();\n this.rootActivity.terminate();\n newRootActivity.preRootId = preRootId;\n }\n this.rootActivity = newRootActivity;\n\n return this.rootActivity as RootActivity;\n }, rootActivityNoOp);\n }\n\n private handleRootActivityStop(detail: ActivityDetail): void {\n if (detail.stopReason === discarded) {\n return;\n }\n\n const activityData: ActivityData = this._getActivityData(detail);\n\n this._logActivity(activityData, detail.startTimestamp);\n this.rootActivity = undefined;\n }\n\n protected _getActivityData(detail: ActivityDetail): ActivityData {\n const activityData: ActivityData = super._getActivityData(detail);\n activityData.isRoot = detail.isRoot;\n activityData.preRootId = detail.preRootId;\n return activityData;\n }\n\n getRootActivityId(): string {\n return this.rootActivity && this.rootActivity.getId();\n }\n\n isRootActivitySampled(): boolean {\n return this.rootActivity && this.rootActivity.getIsSampled();\n }\n}\n","import { Instrumentation } from '../interfaces';\nimport { utility } from 'o11y/shared';\n\nconst pathLimit = 5;\n\nexport class AutomaticClickTracker {\n private instr: Instrumentation;\n private ignoredEvent: Event;\n private isActive = false;\n private document: Document;\n private readonly _boundClickListener = this.clickListener.bind(this);\n\n constructor(instrumentation: Instrumentation, document: Document) {\n utility.requireArgument(instrumentation, 'instrumentation');\n utility.requireArgument(document, 'document');\n\n this.instr = instrumentation;\n this.document = document;\n }\n\n activate(): void {\n if (!this.isActive) {\n this.document.addEventListener('click', this._boundClickListener, true);\n this.isActive = true;\n }\n }\n\n deactivate(): void {\n if (this.isActive) {\n this.document.removeEventListener('click', this._boundClickListener, true);\n this.isActive = false;\n }\n }\n\n markEventHandled(event: MouseEvent): void {\n this.ignoredEvent = event;\n }\n\n private clickListener(event: MouseEvent): void {\n let eventTargets: EventTarget[] = event.composedPath && event.composedPath();\n if (!eventTargets || !eventTargets.length) {\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n eventTargets = (event as any).path;\n }\n const handledBy: HTMLElement = this.getClickableElement(eventTargets);\n\n if (handledBy) {\n // Immediate\n setTimeout(() => {\n if (event !== this.ignoredEvent) {\n this.instr.domEvent(event, handledBy, undefined, undefined, true);\n }\n });\n }\n }\n\n private getClickableElement(path: EventTarget[]): HTMLElement {\n const limit = path ? Math.min(path.length, pathLimit) : 0;\n for (let x = 0; x < limit; x += 1) {\n const currentElement = path[x] as HTMLElement;\n const tagName = currentElement.tagName && currentElement.tagName.toLowerCase();\n if (tagName === 'a' || tagName === 'button') {\n return currentElement;\n }\n if (tagName === 'input') {\n const inputElement = currentElement as HTMLInputElement;\n if (inputElement.type && inputElement.type.toLowerCase() === 'button') {\n return inputElement;\n }\n }\n }\n return undefined;\n }\n}\n","import {\n BufferedLog,\n Instrumentation,\n InstrumentedAppMethods,\n LogCollector,\n LogMeta,\n Metric,\n MetricsCollector,\n Nextgen,\n PayloadProvider,\n Schema,\n SchematizedPayload\n} from '../interfaces';\nimport { AppInstrumentationImpl } from './AppInstrumentationImpl';\nimport { AutomaticClickTracker } from './AutomaticClickTracker';\nimport { InstrumentationImpl } from './InstrumentationImpl';\nimport { Tracing } from './Tracing';\nimport { SchematizedData, utility } from 'o11y/shared';\nimport { LogCollectorOptions } from 'src/interfaces/LogCollectorOptions';\n\nconst maxInstrumentationLength = 80;\nconst truncatedText = '_CUT';\nconst maxInstrumentationLengthBeforeTruncated = maxInstrumentationLength - truncatedText.length;\n\nexport class NextgenImpl implements Nextgen {\n private readonly _logCollectors = new Set<LogCollector>();\n private readonly _instruments = new Map<string, InstrumentationImpl | AppInstrumentationImpl>();\n private _sequence = 0;\n private _appInstr: AppInstrumentationImpl;\n private _autoClickTracker: AutomaticClickTracker;\n private _metricsCollector: MetricsCollector;\n private _appPayloadProvider: PayloadProvider;\n private _pagePayloadProvider: PayloadProvider;\n private _forceDisabledLogCollectors = new Set<LogCollector>();\n private _logCollectorFailures = new Map<LogCollector, number>();\n private static _collectorFailureLimit = 5;\n private _isBufferingEnabled = false;\n private _buffer: BufferedLog[] = [];\n\n get pagePayloadProvider(): PayloadProvider {\n return this._pagePayloadProvider;\n }\n set pagePayloadProvider(provider: PayloadProvider) {\n this._pagePayloadProvider = provider;\n }\n\n get appPayloadProvider(): PayloadProvider {\n return this._appPayloadProvider;\n }\n set appPayloadProvider(provider: PayloadProvider) {\n this._appPayloadProvider = provider;\n }\n\n registerApp(name: string, enableBuffering?: boolean): InstrumentedAppMethods {\n utility.requireArgument(name, 'name', 'string');\n if (this._appInstr) {\n throw new Error('An app has already been registered with instrumentation.');\n }\n const instr = this._instruments.get(name);\n if (instr) {\n throw new Error(`The instrumentation name ${name} is already taken`);\n }\n this._appInstr = new AppInstrumentationImpl(this, name);\n this._instruments.set(name, this._appInstr);\n this._isBufferingEnabled = enableBuffering;\n\n const tracing = new Tracing(this._appInstr);\n\n return {\n log: this._appInstr.log.bind(this._appInstr),\n error: this._appInstr.error.bind(this._appInstr),\n startActivity: this._appInstr.startActivity.bind(this._appInstr),\n domEvent: this._appInstr.domEvent.bind(this._appInstr),\n incrementCounter: this._appInstr.incrementCounter.bind(this._appInstr),\n trackValue: this._appInstr.trackValue.bind(this._appInstr),\n networkInstrumentation: tracing.networkInstrumentation.bind(tracing),\n\n startRootActivity: this._appInstr.startRootActivity.bind(this._appInstr),\n registerLogCollector: this.registerLogCollector.bind(this),\n registerMetricsCollector: this.registerMetricsCollector.bind(this),\n activateClickTracker: this.activateClickTracker.bind(this),\n deactivateClickTracker: this.deactivateClickTracker.bind(this),\n disableBuffering: this.disableBuffering.bind(this)\n };\n }\n\n getInstrumentation(name: string): Instrumentation {\n utility.requireArgument(name, 'name', 'string');\n if (name.length > maxInstrumentationLength) {\n // don't throw if it's too long. just add truncated suffix, but stay within max length\n name = name.substr(0, maxInstrumentationLengthBeforeTruncated) + truncatedText;\n }\n let instr: InstrumentationImpl | AppInstrumentationImpl = this._instruments.get(name);\n if (!instr) {\n instr = new InstrumentationImpl(this, name);\n this._instruments.set(name, instr);\n } else if (instr === this._appInstr) {\n throw new Error(`The instrumentation name ${name} is being used by the app.`);\n }\n return instr;\n }\n\n get appName(): string {\n return this._appInstr && this._appInstr.name;\n }\n\n // This is an internal method that needs to be public\n addLog(\n loggerName: string,\n schema: Schema,\n data: SchematizedData,\n timestamp: number,\n rootId: string,\n pagePayload: SchematizedPayload,\n appPayload: SchematizedPayload\n ): number {\n this._sequence += 1;\n const sequence: number = this._sequence;\n const loggerAppName: string = this.appName;\n const connectionType: string = utility.getConnectionType();\n const logMeta: LogMeta = {\n timestamp,\n rootId,\n sequence,\n loggerName,\n pagePayload,\n appPayload,\n loggerAppName,\n connectionType\n };\n\n if (this._isBufferingEnabled) {\n this._buffer.push({ schema, data: utility.clone(data), logMeta });\n }\n\n for (const collector of this._logCollectors) {\n // Make a copy of the aguments passed to the collectors lest they change them.\n const dataClone = utility.clone(data);\n const failures: number = this._logCollectorFailures.get(collector);\n\n try {\n if (\n !this._forceDisabledLogCollectors.has(collector) &&\n !(collector.getIsCollectDisabled && collector.getIsCollectDisabled())\n ) {\n collector.collect(schema, dataClone, logMeta);\n // if it got here it means it succeeded/didn't throw so we want to decrement the failure count\n if (failures > 0) {\n this._logCollectorFailures.set(collector, failures - 1);\n }\n }\n } catch (err) {\n // If a collector fails too much we just disable it\n if (\n failures >= NextgenImpl._collectorFailureLimit &&\n !this._forceDisabledLogCollectors.has(collector)\n ) {\n this._forceDisabledLogCollectors.add(collector);\n } else {\n this._logCollectorFailures.set(collector, failures + 1);\n }\n }\n }\n return this._sequence;\n }\n\n getBuffer(): BufferedLog[] {\n return this._buffer;\n }\n\n disableBuffering(): void {\n this._isBufferingEnabled = false;\n this._buffer = [];\n }\n\n getClickTracker(): AutomaticClickTracker {\n return this._autoClickTracker;\n }\n\n getRootActivityId(): string {\n return this._appInstr && this._appInstr.getRootActivityId();\n }\n\n isRootActivitySampled(): boolean {\n return this._appInstr && this._appInstr.isRootActivitySampled();\n }\n\n activateClickTracker(): void {\n if (!this._autoClickTracker) {\n this._autoClickTracker = new AutomaticClickTracker(this._appInstr, window.document);\n }\n this._autoClickTracker.activate();\n }\n\n deactivateClickTracker(): void {\n if (this._autoClickTracker) {\n this._autoClickTracker.deactivate();\n // In case activateClickTracker is called later with a different instrumentation\n this._autoClickTracker = undefined;\n }\n }\n\n registerLogCollector(collector: LogCollector, options?: LogCollectorOptions): void {\n utility.requireArgument(collector, 'collector');\n this._logCollectors.add(collector);\n this._logCollectorFailures.set(collector, 0);\n if (\n (!collector.getIsCollectDisabled || !collector.getIsCollectDisabled()) &&\n options &&\n options.retroactive\n ) {\n for (const log of this._buffer) {\n collector.collect(log.schema, log.data, log.logMeta);\n }\n }\n }\n\n registerMetricsCollector(collector: MetricsCollector): void {\n utility.requireArgument(collector, 'collector');\n if (this._metricsCollector) {\n throw new Error('A metrics Collector is already registered.');\n }\n this._metricsCollector = collector;\n this._metricsCollector.receiveMetricsExtractors({\n getAllUpCounters: this.getAllUpCounters.bind(this),\n getAllValueRecorders: this.getAllValueRecorders.bind(this)\n });\n }\n\n private getAllUpCounters(): Metric<number>[] {\n const arrOfArrs = Array.from(this._instruments.values()).map((instr) =>\n instr.getUpCounters()\n );\n return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);\n }\n\n private getAllValueRecorders(): Metric<number[]>[] {\n const arrOfArrs = Array.from(this._instruments.values()).map((instr) =>\n instr.getValueRecorders()\n );\n return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);\n }\n}\n","import { Instrumentation, InstrumentedAppMethods, InstrumentedAppOptions } from './interfaces';\nimport { NextgenImpl } from './library/NextgenImpl';\nimport { utility } from 'o11y/shared';\n\nclass Index {\n private _nextgen: NextgenImpl;\n // We are lazily initializing the singleton to allow any options to be processed\n // before the instantiation.\n private get _lazyNextGen(): NextgenImpl {\n if (!this._nextgen) {\n this._nextgen = new NextgenImpl();\n }\n return this._nextgen;\n }\n\n public registerInstrumentedApp(\n name: string,\n options?: InstrumentedAppOptions\n ): InstrumentedAppMethods {\n if (options && options.isProduction) {\n // Do this before construction\n utility.markProduction();\n }\n const retVal: InstrumentedAppMethods = this._lazyNextGen.registerApp(\n name,\n options && options.enableBuffering\n );\n if (options) {\n this._nextgen.appPayloadProvider = options.appPayloadProvider;\n this._nextgen.pagePayloadProvider = options.pagePayloadProvider;\n }\n return retVal;\n }\n\n public getInstrumentation(name?: string): Instrumentation {\n return this._lazyNextGen.getInstrumentation(name);\n }\n}\nconst index = new Index(); // singleton\nconst registerInstrumentedApp = index.registerInstrumentedApp.bind(index);\nconst getInstrumentation = index.getInstrumentation.bind(index);\nconst time = utility.time.bind(utility);\n\nexport { registerInstrumentedApp, getInstrumentation, time };\n","import { Root, Type } from 'protobufjs';\nimport { coreEnvelopeSchema } from 'o11y_schema/sf_instrumentation';\n\nimport {\n Environment,\n Instrumentation,\n LogCollector,\n LogMeta,\n MetricsCollector,\n MetricsExtractorMethods,\n Schema\n} from '../../interfaces';\nimport { LazyMapToList, SchematizedData, schemaUtil } from 'o11y/shared';\n\nimport { CoreEnvelope } from './CoreEnvelope';\nimport { CoreEnvelopeBuilder } from './CoreEnvelopeBuilder';\nimport { LogMessage } from './LogMessage';\nimport { StaticAttributes } from './StaticAttributes';\nimport { protobufUtil } from '../protobuf-util';\nimport { getInstrumentation } from '../../index';\n\nconst maxUniqueSchemas = 10000;\nconst maxDelay_msecs = 10000;\nconst uploadThreshold_items = 10;\nconst formDataKey = 'telemetry';\n\nexport enum UploadMode {\n fetchBinary, // application/octet-stream\n fetchFile, // multipart/form-data\n noUpload\n}\n\nexport class CoreCollector implements LogCollector, MetricsCollector {\n private readonly _messageBuffers = new LazyMapToList<Schema, LogMessage>(maxUniqueSchemas);\n private readonly _coreEnvelopeType: Type;\n private _intervalHandle: NodeJS.Timeout;\n private _metricsExtractors: MetricsExtractorMethods;\n private _staticAttributes: StaticAttributes;\n private _immediateUpload: boolean;\n private _instr: Instrumentation = getInstrumentation('CoreCollector');\n\n constructor(\n private readonly _apiEndpoint?: string,\n private readonly _uploadMode?: UploadMode,\n readonly environment?: Environment\n ) {\n if (!_apiEndpoint) {\n this._uploadMode = UploadMode.noUpload;\n } else if (_uploadMode === undefined) {\n this._uploadMode = UploadMode.fetchBinary;\n } else if (!(_uploadMode in UploadMode)) {\n throw new Error(`Unsupported upload mode: ${_uploadMode}`);\n }\n\n const root = Root.fromJSON(coreEnvelopeSchema.pbjsSchema);\n this._coreEnvelopeType = root.lookupType('CoreEnvelope');\n\n if (environment) {\n this._staticAttributes = {\n appName: environment.appName,\n appVersion: environment.appVersion,\n appExperience: environment.appExperience,\n deviceId: environment.deviceId,\n deviceModel: environment.deviceModel,\n sdkVersion: environment.sdkVersion\n };\n }\n }\n\n getIsCollectDisabled(): boolean {\n return this._isFull();\n }\n\n getProtoEncodedCoreEnvelope(): Uint8Array {\n return this._getProtoEncodedCoreEnvelope();\n }\n\n getByteSize(): number {\n return this._messageBuffers.byteSizeOfValues;\n }\n\n private _isFull(): boolean {\n return this._messageBuffers.totalItemCount === this._messageBuffers.maxSize;\n }\n\n private _stopTimer(): void {\n if (this._intervalHandle !== undefined) {\n clearInterval(this._intervalHandle);\n }\n }\n\n private _restartTimer(): void {\n this._stopTimer();\n this._intervalHandle = setInterval(() => {\n this._upload();\n }, maxDelay_msecs);\n }\n\n collect(schema: Schema, data: SchematizedData, logMeta: LogMeta): void {\n const wasEmpty = this._messageBuffers.totalItemCount === 0;\n\n if (schemaUtil.isInternal(schema) && data.userPayload) {\n data.userPayload = protobufUtil.encodePayload(data.userPayload);\n }\n\n if (!this._messageBuffers.push(schema, protobufUtil.getLogMessage(schema, data, logMeta))) {\n // This means that the buffer is full, so we should disable, upload, and reenable once\n // are able to accept more logs\n this._instr.error(new Error('Buffer is full'), schemaUtil.getSchemaId(schema));\n this._stopTimer();\n this._upload();\n } else if (wasEmpty) {\n // Start the timer when we have at least one message\n this._restartTimer();\n }\n\n if (!this.getIsCollectDisabled() && this._shouldUpload()) {\n // Rethink how to do the timer in case we don't get any logs but possibly there are metrics.\n this._stopTimer();\n this._upload();\n }\n }\n\n private _shouldUpload(): boolean {\n return (\n this._immediateUpload || this._messageBuffers.totalItemCount >= uploadThreshold_items\n );\n }\n\n private async _upload(): Promise<void> {\n try {\n if (this._uploadMode === UploadMode.noUpload) {\n // do nothing\n return;\n }\n const buffer: Uint8Array = this._getProtoEncodedCoreEnvelope();\n if (!buffer) {\n // Nothing to upload\n return;\n }\n\n let requestInit;\n switch (this._uploadMode) {\n case UploadMode.fetchBinary:\n requestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream'\n },\n body: buffer\n };\n break;\n case UploadMode.fetchFile:\n const formData = new FormData();\n formData.append(formDataKey, new Blob([buffer]));\n // Per [this article](https://muffinman.io/uploading-files-using-fetch-multipart-form-data/)\n // make sure not to set the Content-Type header.\n // The browser will set it for you, including the boundary parameter.\n requestInit = {\n method: 'POST',\n body: formData\n };\n break;\n }\n if (requestInit) {\n await fetch(this._apiEndpoint, requestInit);\n }\n } catch (err) {\n this._instr.error(err);\n }\n }\n\n private _getProtoEncodedCoreEnvelope(): Uint8Array {\n if (!this._messageBuffers.totalItemCount) {\n return undefined;\n }\n const coreEnvelopeBuilder = new CoreEnvelopeBuilder().withStaticAttributes(\n this._staticAttributes\n );\n\n const messages: Map<Schema, LogMessage[]> = this._messageBuffers.extractAllMessages();\n messages.forEach((logs, schema) => {\n coreEnvelopeBuilder.withLogs(schemaUtil.getSchemaId(schema), logs);\n });\n\n if (this._metricsExtractors) {\n coreEnvelopeBuilder\n .withUpCounters(this._metricsExtractors.getAllUpCounters())\n .withValueRecorders(this._metricsExtractors.getAllValueRecorders());\n }\n\n const coreEnvelope: CoreEnvelope = coreEnvelopeBuilder.build();\n const errorMessage = this._coreEnvelopeType.verify(coreEnvelope);\n if (errorMessage) {\n throw new Error(`Invalid CoreEnvelope: ${errorMessage}`);\n }\n\n const encodedCoreEnvelope = this._coreEnvelopeType.encode(coreEnvelope).finish();\n return encodedCoreEnvelope;\n }\n\n receiveMetricsExtractors(metricsExtractors: MetricsExtractorMethods): void {\n this._metricsExtractors = metricsExtractors;\n }\n}\n","import {\n LogCollector,\n LogMeta,\n Metric,\n MetricsCollector,\n MetricsExtractorMethods,\n Schema\n} from '../../interfaces';\nimport { SchematizedData, MetricsTags, schemaUtil, utility } from 'o11y/shared';\nimport { protobufUtil } from '../protobuf-util';\nimport { LogMessage } from '../core-collector/LogMessage';\nimport { EncodedSchematizedPayload } from '../EncodedSchematizedPayload';\nimport { MetricTag } from '../metrics/MetricTag';\nimport { UpCounter } from '../metrics/UpCounter';\nimport { ValueRecorder } from '../metrics/ValueRecorder';\nimport { Metrics } from '../metrics/Metrics';\n\nconst metricsCollectionMilliseconds = 30000;\n\n// The observability plugin expects encoded payloads, so can't use LogMeta as-is.\ninterface LogMetaObservability {\n timestamp: number;\n rootId: string;\n sequence: number;\n loggerName: string;\n pagePayload: EncodedSchematizedPayload;\n loggerAppName: string;\n connectionType: string;\n appPayload: EncodedSchematizedPayload;\n}\n\n// The following interface is expected to be fulfilled by the\n// observability plugin in Lightning SDK.\ndeclare type NimbusObservabilityPlugin = {\n // Called to send a collected message to native for handling\n log: (schema: string, encodedMessage: Uint8Array, logMeta: LogMetaObservability) => void;\n\n // Called to send metrics to native for handling\n logMetrics: (metrics: Metrics) => void;\n\n // Called to listen for root activity changes in native.\n //\n // The startListener is called with the id of the root activity when an activity is started\n // The stopListener is called when a root activity is stopped\n addRootActivityListeners: (\n startListener: (activityInfo: { id: string }) => void,\n stopListener: () => void\n ) => void;\n\n // Called to inform native that the web view has detected an idle state.\n idleDetected: (timestamp: number) => void;\n};\n\n// The `HybridCollector` uses nimbus to send log data immediately across\n// to be handled by the native observability library.\nexport class HybridCollector implements LogCollector, MetricsCollector {\n private readonly _observability: NimbusObservabilityPlugin;\n private _metricsExtractors: MetricsExtractorMethods;\n\n constructor() {\n if (typeof __nimbus === 'undefined') {\n throw new Error('Nimbus is unavailable');\n }\n if (!__nimbus.plugins || !__nimbus.plugins.observability) {\n throw new Error('Observability plugin not found in Nimbus plugins');\n }\n this._observability = __nimbus.plugins.observability as NimbusObservabilityPlugin;\n setInterval(() => {\n this._collectMetrics();\n }, metricsCollectionMilliseconds);\n }\n\n collect(schema: Schema, data: SchematizedData, logMeta: LogMeta): void {\n if (schemaUtil.isInternal(schema) && data.userPayload) {\n data.userPayload = protobufUtil.encodePayload(data.userPayload);\n }\n const logMessage: LogMessage = protobufUtil.getLogMessage(schema, data, logMeta);\n const logMetaObs: LogMetaObservability = {\n timestamp: logMeta.timestamp,\n rootId: logMeta.rootId,\n sequence: logMeta.sequence,\n loggerName: logMeta.loggerName,\n pagePayload: logMessage.pagePayload,\n loggerAppName: logMeta.loggerAppName,\n connectionType: logMeta.connectionType,\n appPayload: logMessage.appPayload\n };\n this._observability.log(schemaUtil.getSchemaId(schema), logMessage.data, logMetaObs);\n }\n\n receiveMetricsExtractors(metricsExtractors: MetricsExtractorMethods): void {\n this._metricsExtractors = metricsExtractors;\n }\n\n // An app can call this method to listen for root activities that start and stop\n // on the native side, in order to associate web activities with the same root id.\n addRootActivityListeners(\n activityStarted: (info: { id: string }) => void,\n activityEnded: () => void\n ): void {\n utility.requireArgument(activityStarted, 'activityStarted', 'function');\n utility.requireArgument(activityEnded, 'activityEnded', 'function');\n\n this._observability.addRootActivityListeners(activityStarted, activityEnded);\n }\n\n // An app should call this method when it detects idle in the web view in order\n // to inform the native app of the idle state.\n notifyIdleDetected(timestamp: number): void {\n this._observability.idleDetected(timestamp);\n }\n\n private _collectMetrics(): void {\n if (this._metricsExtractors) {\n const upCounters: Metric<number>[] = this._metricsExtractors.getAllUpCounters();\n const valueRecorders: Metric<number[]>[] =\n this._metricsExtractors.getAllValueRecorders();\n\n const recorders: ValueRecorder[] = [];\n const counters: UpCounter[] = [];\n\n for (const valueRecorder of valueRecorders) {\n const vr: ValueRecorder = {\n name: valueRecorder.getName(),\n createdTimestamp: valueRecorder.getCreatedOn(),\n lastUpdatedTimestamp: valueRecorder.getLastUpdatedOn(),\n values: valueRecorder.getData(),\n ownerName: valueRecorder.getOwnerName(),\n ownerAppName: valueRecorder.getOwnerAppName(),\n tags: this._getMetricTags(valueRecorder)\n };\n recorders.push(vr);\n valueRecorder.reset();\n }\n\n for (const upCounter of upCounters) {\n const uc: UpCounter = {\n name: upCounter.getName(),\n createdTimestamp: upCounter.getCreatedOn(),\n lastUpdatedTimestamp: upCounter.getLastUpdatedOn(),\n value: upCounter.getData(),\n ownerName: upCounter.getOwnerName(),\n ownerAppName: upCounter.getOwnerAppName(),\n tags: this._getMetricTags(upCounter)\n };\n counters.push(uc);\n upCounter.reset();\n }\n\n if (recorders.length > 0 || counters.length > 0) {\n const metrics: Metrics = {\n upCounters: counters,\n valueRecorders: recorders\n };\n this._observability.logMetrics(metrics);\n }\n }\n }\n\n private _getMetricTags<T>(metric: Metric<T>): MetricTag[] {\n const metricsTags: MetricsTags = metric.getTags();\n\n if (metricsTags) {\n return Object.entries(metricsTags).map((entry) => {\n const mt: MetricTag = {\n name: entry[0],\n value: entry[1].toString()\n };\n return mt;\n });\n }\n return [];\n }\n}\n"],"names":["activity","namespace","name","pbjsSchema","nested","sf","instrumentation","Activity","reserved","fields","duration","options","id","type","stopReason","isRoot","(meta.max_length)","isSampled","preRootId","userPayload","errorCount","Payload","payload","schemaName","core_envelope","MessageBundle","messages","rule","Metrics","valueRecorders","upCounters","CoreEnvelopeDiagnostics","schemaVersion","generatedTimestamp","bundleCount","upCounterCount","valueRecorderCount","key","LogMessage","appPayload","data","rootId","pagePayload","loggerAppName","loggerName","connectionType","age","seq","timestamp","CoreEnvelope","(meta.msg.desc)","diagnostics","bundles","metrics","staticAttributes","MetricTag","value","ValueRecorder","lastUpdatedTimestamp","ownerName","ownerAppName","createdTimestamp","values","tags","StaticAttributes","appVersion","appName","deviceModel","sdkVersion","deviceId","appExperience","UpCounter","error","Error","activityId","stack","message","instrumented_event","MouseEvent","cancelable","ctrlKey","button","offsetX","eventPhase","shiftKey","offsetY","composed","altKey","isTrusted","buttons","movementY","clientY","clientX","movementX","defaultPrevented","metaKey","timeStamp","bubbles","detail","pageY","pageX","screenX","screenY","InstrumentedEvent","oneofs","event","oneof","mouseEvent","auto","parentComponent","ownerComponent","simplePath","simple","Simple","text","version","coreEnvelopeKey","CoreEnvelopeBuilder","[object Object]","this","_envelope","undefined","logs","msgBundle","find","bundle","log","push","length","metric","getTags","Object","entries","map","entry","toString","getName","getCreatedOn","getLastUpdatedOn","getData","getOwnerName","getOwnerAppName","_getMetricTags","reset","utility","time","tsNow","__protobufjs","PublicSafety","_errorCounter","fn","err","_prodSafeCatch","noopValue","requireArgument","allowThrow","isProduction","_safeCatchMode","increment","errorText","internalError","console","defaultTraceIdLengthW3","defaultTraceIdLengthB3","defaultSpanIdLength","headerTraceParent","headerB3","headerTraceId","headerSpanId","headerSampled","headerParentSpanId","defaultActivityNameForFetch","defaultActivityNameForXhrSend","Tracing","instr","traceId","spanId","parentSpanId","b3","numChars","len","toLowerCase","i","c","substr","padStart","useB3Headers","_conformTextAsId","traceIdEffectiveLength","headers","useCompactHeader","_getB3CompactFormat","_getW3CompactFormat","_isNetworkInstrumentationEnabled","_originalFetch","_global","fetch","_originalXhr","XMLHttpRequest","_originalXhrSend","prototype","send","logErrors","activityName","useTracing","_overrideFetch","_overrideXhr","async","url","reqOptions","restArgs","startActivity","traceHeaders","getTraceHeaders","assign","call","ex","stop","args","xhr","_o11yActivity","forEach","setRequestHeader","xhrProxy","Proxy","target","newXhr","addEventListener","__err","discard","_disableNetworkInstrumentation","tracingOptions","_enableNetworkInstrumentation","definedValueOrDefault","tracingHeadersOptions","getGlobal","timedout","terminated","discarded","ActivityImpl","_name","_rootId","_onStopped","_onError","timeout","_isSampled","perfNow","_count","_id","generateUniqueId","_usePerf","performance","mark","measure","_perfName","_perfId","_startTimestamp","_startPerfTime","_timer","setTimeout","_stopReason","_safety","userSchemaOrText","userData","tryCatch","_errorCount","_getDetail","_stopInternal","stopPerfTime","clearMarks","clearMeasures","clearTimeout","isStopped","_stopPerfTime","activityDetail","startTimestamp","startPerfTime","getIsSampled","getHeaders","Array","fill","join","ActivityNoOp","__options","activityNoOp","freeze","DomEventHelpers","eventData","handledBy","instrumentedEvent","tagName","parentElement","getXpath","schemaUtil","makePayload","schema","e","singleton","domEventHelpers","maxFieldLength","minFieldLength","maxFourBytesPos","maxFourBytesNeg","maxFourBytesUnsigned","maxEightBytesPos","maxEightBytesNeg","maxEightBytesUnsigned","LogValidator","schemaTokens","checkSchema","nestedSchema","getTypes","errorMessage","validateFields","getSchemaId","custom","schemaId","isNullOrUndefinedOrEmpty","matchFieldTypes","val","fieldData","fieldType","descriptor","convertedSchemaType","extraContext","isArray","index","Uint8Array","checkNumberRange","Number","isFinite","ref","keys","x","fieldLength","max","min","logValidator","UpCounterImpl","_ownerName","_ownerAppName","_tags","_createdOn","_lastUpdatedOn","_value","Math","round","ValueRecorderImpl","_values","slice","SizeLimitedMap","maxSize","Map","_maxSize","ceil","_map","get","has","size","set","from","clear","maxCounters","maxValueRecorders","MetricType","MetricsImpl","operation","hasError","_tagError","_upCounter","_valueRecorder","record","sortedTags","_getKeyAndSortedTags","Counter","instrument","_upCounters","Percentile","_valueRecorders","getElements","status","metricType","sort","reduce","prev","curr","JSON","stringify","MockEvent","_composedPaths","maxActivityDurationMsecs","reservedMetricCharacters","reservedMetricNames","denyListMetricNames","InstrumentationImpl","_nextGen","_handleActivityStop","bind","_handleActivityError","reservedChar","indexOf","_incrementError","_metrics","simpleTextOptions","getOptions","simpleSchema","_simpleTextMaxLength","MAX_VALUE","incrementCounter","onlyIfBoth","userSchema","_wrapUserPayload","_logInternal","getRootActivityId","_checkInputs","_getPayloadFromProvider","appPayloadProvider","pagePayloadProvider","addLog","_errorInternal","loggedTimestamp","errorData","errorSchema","tryCatchReturn","_onActivityStoppedCallback","_onActivityErrorCallback","isRootActivitySampled","activityData","_getActivityData","_logActivity","activitySchema","provider","getPayload","htmlElement","Event","HTMLElement","template","host","acd","getClickTracker","markEventHandled","mouseEventData","getMouseEventData","getInstrumentedEventData","instrumentedEventSchema","notImplemented","checkForDenyListedValues","checkForReservedCharacters","trackValue","savedUserPayload","isInternal","validate","getUpCounters","filter","m","getValueRecorders","RootActivityImpl","onStopped","onError","super","_preRootId","RootActivityNoOp","rootActivityNoOp","AppInstrumentationImpl","handleRootActivityStop","newRootActivity","_onRootActivityStoppedCallback","rootActivity","getId","terminate","pathLimit","AutomaticClickTracker","document","clickListener","isActive","_boundClickListener","removeEventListener","ignoredEvent","eventTargets","composedPath","path","getClickableElement","domEvent","limit","currentElement","inputElement","maxInstrumentationLength","truncatedText","maxInstrumentationLengthBeforeTruncated","NextgenImpl","Set","_pagePayloadProvider","_appPayloadProvider","enableBuffering","_appInstr","_instruments","_isBufferingEnabled","tracing","networkInstrumentation","startRootActivity","registerLogCollector","registerMetricsCollector","activateClickTracker","deactivateClickTracker","disableBuffering","_sequence","logMeta","sequence","getConnectionType","_buffer","clone","collector","_logCollectors","dataClone","failures","_logCollectorFailures","_forceDisabledLogCollectors","getIsCollectDisabled","collect","_collectorFailureLimit","add","_autoClickTracker","window","activate","deactivate","retroactive","_metricsCollector","receiveMetricsExtractors","getAllUpCounters","getAllValueRecorders","pv","cv","concat","Index","_lazyNextGen","_nextgen","markProduction","retVal","registerApp","getInstrumentation","registerInstrumentedApp","metricsCollectionMilliseconds","HybridCollector","__nimbus","plugins","observability","_observability","setInterval","_collectMetrics","protobufUtil","encodePayload","logMessage","getLogMessage","logMetaObs","metricsExtractors","_metricsExtractors","activityStarted","activityEnded","addRootActivityListeners","idleDetected","recorders","counters","valueRecorder","vr","upCounter","uc","logMetrics","metricsTags"],"mappings":";;;;;;6l7DAAO,MAAMA,SAAS,CAACC,UAAU,qBAAqBC,KAAK,WAAWC,WAAW,CAACC,OAAS,CAACC,GAAK,CAACD,OAAS,CAACE,gBAAkB,CAACF,OAAS,CAACG,SAAW,CAACC,SAAW,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,IAAIC,OAAS,CAACC,SAAW,CAACC,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUC,WAAa,CAACH,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUE,OAAS,CAACJ,QAAU,GAAGC,GAAK,EAAEC,KAAO,QAAQX,KAAO,CAACS,QAAU,CAACK,oBAAoB,IAAIJ,GAAK,EAAEC,KAAO,UAAUI,UAAY,CAACN,QAAU,GAAGC,GAAK,GAAGC,KAAO,QAAQK,UAAY,CAACP,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUD,GAAK,CAACD,QAAU,GAC/fC,GAAK,EAAEC,KAAO,UAAUM,YAAc,CAACR,QAAU,GAAGC,GAAK,EAAEC,KAAO,WAAWO,WAAa,CAACT,QAAU,GAAGC,GAAK,GAAGC,KAAO,YAAYQ,QAAU,CAACZ,OAAS,CAACa,QAAU,CAACX,QAAU,GAAGC,GAAK,EAAEC,KAAO,SAASU,WAAa,CAACZ,QAAU,GAAGC,GAAK,EAAEC,KAAO,mBCDnOW,cAAc,CAACvB,UAAU,qBAAqBC,KAAK,eAAeC,WAAW,CAACC,OAAS,CAACC,GAAK,CAACD,OAAS,CAACE,gBAAkB,CAACF,OAAS,CAACqB,cAAgB,CAAChB,OAAS,CAACiB,SAAW,CAACf,QAAU,GAAGgB,KAAO,WAAWf,GAAK,EAAEC,KAAO,cAAcU,WAAa,CAACZ,QAAU,GAAGC,GAAK,EAAEC,KAAO,YAAYe,QAAU,CAACnB,OAAS,CAACoB,eAAiB,CAAClB,QAAU,GAAGgB,KAAO,WAAWf,GAAK,EA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,GAAKib,EAASjb,OAAS,EAAG,CAC7C,MAAM3E,EAAmB,CACrBvB,WAAYmhB,EACZphB,eAAgBmhB,GAEpBzb,KAAK2a,eAAeoB,WAAWjgB,KAKnCiE,eAAkBW,GACtB,MAAMsb,EAA2Btb,EAAOC,UAExC,OAAIqb,EACOpb,OAAOC,QAAQmb,GAAalb,KAAKC,IACd,CAClBpI,KAAMoI,EAAM,GACZ9E,MAAO8E,EAAM,GAAGC,eAKrB"}
1
+ {"version":3,"file":"collectors.js","sources":["../../../../../../node_modules/o11y_schema/sf_instrumentation/activity.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/core_envelope.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/error.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/instrumented_event.js","../../../../../../node_modules/o11y_schema/sf_instrumentation/simple.js","../../../../../../node_modules/o11y_schema/version/version.js","../../../../src/collectors/core-collector/CoreEnvelopeBuilder.ts","../../../../src/collectors/protobuf-util.ts","../../../../src/library/PublicSafety.ts","../../../../src/library/Tracing.ts","../../../../src/library/ActivityImpl.ts","../../../../src/library/ActivityNoOp.ts","../../../../src/library/DomEventHelpers.ts","../../../../src/library/LogValidator.ts","../../../../src/library/UpCounterImpl.ts","../../../../src/library/ValueRecorderImpl.ts","../../../../src/library/SizeLimitedMap.ts","../../../../src/library/MetricsImpl.ts","../../../../src/library/MockEvent.ts","../../../../src/library/InstrumentationImpl.ts","../../../../src/library/RootActivityImpl.ts","../../../../src/library/RootActivityNoOp.ts","../../../../src/library/AppInstrumentationImpl.ts","../../../../src/library/AutomaticClickTracker.ts","../../../../src/library/NextgenImpl.ts","../../../../src/index.ts","../../../../src/collectors/core-collector/CoreCollector.ts","../../../../src/collectors/hybrid-collector/HybridCollector.ts"],"sourcesContent":["export const activity={namespace:\"sf.instrumentation\",name:\"Activity\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Activity\":{\"reserved\":[[5,5],[7,7]],\"fields\":{\"duration\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"stopReason\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"isRoot\":{\"options\":{},\"id\":8,\"type\":\"bool\"},\"name\":{\"options\":{\"(meta.max_length)\":25},\"id\":2,\"type\":\"string\"},\"isSampled\":{\"options\":{},\"id\":11,\"type\":\"bool\"},\"preRootId\":{\"options\":{},\"id\":9,\"type\":\"string\"},\"id\":{\"options\":{},\n\"id\":1,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":4,\"type\":\"Payload\"},\"errorCount\":{\"options\":{},\"id\":10,\"type\":\"uint32\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const core_envelope={namespace:\"sf.instrumentation\",name:\"CoreEnvelope\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"MessageBundle\":{\"fields\":{\"messages\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"LogMessage\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"Metrics\":{\"fields\":{\"valueRecorders\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"ValueRecorder\"},\"upCounters\":{\"options\":{},\"rule\":\"repeated\",\"id\":1,\"type\":\"UpCounter\"}}},\"CoreEnvelopeDiagnostics\":{\"fields\":{\"schemaVersion\":{\"options\":{},\n\"id\":6,\"type\":\"string\"},\"generatedTimestamp\":{\"options\":{},\"id\":2,\"type\":\"double\"},\"bundleCount\":{\"options\":{},\"id\":3,\"type\":\"uint32\"},\"upCounterCount\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"valueRecorderCount\":{\"options\":{},\"id\":5,\"type\":\"uint32\"},\"key\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"LogMessage\":{\"fields\":{\"appPayload\":{\"options\":{},\"id\":10,\"type\":\"Payload\"},\"data\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"rootId\":{\"options\":{},\"id\":4,\"type\":\"string\"},\"pagePayload\":{\"options\":{},\"id\":7,\"type\":\"Payload\"},\n\"loggerAppName\":{\"options\":{},\"id\":8,\"type\":\"string\"},\"loggerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"connectionType\":{\"options\":{},\"id\":9,\"type\":\"string\"},\"age\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"seq\":{\"options\":{},\"id\":5,\"type\":\"uint32\"},\"timestamp\":{\"options\":{},\"id\":1,\"type\":\"double\"}}},\"CoreEnvelope\":{\"options\":{\"(meta.msg.desc)\":\"This message is used to contain data that the Core ui-telemetry Connect API endpoint accepts.\"},\"fields\":{\"diagnostics\":{\"options\":{},\"id\":1,\"type\":\"CoreEnvelopeDiagnostics\"},\n\"bundles\":{\"options\":{},\"rule\":\"repeated\",\"id\":2,\"type\":\"MessageBundle\"},\"metrics\":{\"options\":{},\"id\":3,\"type\":\"Metrics\"},\"staticAttributes\":{\"options\":{},\"id\":4,\"type\":\"StaticAttributes\"}}},\"MetricTag\":{\"fields\":{\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"value\":{\"options\":{},\"id\":2,\"type\":\"string\"}}},\"ValueRecorder\":{\"fields\":{\"lastUpdatedTimestamp\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"ownerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"ownerAppName\":{\"options\":{},\"id\":7,\"type\":\"string\"},\"createdTimestamp\":{\"options\":{},\n\"id\":2,\"type\":\"double\"},\"values\":{\"options\":{},\"rule\":\"repeated\",\"id\":4,\"type\":\"double\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"tags\":{\"options\":{},\"rule\":\"repeated\",\"id\":5,\"type\":\"MetricTag\"}}},\"StaticAttributes\":{\"fields\":{\"appVersion\":{\"options\":{},\"id\":2,\"type\":\"string\"},\"appName\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"deviceModel\":{\"options\":{},\"id\":5,\"type\":\"string\"},\"sdkVersion\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"deviceId\":{\"options\":{},\"id\":4,\"type\":\"string\"},\"appExperience\":{\"options\":{},\n\"id\":3,\"type\":\"string\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}},\"UpCounter\":{\"fields\":{\"lastUpdatedTimestamp\":{\"options\":{},\"id\":3,\"type\":\"double\"},\"ownerName\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"ownerAppName\":{\"options\":{},\"id\":7,\"type\":\"string\"},\"createdTimestamp\":{\"options\":{},\"id\":2,\"type\":\"double\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"value\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"tags\":{\"options\":{},\n\"rule\":\"repeated\",\"id\":5,\"type\":\"MetricTag\"}}}}}}}}}};","export const error={namespace:\"sf.instrumentation\",name:\"Error\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Error\":{\"reserved\":[[5,5],[7,7]],\"fields\":{\"activityId\":{\"options\":{},\"id\":6,\"type\":\"string\"},\"stack\":{\"options\":{},\"id\":3,\"type\":\"string\"},\"name\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"message\":{\"options\":{\"(meta.max_length)\":200},\"id\":2,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":4,\"type\":\"Payload\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\n\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const instrumented_event={namespace:\"sf.instrumentation\",name:\"InstrumentedEvent\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"MouseEvent\":{\"fields\":{\"cancelable\":{\"options\":{},\"id\":5,\"type\":\"bool\"},\"ctrlKey\":{\"options\":{},\"id\":9,\"type\":\"bool\"},\"type\":{\"options\":{},\"id\":25,\"type\":\"string\"},\"button\":{\"options\":{},\"id\":3,\"type\":\"uint32\"},\"offsetX\":{\"options\":{},\"id\":17,\"type\":\"uint32\"},\"eventPhase\":{\"options\":{},\"id\":12,\"type\":\"uint32\"},\"shiftKey\":{\"options\":{},\"id\":23,\n\"type\":\"bool\"},\"offsetY\":{\"options\":{},\"id\":18,\"type\":\"uint32\"},\"composed\":{\"options\":{},\"id\":8,\"type\":\"bool\"},\"altKey\":{\"options\":{},\"id\":1,\"type\":\"bool\"},\"isTrusted\":{\"options\":{},\"id\":13,\"type\":\"bool\"},\"buttons\":{\"options\":{},\"id\":4,\"type\":\"uint32\"},\"movementY\":{\"options\":{},\"id\":16,\"type\":\"uint32\"},\"clientY\":{\"options\":{},\"id\":7,\"type\":\"uint32\"},\"clientX\":{\"options\":{},\"id\":6,\"type\":\"uint32\"},\"movementX\":{\"options\":{},\"id\":15,\"type\":\"uint32\"},\"defaultPrevented\":{\"options\":{},\"id\":10,\"type\":\"bool\"},\n\"metaKey\":{\"options\":{},\"id\":14,\"type\":\"bool\"},\"timeStamp\":{\"options\":{},\"id\":24,\"type\":\"double\"},\"bubbles\":{\"options\":{},\"id\":2,\"type\":\"bool\"},\"detail\":{\"options\":{},\"id\":11,\"type\":\"int64\"},\"pageY\":{\"options\":{},\"id\":20,\"type\":\"uint32\"},\"pageX\":{\"options\":{},\"id\":19,\"type\":\"uint32\"},\"screenX\":{\"options\":{},\"id\":21,\"type\":\"uint32\"},\"screenY\":{\"options\":{},\"id\":22,\"type\":\"uint32\"}}},\"InstrumentedEvent\":{\"oneofs\":{\"event\":{\"oneof\":[\"mouseEvent\"]}},\"reserved\":[[4,4],\"xpath\",[6,6],[8,8]],\"fields\":{\"mouseEvent\":{\"options\":{},\n\"id\":7,\"type\":\"MouseEvent\"},\"auto\":{\"options\":{},\"id\":3,\"type\":\"bool\"},\"parentComponent\":{\"options\":{},\"id\":2,\"type\":\"string\"},\"ownerComponent\":{\"options\":{},\"id\":1,\"type\":\"string\"},\"userPayload\":{\"options\":{},\"id\":5,\"type\":\"Payload\"},\"simplePath\":{\"options\":{},\"id\":9,\"type\":\"string\"}}},\"Payload\":{\"fields\":{\"payload\":{\"options\":{},\"id\":2,\"type\":\"bytes\"},\"schemaName\":{\"options\":{},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const simple={namespace:\"sf.instrumentation\",name:\"Simple\",pbjsSchema:{\"nested\":{\"sf\":{\"nested\":{\"instrumentation\":{\"nested\":{\"Simple\":{\"options\":{\"(meta.msg.desc)\":\"This message is used internally to allow convenient logging of simple text via the API without requiring a schema.\"},\"fields\":{\"text\":{\"options\":{\"(meta.max_length)\":25},\"id\":1,\"type\":\"string\"}}}}}}}}}};","export const version='2.10.0'","import { Metric } from '../../interfaces';\nimport { MetricsTags, utility } from 'o11y/shared';\nimport { CoreEnvelope } from './CoreEnvelope';\nimport { LogMessage } from './LogMessage';\nimport { MessageBundle } from './MessageBundle';\nimport { StaticAttributes } from './StaticAttributes';\nimport { UpCounter } from '../metrics/UpCounter';\nimport { ValueRecorder } from '../metrics/ValueRecorder';\nimport { version as schemaVersion } from 'o11y_schema/version';\nimport { MetricTag } from '../metrics/MetricTag';\n\nexport const coreEnvelopeKey = 'o11y';\nexport class CoreEnvelopeBuilder {\n private _envelope: CoreEnvelope;\n\n constructor() {\n this._envelope = {\n diagnostics: {\n key: coreEnvelopeKey,\n generatedTimestamp: undefined,\n bundleCount: 0,\n upCounterCount: 0,\n valueRecorderCount: 0,\n schemaVersion\n },\n bundles: [] as MessageBundle[],\n metrics: {\n upCounters: [] as UpCounter[],\n valueRecorders: [] as ValueRecorder[]\n },\n staticAttributes: {}\n };\n }\n\n withStaticAttributes(staticAttributes: StaticAttributes): CoreEnvelopeBuilder {\n this._envelope.staticAttributes = staticAttributes;\n return this;\n }\n\n withLogs(schemaName: string, logs: LogMessage[]): CoreEnvelopeBuilder {\n let msgBundle: MessageBundle = this._envelope.bundles.find(\n (bundle) => bundle.schemaName === schemaName\n );\n\n if (msgBundle) {\n for (const log of logs) {\n msgBundle.messages.push(log);\n }\n } else {\n msgBundle = {\n schemaName: schemaName,\n messages: logs\n };\n this._envelope.bundles.push(msgBundle);\n }\n this._envelope.diagnostics.bundleCount = this._envelope.bundles.length;\n return this;\n }\n\n private _getMetricTags<T>(metric: Metric<T>): MetricTag[] {\n const tags: MetricsTags = metric.getTags();\n if (tags) {\n return Object.entries(tags).map((entry) => {\n const mt: MetricTag = {\n name: entry[0],\n value: entry[1].toString()\n };\n return mt;\n });\n }\n return undefined;\n }\n\n withUpCounters(metrics: Metric<number>[]): CoreEnvelopeBuilder {\n for (const metric of metrics) {\n const data: UpCounter = {\n name: metric.getName(),\n createdTimestamp: metric.getCreatedOn(),\n lastUpdatedTimestamp: metric.getLastUpdatedOn(),\n value: metric.getData(),\n ownerName: metric.getOwnerName(),\n ownerAppName: metric.getOwnerAppName(),\n tags: this._getMetricTags(metric)\n };\n this._envelope.metrics.upCounters.push(data);\n metric.reset();\n }\n this._envelope.diagnostics.upCounterCount = this._envelope.metrics.upCounters.length;\n return this;\n }\n\n withValueRecorders(metrics: Metric<number[]>[]): CoreEnvelopeBuilder {\n for (const metric of metrics) {\n const data: ValueRecorder = {\n name: metric.getName(),\n createdTimestamp: metric.getCreatedOn(),\n lastUpdatedTimestamp: metric.getLastUpdatedOn(),\n values: metric.getData(),\n ownerName: metric.getOwnerName(),\n ownerAppName: metric.getOwnerAppName(),\n tags: this._getMetricTags(metric)\n };\n this._envelope.metrics.valueRecorders.push(data);\n metric.reset();\n }\n this._envelope.diagnostics.valueRecorderCount =\n this._envelope.metrics.valueRecorders.length;\n return this;\n }\n\n build(): CoreEnvelope {\n this._envelope.diagnostics.generatedTimestamp = utility.time().tsNow;\n return this._envelope;\n }\n}\n","import { Message, Root, Type } from 'protobufjs';\n\nimport { LogMeta, Schema, SchematizedPayload } from '../interfaces';\nimport { EncodedSchematizedPayload } from './EncodedSchematizedPayload';\nimport { SchematizedData, schemaUtil, utility } from 'o11y/shared';\nimport { LogMessage } from './core-collector/LogMessage';\n\nclass ProtobufUtil {\n private readonly _typeStore = new Map<string, Type>();\n\n public getSchemaType(schema: Schema): Type {\n utility.requireArgument(schema, 'schema');\n const schemaPath = schemaUtil.getSchemaId(schema);\n let type = this._typeStore.get(schemaPath);\n\n if (!type) {\n // Lazy add to the type store\n const schemaInstance = Root.fromJSON(schema.pbjsSchema);\n // this will throw if it can't find it\n type = schemaInstance.lookupType(schemaPath);\n this._typeStore.set(schemaPath, type);\n }\n\n return type;\n }\n\n public validate(schema: Schema, data: SchematizedData): Type {\n utility.requireArgument(schema, 'schema');\n utility.requireArgument(data, 'data');\n const type: Type = this.getSchemaType(schema);\n\n const errorText = type.verify(data);\n if (errorText) {\n throw new Error(`Data is invalid for ${type.fullName}: ${errorText}`);\n }\n return type;\n }\n\n public encode(schema: Schema, data: SchematizedData): Uint8Array {\n const type: Type = this.validate(schema, data);\n const message: Message = type.fromObject(data);\n const encoded: Uint8Array = type.encode(message).finish();\n return encoded;\n }\n\n public encodePayload(rawPayload: SchematizedPayload): EncodedSchematizedPayload {\n if (rawPayload && rawPayload.schema && rawPayload.payload) {\n return {\n schemaName: schemaUtil.getSchemaId(rawPayload.schema),\n payload: this.encode(rawPayload.schema, rawPayload.payload)\n };\n }\n return undefined;\n }\n\n // This method generates a LogMessage (used in the CoreEnvelope) from the provided arguments.\n public getLogMessage(schema: Schema, data: SchematizedData, logMeta: LogMeta): LogMessage {\n return {\n timestamp: logMeta.timestamp,\n data: this.encode(schema, data),\n age: utility.getAge(logMeta.timestamp),\n rootId: logMeta.rootId,\n seq: logMeta.sequence,\n loggerName: logMeta.loggerName,\n pagePayload: this.encodePayload(logMeta.pagePayload),\n loggerAppName: logMeta.loggerAppName,\n connectionType: logMeta.connectionType,\n appPayload: this.encodePayload(logMeta.appPayload)\n };\n }\n}\n\nexport const protobufUtil = new ProtobufUtil();\n","import { UpCounter } from '../interfaces';\nimport { utility } from 'o11y/shared';\n\nexport class PublicSafety {\n private _safeCatchMode = false;\n\n constructor(private readonly _errorCounter?: UpCounter) {}\n\n /**\n * Instrumentation should never throw in production. Therefore, we need to include in\n * all our public methods a top-most try/catch wrapper. Simply use this function\n * as your first and only top-level call in the function block and sleep well at night.\n *\n * @param fn The body of the unsafe function that doesn't return a value but can throw\n */\n tryCatch(fn: () => void): void {\n try {\n fn();\n } catch (err) {\n this._prodSafeCatch(err);\n }\n }\n\n /**\n *\n * @param fn The body of the unsafe function that returns a value and that can throw\n * @param noopValue A static, noop instance of V (like a mock) that will be returned in case\n * the function could not be called.\n */\n tryCatchReturn<V>(fn: () => V, noopValue: V): V {\n try {\n utility.requireArgument(noopValue, 'noopValue');\n return fn();\n } catch (err) {\n this._prodSafeCatch(err);\n return noopValue;\n }\n }\n\n /**\n * Safely handles exceptions. Suppresses throws in a production environment.\n * This method is intended to be called inside a catch block.\n *\n * @param error The error that was caught\n */\n private _prodSafeCatch(error: unknown): void {\n let allowThrow;\n try {\n allowThrow = !utility.isProduction;\n if (allowThrow) {\n // Just throw the error in development\n throw error;\n }\n\n if (this._safeCatchMode) {\n // If we're here, that means code in the try block of prodSafeCatch itself is throwing an error\n // (i.e. prodSafeCatch is already on the stack). Break out now to prevent infinite loop.\n this._safeCatchMode = false;\n\n throw new Error('Internal error in prodSafeCatch.');\n }\n\n this._safeCatchMode = true;\n if (this._errorCounter) {\n this._errorCounter.increment();\n }\n\n if (!(error instanceof Error)) {\n const errorText =\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n (error && (error as any).message) ||\n (typeof error.toString === 'function' ? error.toString() : '');\n error = new Error(errorText);\n }\n\n // If not allowed to throw the error, at least try to log it\n // TODO: This error should be attributed to the global Instrumentation (not to \"this\")\n // this.error(error);\n this._safeCatchMode = false;\n } catch (internalError) {\n // Do not call any methods in this catch block except for console.error\n\n if (allowThrow) {\n // pass it along\n throw internalError;\n }\n\n // eslint-disable-next-line no-console\n if (internalError && console && typeof console.error === 'function') {\n try {\n // eslint-disable-next-line no-console\n console.error(internalError);\n } catch {\n // Nothing we can do at this point\n }\n }\n this._safeCatchMode = false;\n }\n }\n}\n","import {\n Instrumentation,\n TracingHeadersOptions,\n NetworkInstrumentationOptions,\n Activity\n} from '../interfaces';\nimport { utility } from 'o11y/shared';\n\ntype FetchType = (input: RequestInfo, init?: RequestInit) => Promise<Response>;\ntype XhrType = {\n prototype: XMLHttpRequest;\n new (): XMLHttpRequest;\n readonly DONE: number;\n readonly HEADERS_RECEIVED: number;\n readonly LOADING: number;\n readonly OPENED: number;\n readonly UNSENT: number;\n};\ntype XhrSendType = (body?: Document | BodyInit | null) => void;\ninterface O11yXhr extends XMLHttpRequest {\n _o11yActivity: Activity;\n}\n\nconst defaultTraceIdLengthW3 = 32; // 32 Characters = 128 bits\nconst defaultTraceIdLengthB3 = 16; // 16 Characters = 64 bits\nconst defaultSpanIdLength = 16; // 16 Characters = 64 bits\n\n// Headers for W3 tracing (https://www.w3.org/TR/trace-context/#traceparent-header)\nconst headerTraceParent = 'traceparent';\n\n// Headers for B3 tracing (https://github.com/openzipkin/b3-propagation)\nconst headerB3 = 'b3';\nconst headerTraceId = 'X-B3-TraceId';\nconst headerSpanId = 'X-B3-SpanId';\nconst headerSampled = 'X-B3-Sampled';\nconst headerParentSpanId = 'X-B3-ParentSpanId';\n\nconst defaultActivityNameForFetch = 'fetch';\nconst defaultActivityNameForXhrSend = 'xhr_send';\n\nexport class Tracing {\n private static _global = utility.getGlobal();\n private static _originalFetch: FetchType;\n private static _originalXhr: XhrType;\n private static _originalXhrSend: XhrSendType;\n private static _isNetworkInstrumentationEnabled = false;\n\n constructor(private readonly instr: Instrumentation) {\n utility.requireArgument(instr, 'instr', 'object');\n }\n\n private static _getB3CompactFormat(\n traceId: string,\n spanId: string,\n isSampled?: boolean,\n parentSpanId?: string\n ): string {\n // b3={TraceId}-{SpanId}-{SamplingState}-{ParentSpanId}\n // Note: last two fields are optional\n\n let b3 = `${traceId}-${spanId}`;\n\n if (isSampled !== undefined || parentSpanId !== undefined) {\n b3 += isSampled ? '-1' : '-0';\n if (parentSpanId !== undefined) {\n b3 += `-${parentSpanId}`;\n }\n }\n return b3;\n }\n\n private static _getW3CompactFormat(\n traceId: string,\n spanId: string,\n isSampled: boolean\n ): string {\n // traceparent={version}-{trace-id}-{parent-id}-{trace-flags}\n // \"in some tracing systems, parent-id is known as the span-id, where a span is the execution of a client request\"\n return `00-${traceId}-${spanId}-${isSampled ? '01' : '00'}`;\n }\n\n private static _conformTextAsId(text: string, numChars: number): string {\n // First validate\n text = text.toLowerCase();\n const len: number = text.length;\n for (let i = 0; i < len; i += 1) {\n const c = text[i];\n if (!(c >= 'a' && c <= 'f') && !(c >= '0' && c <= '9')) {\n throw new Error(`The text '${text}' has an invalid character at index #${i}`);\n }\n }\n\n if (len > numChars) {\n // Use the right-most characters per spec\n return text.substr(len - numChars);\n }\n if (len < numChars) {\n // Pad left with 0s per spec\n return text.padStart(numChars, '0');\n }\n return text;\n }\n\n public static getHeaders(\n traceId: string,\n spanId: string,\n isSampled?: boolean,\n options?: TracingHeadersOptions\n ): Record<string, string> {\n utility.requireArgument(traceId, 'traceId', 'string');\n utility.requireArgument(spanId, 'spanId', 'string');\n\n const useB3Headers: boolean = options && options.useB3Headers;\n\n traceId = this._conformTextAsId(\n traceId,\n options && options.traceIdEffectiveLength !== undefined\n ? options.traceIdEffectiveLength\n : useB3Headers\n ? defaultTraceIdLengthB3\n : defaultTraceIdLengthW3\n );\n spanId = this._conformTextAsId(spanId, defaultSpanIdLength);\n\n const parentSpanId =\n (options &&\n options.parentSpanId !== undefined &&\n this._conformTextAsId(options.parentSpanId, defaultSpanIdLength)) ||\n undefined;\n\n const headers: Record<string, string> = {};\n\n if (useB3Headers) {\n // By default, use non-compact\n const isCompact: boolean = options && options.useCompactHeader;\n if (isCompact) {\n headers[headerB3] = this._getB3CompactFormat(\n traceId,\n spanId,\n isSampled,\n parentSpanId\n );\n } else {\n headers[headerTraceId] = traceId;\n headers[headerSpanId] = spanId;\n if (parentSpanId !== undefined) {\n headers[headerParentSpanId] = parentSpanId;\n }\n if (isSampled !== undefined) {\n headers[headerSampled] = isSampled ? '1' : '0';\n }\n }\n } else {\n headers[headerTraceParent] = this._getW3CompactFormat(traceId, spanId, isSampled);\n }\n\n return headers;\n }\n\n private _disableNetworkInstrumentation(): void {\n if (Tracing._isNetworkInstrumentationEnabled) {\n if (Tracing._originalFetch) {\n Tracing._global.fetch = Tracing._originalFetch;\n Tracing._originalFetch = undefined;\n }\n if (Tracing._originalXhr) {\n Tracing._global.XMLHttpRequest = Tracing._originalXhr;\n Tracing._originalXhr = undefined;\n }\n if (Tracing._originalXhrSend) {\n Tracing._global.XMLHttpRequest.prototype.send = Tracing._originalXhrSend;\n Tracing._originalXhrSend = undefined;\n }\n Tracing._isNetworkInstrumentationEnabled = false;\n }\n }\n\n private _enableNetworkInstrumentation(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n if (typeof Tracing._global.fetch === 'function') {\n this._overrideFetch(instr, logErrors, activityName, useTracing, options);\n Tracing._isNetworkInstrumentationEnabled = true;\n }\n\n if (typeof Tracing._global.XMLHttpRequest === 'function') {\n this._overrideXhr(instr, logErrors, activityName, useTracing, options);\n Tracing._isNetworkInstrumentationEnabled = true;\n }\n }\n\n private _overrideFetch(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n Tracing._originalFetch = Tracing._global.fetch;\n const o11yFetch: FetchType = async (url, reqOptions, ...restArgs) => {\n let activity: Activity;\n try {\n activity = instr.startActivity(activityName || defaultActivityNameForFetch);\n\n if (useTracing) {\n reqOptions = reqOptions || {};\n const traceHeaders = activity.getTraceHeaders(options);\n reqOptions.headers = Object.assign(reqOptions.headers || {}, traceHeaders);\n }\n return await Tracing._originalFetch.call(\n Tracing._global,\n url,\n reqOptions,\n ...restArgs\n );\n } catch (ex) {\n if (logErrors) {\n if (activity) {\n activity.error(ex);\n } else {\n instr.error(ex);\n }\n }\n throw ex;\n } finally {\n if (activity) {\n activity.stop();\n }\n }\n };\n Tracing._global.fetch = o11yFetch;\n }\n\n private _overrideXhr(\n instr: Instrumentation,\n logErrors: boolean,\n activityName: string,\n useTracing: boolean,\n options: TracingHeadersOptions\n ): void {\n Tracing._originalXhr = Tracing._global.XMLHttpRequest;\n Tracing._originalXhrSend = Tracing._originalXhr.prototype.send;\n\n Tracing._originalXhr.prototype.send = function (this: O11yXhr, ...args) {\n let activity: Activity;\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr: O11yXhr = this;\n try {\n xhr._o11yActivity = activity = instr.startActivity(\n activityName || defaultActivityNameForXhrSend\n );\n if (useTracing) {\n const headers = activity.getTraceHeaders(options);\n\n Object.entries(headers).forEach((entry) => {\n xhr.setRequestHeader(entry[0], entry[1]);\n });\n }\n Tracing._originalXhrSend.call(this, ...args);\n } catch (ex) {\n if (logErrors) {\n if (activity) {\n activity.error(ex);\n } else {\n instr.error(ex);\n }\n }\n if (activity) {\n activity.stop();\n }\n throw ex;\n }\n };\n\n const xhrProxy = new Proxy<XhrType>(Tracing._originalXhr, {\n construct(target: XhrType) {\n const newXhr = new target() as O11yXhr;\n\n // Be the first in the event chain\n newXhr.addEventListener('load', () => {\n const activity = newXhr._o11yActivity;\n if (activity) {\n activity.stop();\n }\n });\n newXhr.addEventListener(\n 'error',\n (__err: ProgressEvent<XMLHttpRequestEventTarget>) => {\n const error = new Error('XHR Network-Level Error');\n const activity = newXhr._o11yActivity;\n if (activity) {\n if (logErrors) {\n activity.error(error);\n }\n activity.stop();\n } else if (logErrors) {\n instr.error(error);\n }\n }\n );\n newXhr.addEventListener('abort', () => {\n const activity = newXhr._o11yActivity;\n if (activity) {\n activity.discard();\n }\n });\n return newXhr;\n }\n });\n\n Tracing._global.XMLHttpRequest = xhrProxy;\n }\n\n networkInstrumentation(options: boolean | NetworkInstrumentationOptions): void {\n utility.requireArgument(options, 'options', ['boolean', 'object']);\n\n if (options) {\n // First disable it if necessary, so we can use the new options if it was already enabled\n this._disableNetworkInstrumentation();\n\n const tracingOptions: NetworkInstrumentationOptions =\n typeof options === 'object' ? options : {};\n\n this._enableNetworkInstrumentation(\n utility.definedValueOrDefault(tracingOptions.instrumentation, this.instr),\n utility.definedValueOrDefault(tracingOptions.logErrors, true),\n tracingOptions.activityName,\n utility.definedValueOrDefault(tracingOptions.useTracing, true),\n tracingOptions.tracingHeadersOptions\n );\n } else {\n // Options is falsy, disable.\n this._disableNetworkInstrumentation();\n }\n }\n}\n","import { Activity, ActivityDetail, Schema, TracingHeadersOptions } from '../interfaces';\nimport { PublicSafety } from './PublicSafety';\nimport { Tracing } from './Tracing';\nimport { SchematizedData, utility } from 'o11y/shared';\n\nexport const timedout = 'timedout';\nexport const terminated = 'terminated';\nexport const discarded = 'discarded';\n\nconst stopReason = {\n timedout,\n terminated,\n discarded\n};\n\nexport type onActivityStop = (detail: ActivityDetail) => void;\nexport type onActivityError = (error: Error, detail: ActivityDetail) => void;\n\nexport class ActivityImpl implements Activity {\n protected readonly _id: string;\n private readonly _startTimestamp: number;\n private readonly _startPerfTime: number;\n private readonly _safety: PublicSafety;\n private readonly _usePerf: boolean;\n protected static _count = 0;\n private readonly _perfId: string;\n private readonly _perfName: string;\n private _stopPerfTime: number;\n private _stopReason: string;\n private _timer: NodeJS.Timer;\n private _errorCount = 0;\n\n constructor(\n protected readonly _name: string,\n protected readonly _rootId: string,\n private readonly _onStopped: onActivityStop,\n private readonly _onError: onActivityError,\n timeout?: number,\n id?: string,\n protected readonly _isSampled?: boolean\n ) {\n const { tsNow, perfNow } = utility.time();\n\n ActivityImpl._count += 1;\n this._id = id || utility.generateUniqueId();\n\n this._usePerf =\n typeof performance !== 'undefined' &&\n typeof performance.mark === 'function' &&\n typeof performance.measure === 'function';\n if (this._usePerf) {\n this._perfName = `${this._name}__${ActivityImpl._count}`;\n this._perfId = `${this._name}__${this.id}`;\n try {\n performance.mark(this._perfId);\n } catch {\n this._usePerf = false;\n }\n }\n\n this._startTimestamp = tsNow;\n this._startPerfTime = perfNow;\n\n if (timeout > 0) {\n this._timer = setTimeout(() => {\n this._stopReason = this._stopReason || stopReason.timedout;\n this.stop();\n }, timeout);\n }\n this._safety = new PublicSafety();\n }\n\n get id(): string {\n return this._id;\n }\n\n getId(): string {\n return this.id;\n }\n\n getRootId(): string {\n return this._rootId;\n }\n\n get stopReason(): string {\n return this._stopReason;\n }\n\n error(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData\n ): void {\n this._safety.tryCatch(() => {\n this._errorCount += 1;\n if (typeof error === 'string') {\n error = new Error(error);\n }\n this._onError(error, this._getDetail(userSchemaOrText, userData));\n });\n }\n\n stop(userSchemaOrText?: Schema | string, userData?: SchematizedData): void {\n this._safety.tryCatch(() => this._stopInternal(userSchemaOrText, userData));\n }\n\n private _stopInternal(userSchemaOrText: Schema | string, userData: SchematizedData): void {\n // First things first.\n const stopPerfTime = utility.perfNow();\n if (this._usePerf) {\n try {\n // Use a more user-friendly name for measure.\n performance.measure(this._perfName, this._perfId);\n performance.clearMarks(this._perfId);\n performance.clearMeasures(this._perfName);\n } catch {}\n }\n\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n if (this.isStopped) {\n // Already stopped\n return;\n }\n this._stopPerfTime = stopPerfTime;\n\n const activityDetail: ActivityDetail = this._getDetail(userSchemaOrText, userData);\n this._onStopped(activityDetail);\n }\n\n get isStopped(): boolean {\n return this._stopPerfTime !== undefined;\n }\n\n discard(): void {\n this._safety.tryCatch(() => {\n this._stopReason = this._stopReason || stopReason.discarded;\n this.stop();\n });\n }\n\n terminate(): void {\n this._safety.tryCatch(() => {\n this._stopReason = this._stopReason || stopReason.terminated;\n this.stop();\n });\n }\n\n getIsSampled(): boolean {\n return this._isSampled || false;\n }\n\n protected _getDetail(\n userSchemaOrText: Schema | string,\n userData: SchematizedData\n ): ActivityDetail {\n return {\n id: this._id,\n rootId: this._rootId,\n name: this._name,\n userSchemaOrText: userSchemaOrText,\n userData,\n stopReason: this._stopReason,\n startTimestamp: this._startTimestamp,\n startPerfTime: this._startPerfTime,\n stopPerfTime: this._stopPerfTime,\n errorCount: this._errorCount,\n isSampled: this.getIsSampled()\n };\n }\n\n public getTraceHeaders(options: TracingHeadersOptions): Record<string, string> {\n // Normally, the root activity ID is the traceId.\n // If the activity is root, it's ID is (also) the traceId.\n // If the activity has no root, it's ID is (also) the traceId. i.e. It creates its own trace.\n const spanId = this.id;\n const traceId = this._rootId || spanId;\n\n return Tracing.getHeaders(traceId, spanId, this.getIsSampled(), options);\n }\n\n getStartTimestamp(): number {\n return this._startTimestamp;\n }\n\n getStartPerfTime(): number {\n return this._startPerfTime;\n }\n\n getStopPerfTime(): number {\n return this._stopPerfTime;\n }\n}\n","import { Activity, TracingHeadersOptions } from '../interfaces';\n\nconst id: string = new Array(16).fill(0).join('');\nclass ActivityNoOp implements Activity {\n getId(): string {\n return id;\n }\n getRootId(): string {\n return undefined;\n }\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n error(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n stop(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n discard(): void {}\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n terminate(): void {}\n\n getIsSampled(): boolean {\n return false;\n }\n getTraceHeaders(__options: TracingHeadersOptions): Record<string, string> {\n return {};\n }\n getStartTimestamp(): number {\n return undefined;\n }\n getStartPerfTime(): number {\n return undefined;\n }\n getStopPerfTime(): number {\n return undefined;\n }\n}\n\nexport const activityNoOp = Object.freeze(new ActivityNoOp());\n","import { SchematizedPayload } from '../interfaces';\nimport { InstrumentedEventData, MouseEventData } from '../interfaces-private';\nimport { DomEventData } from '../types/TypeDefinitions-Private';\nimport { schemaUtil, utility } from 'o11y/shared';\n\nexport class DomEventHelpers {\n getInstrumentedEventData(\n eventData: DomEventData,\n handledBy: HTMLElement,\n userPayload: SchematizedPayload\n ): InstrumentedEventData {\n const instrumentedEvent: InstrumentedEventData = {\n ownerComponent: handledBy.tagName,\n parentComponent:\n (handledBy.parentElement && handledBy.parentElement.tagName) || undefined,\n event: eventData,\n simplePath: utility.getXpath(handledBy)\n };\n\n if (userPayload) {\n instrumentedEvent.userPayload = schemaUtil.makePayload(\n userPayload.schema,\n userPayload.payload,\n true\n );\n }\n\n return instrumentedEvent;\n }\n\n getMouseEventData(e: MouseEvent): MouseEventData {\n return {\n altKey: e.altKey,\n bubbles: e.bubbles,\n button: e.button,\n buttons: e.buttons,\n cancelable: e.cancelable,\n clientX: e.clientX,\n clientY: e.clientY,\n composed: e.composed,\n defaultPrevented: e.defaultPrevented,\n detail: e.detail,\n eventPhase: e.eventPhase,\n isTrusted: e.isTrusted,\n timeStamp: e.timeStamp,\n type: e.type,\n ctrlKey: e.ctrlKey,\n metaKey: e.metaKey,\n movementX: e.movementX,\n movementY: e.movementY,\n offsetX: e.offsetX,\n offsetY: e.offsetY,\n pageX: e.pageX,\n pageY: e.pageY,\n screenX: e.screenX,\n screenY: e.screenY,\n shiftKey: e.shiftKey\n };\n }\n}\n\nconst singleton = new DomEventHelpers();\nexport const domEventHelpers = singleton;\n","import { IType, Schema, SchemaTokens } from '../interfaces';\nimport { PbjsNestedObjectDescriptor, SchematizedData, SchematizedDataValue, schemaUtil, utility } from 'o11y/shared';\n\n// These are temporary fields, the max value should be specified as an option on the schema. We may\n// keep some default values like this in the future\nconst maxFieldLength = 10000;\nconst minFieldLength = 0;\n\nconst maxFourBytesPos = 2147483647;\nconst maxFourBytesNeg = -2147483648;\nconst maxFourBytesUnsigned = 4294967295;\nconst maxEightBytesPos = 9223372036854776000;\nconst maxEightBytesNeg = -9223372036854776001;\nconst maxEightBytesUnsigned = 18446744073709552000;\n\nclass LogValidator {\n public validate(schema: Schema, data: SchematizedData): void {\n const schemaTokens: SchemaTokens = schemaUtil.checkSchema(schema);\n utility.requireArgument(data, 'data', 'object');\n\n const nestedSchema: PbjsNestedObjectDescriptor = schemaUtil.getTypes(schema);\n const errorMessage = this.validateFields(\n data,\n nestedSchema[schemaTokens.message] as IType,\n nestedSchema,\n schemaUtil.getSchemaId(schema)\n );\n\n if (errorMessage) {\n throw new Error(errorMessage);\n }\n }\n\n private validateFields(\n data: SchematizedData,\n message: IType,\n custom: PbjsNestedObjectDescriptor,\n schemaId: string\n ): string {\n const oneofs = message.oneofs || {};\n const fields = message.fields || {};\n let errorMessage = undefined;\n for (const key in data) {\n const value = data[key];\n if (!this.isNullOrUndefinedOrEmpty(value)) {\n // if it's null or undefined we don't need to match\n if (oneofs[key]) {\n errorMessage = this.matchFieldTypes(\n value,\n oneofs[key].oneof[0],\n custom,\n schemaId,\n key\n );\n } else if (fields[key]) {\n errorMessage = this.matchFieldTypes(\n value,\n fields[key].type,\n custom,\n schemaId,\n key,\n fields[key].rule\n );\n }\n // if the field is not present in the schema then we ignore it and will drop it later\n }\n if (errorMessage) {\n return errorMessage;\n }\n }\n return undefined;\n }\n\n private isNullOrUndefinedOrEmpty(val: SchematizedDataValue): boolean {\n return val === undefined || val === null || val === '';\n }\n\n private matchFieldTypes(\n fieldData: SchematizedDataValue,\n fieldType: string,\n descriptor: PbjsNestedObjectDescriptor,\n schemaId: string,\n key: string,\n rule?: string\n ): string {\n let convertedSchemaType;\n // this field can generically track specific conditions for each type\n let extraContext = undefined;\n if (rule === 'repeated') {\n let errorMessage = undefined;\n if (Array.isArray(fieldData)) {\n for (const index in fieldData) {\n // if it's repeated they should all be the same type so we can just run it as is\n errorMessage = this.matchFieldTypes(\n fieldData[index],\n fieldType,\n descriptor,\n schemaId,\n key\n );\n if (errorMessage) {\n // we should fail if any values are not validated\n break;\n }\n }\n } else {\n errorMessage = `Schema ${schemaId} on field: ${key}, repeated field should be an array`;\n }\n // this means that every value in the array was validated and we can finish\n return errorMessage;\n }\n switch (fieldType) {\n case 'string':\n convertedSchemaType = 'string';\n break;\n case 'bytes':\n convertedSchemaType = 'object';\n if (!(fieldData instanceof Uint8Array)) {\n extraContext = `Schema ${schemaId} on field: ${key}, bytes array is malformed`;\n }\n break;\n case 'bool':\n convertedSchemaType = 'boolean';\n break;\n case 'uint32':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxFourBytesUnsigned,\n 0,\n schemaId,\n key\n );\n break;\n case 'int32':\n case 'sint32':\n case 'fixed32':\n case 'sfixed32':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxFourBytesPos,\n maxFourBytesNeg,\n schemaId,\n key\n );\n break;\n case 'uint64':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxEightBytesUnsigned,\n 0,\n schemaId,\n key\n );\n break;\n case 'fixed64':\n case 'sfixed64':\n case 'int64':\n case 'sint64':\n convertedSchemaType = 'number';\n extraContext = this.checkNumberRange(\n fieldData,\n maxEightBytesPos,\n maxEightBytesNeg,\n schemaId,\n key\n );\n break;\n case 'double':\n case 'float':\n convertedSchemaType = 'number';\n if (!Number.isFinite(fieldData)) {\n extraContext = `Schema ${schemaId} on field: ${key}. Value must be finite`;\n }\n break;\n default:\n const ref: Record<string, string> = {};\n const keys = Object.keys(descriptor);\n for (const x in keys) {\n ref[keys[x].toLowerCase()] = keys[x];\n }\n if (ref[fieldType.toLowerCase()]) {\n //now we check this schema\n extraContext = this.validateFields(\n fieldData,\n descriptor[ref[fieldType.toLowerCase()]] as IType,\n descriptor,\n schemaId\n );\n convertedSchemaType = 'object';\n }\n break;\n }\n\n const fieldLength = (fieldData + '').length;\n if (typeof fieldData !== convertedSchemaType) {\n return `Schema ${schemaId} on field: ${key}. Expected type ${fieldType} but received type ${typeof fieldData}`;\n } else if (fieldLength < minFieldLength || fieldLength > maxFieldLength) {\n return `Schema ${schemaId} on field: ${key}, exceeded maximum or minimum field length`;\n } else if (extraContext) {\n return extraContext;\n }\n return undefined;\n }\n\n private checkNumberRange(\n value: number,\n max: number,\n min: number,\n schemaId: string,\n key: string\n ): string {\n if (value > max || value < min) {\n return `Schema ${schemaId} on field: ${key}, number value is too large or small`;\n }\n return undefined;\n }\n}\n\nexport const logValidator = new LogValidator();\n","import { Metric } from '../interfaces/Metric';\nimport { UpCounter } from '../interfaces/UpCounter';\nimport { MetricsTags, utility } from 'o11y/shared';\n\nexport class UpCounterImpl implements Metric<number>, UpCounter {\n private readonly _createdOn: number;\n private _lastUpdatedOn: number;\n private _value = 0;\n\n constructor(\n private readonly _name: string,\n private readonly _ownerName: string,\n private readonly _ownerAppName: string,\n private readonly _tags: MetricsTags\n ) {\n this._createdOn = utility.time().tsNow;\n }\n\n getName(): string {\n return this._name;\n }\n\n getCreatedOn(): number {\n return this._createdOn;\n }\n\n getLastUpdatedOn(): number {\n return this._lastUpdatedOn;\n }\n\n getData(): number {\n return this._value;\n }\n\n increment(value = 1): void {\n if (typeof value === 'number' && value > 0) {\n this._value += Math.round(value);\n this._lastUpdatedOn = utility.time().tsNow;\n return;\n }\n\n throw new Error('UpCounter can only increment positive numbers.');\n }\n\n reset(): void {\n this._lastUpdatedOn = undefined;\n this._value = 0;\n }\n\n getOwnerName(): string {\n return this._ownerName;\n }\n\n getOwnerAppName(): string {\n return this._ownerAppName;\n }\n\n getTags(): Readonly<MetricsTags> {\n return this._tags;\n }\n}\n","import { Metric } from '../interfaces/Metric';\nimport { ValueRecorder } from '../interfaces/ValueRecorder';\nimport { MetricsTags, utility } from 'o11y/shared';\n\nexport class ValueRecorderImpl implements Metric<number[]>, ValueRecorder {\n private readonly _createdOn: number;\n private _lastUpdatedOn: number;\n private _values = new Array<number>();\n\n constructor(\n private readonly _name: string,\n private readonly _ownerName: string,\n private readonly _ownerAppName: string,\n private readonly _tags: MetricsTags\n ) {\n this._createdOn = utility.time().tsNow;\n // TODO: Add sampling/throttling to put a cap on the size of the array\n }\n\n getName(): string {\n return this._name;\n }\n\n getCreatedOn(): number {\n return this._createdOn;\n }\n\n getLastUpdatedOn(): number {\n return this._lastUpdatedOn;\n }\n\n getData(): number[] {\n return this.values;\n }\n\n get values(): number[] {\n return this._values.slice(0, this._values.length);\n }\n\n record(value: number): void {\n if (typeof value === 'number') {\n this._values.push(value);\n this._lastUpdatedOn = utility.time().tsNow;\n return;\n }\n\n throw new Error('ValueRecorder can only record numbers.');\n }\n\n reset(): void {\n this._lastUpdatedOn = undefined;\n this._values = [];\n }\n\n getOwnerName(): string {\n return this._ownerName;\n }\n\n getOwnerAppName(): string {\n return this._ownerAppName;\n }\n\n getTags(): MetricsTags {\n return this._tags;\n }\n}\n","export class SizeLimitedMap<K, V> {\n private readonly _map = new Map<K, V>();\n\n private _maxSize: number;\n constructor(maxSize: number) {\n if (typeof maxSize === 'number' && maxSize > 0) {\n this._maxSize = Math.ceil(maxSize);\n return;\n }\n throw new Error('maxSize must be a positive number');\n }\n\n get maxSize(): number {\n return this._maxSize;\n }\n\n get(key: K): V {\n return this._map.get(key);\n }\n\n has(key: K): boolean {\n return this._map.has(key);\n }\n\n set(key: K, value: V): boolean {\n if (this.has(key) || this._map.size < this.maxSize) {\n this._map.set(key, value);\n return true;\n }\n return false;\n }\n\n getElements(): V[] {\n return Array.from(this._map.values());\n }\n\n clear(): void {\n this._map.clear();\n }\n}\n","import { MetricsReporter, UpCounter, ValueRecorder } from '../interfaces';\n\nimport { UpCounterImpl } from './UpCounterImpl';\nimport { ValueRecorderImpl } from './ValueRecorderImpl';\nimport { SizeLimitedMap } from './SizeLimitedMap';\nimport { MetricsTags } from 'o11y/shared';\n\nconst maxCounters = 1000;\nconst maxValueRecorders = 500;\n\nenum MetricType {\n Counter,\n Percentile\n}\n\nexport class MetricsImpl implements MetricsReporter {\n private readonly _upCounters = new SizeLimitedMap<string, UpCounterImpl>(maxCounters);\n private readonly _valueRecorders = new SizeLimitedMap<string, ValueRecorderImpl>(\n maxValueRecorders\n );\n\n constructor(\n private readonly _ownerName: string,\n private readonly _getOwnerAppName: () => string\n ) {}\n\n incrementCounter(\n operation: string,\n increment: number,\n hasError = false,\n tags: MetricsTags = {}\n ): void {\n this._tagError(tags, hasError);\n this._upCounter(operation, tags).increment(increment);\n }\n\n trackValue(operation: string, value: number, hasError = false, tags: MetricsTags = {}): void {\n this._tagError(tags, hasError);\n this._valueRecorder(operation, tags).record(value);\n }\n\n private _upCounter(name: string, tags: MetricsTags): UpCounter {\n const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Counter);\n let instrument = this._upCounters.get(key);\n if (!instrument) {\n instrument = new UpCounterImpl(\n name,\n this._ownerName,\n this._getOwnerAppName(),\n sortedTags\n );\n if (!this._upCounters.set(key, instrument)) {\n throw new Error(`Max size of ${maxCounters} exceeeded for UpCounters`);\n }\n }\n return instrument;\n }\n\n private _valueRecorder(name: string, tags: MetricsTags): ValueRecorder {\n const { key, sortedTags } = this._getKeyAndSortedTags(name, tags, MetricType.Percentile);\n let instrument = this._valueRecorders.get(key);\n if (!instrument) {\n instrument = new ValueRecorderImpl(\n name,\n this._ownerName,\n this._getOwnerAppName(),\n sortedTags\n );\n if (!this._valueRecorders.set(key, instrument)) {\n throw new Error(`Max size of ${maxValueRecorders} exceeeded for ValueRecorders`);\n }\n }\n return instrument;\n }\n\n getUpCounters(): UpCounterImpl[] {\n return this._upCounters.getElements();\n }\n\n getValueRecorders(): ValueRecorderImpl[] {\n return this._valueRecorders.getElements();\n }\n\n private _tagError(tags: MetricsTags, hasError: boolean): void {\n tags.status = hasError === true ? 'error' : 'success';\n }\n\n private _getKeyAndSortedTags(\n operation: string,\n tags: MetricsTags,\n metricType: MetricType\n ): { key: string; sortedTags: MetricsTags } {\n // This method should be called after any manipulation of tags\n const sortedTags = Object.keys(tags)\n .sort()\n .reduce((prev: MetricsTags, curr: string) => {\n prev[curr] = tags[curr];\n return prev;\n }, {});\n const key = `${MetricType[metricType]}:${operation}${JSON.stringify(sortedTags)}`;\n return {\n key,\n sortedTags\n };\n }\n}\n","export class MockEvent {\n constructor(\n public readonly type: string,\n public readonly composed: boolean,\n private readonly _composedPaths: unknown[]\n ) {}\n composedPath(): unknown[] {\n return this._composedPaths;\n }\n}\n","import {\n activitySchema,\n errorSchema,\n instrumentedEventSchema,\n simpleSchema\n} from 'o11y_schema/sf_instrumentation';\n\nimport {\n Activity,\n ActivityDetail,\n Instrumentation,\n Metric,\n MetricsReporter,\n PayloadProvider,\n Schema,\n SchematizedPayload\n} from '../interfaces';\nimport { ActivityData, ErrorData, InstrumentedEventData } from '../interfaces-private';\n\nimport { ActivityImpl, discarded, onActivityError, onActivityStop } from './ActivityImpl';\nimport { activityNoOp } from './ActivityNoOp';\nimport { AutomaticClickTracker } from './AutomaticClickTracker';\nimport { domEventHelpers } from './DomEventHelpers';\nimport { logValidator } from './LogValidator';\nimport { MetricsImpl } from './MetricsImpl';\nimport { MockEvent } from './MockEvent';\nimport { NextgenImpl } from './NextgenImpl';\nimport { PublicSafety } from './PublicSafety';\nimport { LightningElement, MetricsTags, SchematizedData, schemaUtil, utility } from 'o11y/shared';\n\n// @W-10241440, disable timeouts\nconst maxActivityDurationMsecs: number = undefined;\nconst reservedMetricCharacters = ['`'];\nconst reservedMetricNames = {\n internalError: 'o11y-error'\n};\nconst denyListMetricNames = Object.freeze(Array.from(Object.values(reservedMetricNames)));\n\nexport class InstrumentationImpl implements Instrumentation, MetricsReporter {\n protected static readonly defaultAppName = 'APP_NOT_REGISTERED';\n private readonly _metrics: MetricsImpl;\n private readonly _onActivityStoppedCallback: onActivityStop =\n this._handleActivityStop.bind(this);\n protected readonly _onActivityErrorCallback: onActivityError =\n this._handleActivityError.bind(this);\n protected readonly _safety: PublicSafety;\n private readonly _simpleTextMaxLength: number;\n\n constructor(private readonly _nextGen: NextgenImpl, private readonly _name: string) {\n for (const reservedChar of reservedMetricCharacters) {\n if (this._name.indexOf(reservedChar) >= 0) {\n throw new Error(`Name cannot include the reserved character \"${reservedChar}\"`);\n }\n }\n\n this._safety = new PublicSafety({\n increment: (increment) => this._incrementError(increment)\n });\n\n this._metrics = this._initMetrics();\n\n const simpleTextOptions = schemaUtil.getOptions(simpleSchema, 'Simple', 'text');\n this._simpleTextMaxLength = simpleTextOptions\n ? simpleTextOptions['(meta.max_length)']\n : Number.MAX_VALUE;\n }\n\n protected _initMetrics(): MetricsImpl {\n return new MetricsImpl(\n this.name,\n () => this._nextGen.appName || InstrumentationImpl.defaultAppName\n );\n }\n\n private _incrementError(increment = 1): void {\n this._metrics.incrementCounter(reservedMetricNames.internalError, increment, false);\n }\n\n get name(): string {\n return this._name;\n }\n\n /**\n * This function is to allow for convenience calls to our API, where a string can\n * be provided instead of an actual Schema. In that case, we wrap the text in\n * a built-in simple schema.\n * @param userSchemaOrText Schema or string.\n * @param userData\n * @param onlyIfBoth If true, then both the schema and the data must be specified.\n * @returns\n */\n protected _wrapUserPayload(\n userSchemaOrText: Schema | string,\n userData: SchematizedData,\n onlyIfBoth = false\n ): SchematizedPayload {\n let userSchema: Schema;\n if (typeof userSchemaOrText === 'string') {\n userSchema = simpleSchema;\n if (userSchemaOrText) {\n userData = {\n text: userSchemaOrText.substr(0, this._simpleTextMaxLength)\n };\n } else {\n userData = undefined;\n }\n } else {\n userSchema = userSchemaOrText;\n }\n\n return schemaUtil.makePayload(userSchema, userData, onlyIfBoth);\n }\n\n /**\n *\n * @param userSchema The schema of the second argument. Also used as the basis for auto-generated\n * counters for log calls using the same schema.\n * @param userData Optional data that complies with the provided schema\n */\n log(userSchemaOrText: Schema | string, userData?: SchematizedData): void {\n this._safety.tryCatch(() => {\n const timestamp = utility.time().tsNow;\n utility.requireArgument(userSchemaOrText, 'userSchemaOrText', ['object', 'string']);\n\n const userPayload = this._wrapUserPayload(userSchemaOrText, userData);\n\n if (userPayload && userPayload.payload) {\n this._logInternal(\n this.name,\n userPayload.schema,\n userPayload.payload,\n timestamp,\n this._nextGen.getRootActivityId()\n );\n }\n });\n }\n\n protected _logInternal(\n loggerName: string,\n schema: Schema,\n data: SchematizedData,\n timestamp: number,\n rootId?: string\n ): number {\n this._checkInputs(schema, data);\n const appPayload: SchematizedPayload = this._getPayloadFromProvider(\n this._nextGen.appPayloadProvider\n );\n const pagePayload: SchematizedPayload = this._getPayloadFromProvider(\n this._nextGen.pagePayloadProvider\n );\n\n return this._nextGen.addLog(\n loggerName,\n schema,\n data,\n timestamp,\n rootId,\n pagePayload,\n appPayload\n );\n }\n\n error(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData\n ): void {\n return this._safety.tryCatch(() =>\n this._errorInternal(error, userSchemaOrText, userData, undefined)\n );\n }\n\n protected _errorInternal(\n error: Error | string,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData,\n activityId?: string\n ): number {\n const loggedTimestamp = utility.time().tsNow;\n utility.requireArgument(error, 'error', [Error, 'string']);\n\n if (typeof error === 'string') {\n error = new Error(error);\n }\n\n const userPayload = this._wrapUserPayload(userSchemaOrText, userData, true);\n\n const errorData: ErrorData = {\n name: error.name,\n message: error.message,\n stack: error.stack,\n userPayload,\n activityId\n };\n\n return this._logInternal(\n this.name,\n errorSchema,\n errorData,\n loggedTimestamp,\n this._nextGen.getRootActivityId()\n );\n }\n\n startActivity(name: string): Activity {\n return this._safety.tryCatchReturn(() => {\n utility.requireArgument(name, 'name');\n\n const activity: Activity = new ActivityImpl(\n name,\n this._nextGen.getRootActivityId(),\n this._onActivityStoppedCallback,\n this._onActivityErrorCallback,\n maxActivityDurationMsecs,\n undefined,\n // By definition, an activity is sampled if root activity is sampled\n this._nextGen.isRootActivitySampled()\n );\n return activity;\n }, activityNoOp);\n }\n\n protected _getActivityData(detail: ActivityDetail): ActivityData {\n const userPayload = this._wrapUserPayload(detail.userSchemaOrText, detail.userData, true);\n\n return {\n id: detail.id,\n name: detail.name,\n duration: detail.stopPerfTime - detail.startPerfTime,\n stopReason: detail.stopReason,\n userPayload,\n errorCount: detail.errorCount,\n isSampled: detail.isSampled\n };\n }\n\n private _handleActivityStop(detail: ActivityDetail): void {\n if (detail.stopReason === discarded) {\n return;\n }\n const activityData: ActivityData = this._getActivityData(detail);\n\n this._logActivity(activityData, detail.startTimestamp, detail.rootId);\n }\n\n protected _logActivity(\n activityData: ActivityData,\n startTimestamp: number,\n rootId?: string\n ): void {\n this._logInternal(this.name, activitySchema, activityData, startTimestamp, rootId);\n }\n\n private _handleActivityError(error: Error, detail: ActivityDetail): void {\n this._errorInternal(error, detail.userSchemaOrText, detail.userData, detail.id);\n }\n\n private _getPayloadFromProvider(provider: PayloadProvider): SchematizedPayload {\n if (provider) {\n const payload: SchematizedPayload = provider.getPayload();\n if (payload) {\n this._checkInputs(payload.schema, payload.payload);\n return payload;\n }\n }\n return undefined;\n }\n\n domEvent(\n event: Event,\n handledBy: HTMLElement | LightningElement,\n userSchemaOrText?: Schema | string,\n userData?: SchematizedData,\n auto?: boolean\n ): void {\n this._safety.tryCatch(() => {\n const tsNow = utility.time().tsNow;\n\n utility.requireArgument(event, 'event', [Event, MockEvent]);\n // TODO: Using 'object' instead of 'LightningElement' for now (no imports)\n utility.requireArgument(handledBy, 'handledBy', [HTMLElement, 'object']);\n\n let htmlElement;\n if (handledBy instanceof HTMLElement) {\n htmlElement = handledBy;\n } else {\n handledBy = handledBy as LightningElement;\n // Convenience for LightningElement developers who pass \"this\" in handledBy.\n // Get the underlying HTML element\n if (handledBy.template && handledBy.template.host instanceof HTMLElement) {\n htmlElement = handledBy.template.host;\n } else {\n utility.requireArgument(undefined, 'handledBy');\n }\n }\n\n const userPayload: SchematizedPayload = this._wrapUserPayload(\n userSchemaOrText,\n userData,\n true\n );\n\n switch (event.type) {\n case 'click': {\n const mouseEvent = event as MouseEvent;\n\n // If the user has called domEvent API on this event explicitly,\n // then we don't need to log it by default.\n const acd: AutomaticClickTracker = this._nextGen.getClickTracker();\n if (acd) {\n acd.markEventHandled(mouseEvent);\n }\n\n const mouseEventData = domEventHelpers.getMouseEventData(mouseEvent);\n\n const instrumentedEvent: InstrumentedEventData =\n domEventHelpers.getInstrumentedEventData(\n mouseEventData,\n htmlElement,\n userPayload\n );\n instrumentedEvent.auto = auto;\n\n this._logInternal(\n this.name,\n instrumentedEventSchema,\n instrumentedEvent,\n tsNow,\n this._nextGen.getRootActivityId()\n );\n break;\n }\n default:\n throw new Error(utility.notImplemented);\n }\n });\n }\n\n incrementCounter(\n operation: string,\n increment = 1,\n hasError = false,\n tags: MetricsTags = {}\n ): void {\n this._safety.tryCatch(() => {\n utility.requireArgument(operation, 'operation', 'string');\n utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);\n utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);\n utility.requireArgument(increment, 'increment', 'number');\n utility.requireArgument(hasError, 'hasError', 'boolean');\n utility.requireArgument(tags, 'tags', 'object');\n Object.entries(tags).forEach((entry) => {\n utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [\n 'string',\n 'number',\n 'boolean'\n ]);\n });\n this._metrics.incrementCounter(operation, increment, hasError, tags);\n });\n }\n\n trackValue(operation: string, value: number, hasError = false, tags: MetricsTags = {}): void {\n this._safety.tryCatch(() => {\n utility.requireArgument(operation, 'operation', 'string');\n utility.checkForDenyListedValues(operation, 'operation', denyListMetricNames);\n utility.checkForReservedCharacters(operation, 'operation', reservedMetricCharacters);\n utility.requireArgument(value, 'value', 'number');\n utility.requireArgument(hasError, 'hasError', 'boolean');\n utility.requireArgument(tags, 'tags', 'object');\n Object.entries(tags).forEach((entry) => {\n utility.requireArgument(entry[1], `Tag value for '${entry[0]}'`, [\n 'string',\n 'number',\n 'boolean'\n ]);\n });\n\n this._metrics.trackValue(operation, value, hasError, tags);\n });\n }\n\n private _checkInputs(schema: Schema, data: SchematizedData): void {\n schemaUtil.checkSchema(schema);\n utility.requireArgument(data, 'data', 'object');\n\n // TODO: Protobuf-free Validation.\n // Until then, do a best-case effort.\n let savedUserPayload: SchematizedPayload;\n if (data.userPayload !== undefined && schemaUtil.isInternal(schema)) {\n savedUserPayload = data.userPayload;\n logValidator.validate(savedUserPayload.schema, savedUserPayload.payload);\n // userPayload needs to be temporarily removed, since it's not yet encoded.\n data.userPayload = undefined;\n }\n logValidator.validate(schema, data);\n if (savedUserPayload !== undefined) {\n // Restore userPayload\n data.userPayload = savedUserPayload;\n }\n }\n\n getUpCounters(): Metric<number>[] {\n return this._metrics.getUpCounters().filter((m) => m.getLastUpdatedOn());\n }\n\n getValueRecorders(): Metric<number[]>[] {\n return this._metrics.getValueRecorders().filter((m) => m.getLastUpdatedOn());\n }\n}\n","import { RootActivity, Schema } from '../interfaces';\nimport { ActivityDetail } from '../interfaces/ActivityDetail';\nimport { ActivityImpl, onActivityError, onActivityStop } from './ActivityImpl';\nimport { SchematizedData, utility } from 'o11y/shared';\n\nexport class RootActivityImpl extends ActivityImpl implements RootActivity {\n constructor(\n name: string,\n onStopped: onActivityStop,\n onError: onActivityError,\n rootId?: string,\n _isSampled?: boolean\n ) {\n super(\n name,\n undefined,\n onStopped,\n onError,\n undefined,\n rootId || utility.generateUniqueId(32),\n _isSampled\n );\n }\n\n private _preRootId: string;\n get preRootId(): string {\n return this._preRootId;\n }\n set preRootId(value: string) {\n this._preRootId = value;\n }\n\n protected _getDetail(userSchema: Schema, userData: SchematizedData): ActivityDetail {\n const detail = super._getDetail(userSchema, userData);\n detail.isRoot = true;\n detail.preRootId = this.preRootId;\n return detail;\n }\n}\n","import { RootActivity, TracingHeadersOptions } from '../interfaces';\n\nconst rootId: string = new Array(32).fill(0).join('');\nclass RootActivityNoOp implements RootActivity {\n getId(): string {\n return rootId;\n }\n getRootId(): string {\n return undefined;\n }\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n error(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n stop(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n discard(): void {}\n\n /* eslint-disable-next-line @typescript-eslint/no-empty-function */\n terminate(): void {}\n\n getIsSampled(): boolean {\n return false;\n }\n getTraceHeaders(__options: TracingHeadersOptions): Record<string, string> {\n return {};\n }\n getStartTimestamp(): number {\n return undefined;\n }\n getStartPerfTime(): number {\n return undefined;\n }\n getStopPerfTime(): number {\n return undefined;\n }\n}\n\nexport const rootActivityNoOp = Object.freeze(new RootActivityNoOp());\n","import { ActivityDetail, RootActivity } from '../interfaces';\nimport { ActivityData } from '../interfaces-private';\nimport { discarded, onActivityStop } from './ActivityImpl';\nimport { InstrumentationImpl } from './InstrumentationImpl';\nimport { RootActivityImpl } from './RootActivityImpl';\nimport { rootActivityNoOp } from './RootActivityNoOp';\nimport { utility } from 'o11y/shared';\nimport { MetricsImpl } from './MetricsImpl';\n\nexport class AppInstrumentationImpl extends InstrumentationImpl {\n private rootActivity: RootActivityImpl;\n\n private readonly _onRootActivityStoppedCallback: onActivityStop =\n this.handleRootActivityStop.bind(this);\n\n startRootActivity(name: string, rootId?: string, isSampled?: boolean): RootActivity {\n return this._safety.tryCatchReturn(() => {\n utility.requireArgument(name, 'name');\n\n const newRootActivity = new RootActivityImpl(\n name,\n this._onRootActivityStoppedCallback,\n this._onActivityErrorCallback,\n rootId,\n isSampled\n );\n\n if (this.rootActivity && !this.rootActivity.isStopped) {\n const preRootId = this.rootActivity.getId();\n this.rootActivity.terminate();\n newRootActivity.preRootId = preRootId;\n }\n this.rootActivity = newRootActivity;\n\n return this.rootActivity as RootActivity;\n }, rootActivityNoOp);\n }\n\n private handleRootActivityStop(detail: ActivityDetail): void {\n if (detail.stopReason === discarded) {\n return;\n }\n\n const activityData: ActivityData = this._getActivityData(detail);\n\n this._logActivity(activityData, detail.startTimestamp);\n this.rootActivity = undefined;\n }\n\n protected _getActivityData(detail: ActivityDetail): ActivityData {\n const activityData: ActivityData = super._getActivityData(detail);\n activityData.isRoot = detail.isRoot;\n activityData.preRootId = detail.preRootId;\n return activityData;\n }\n\n getRootActivityId(): string {\n return this.rootActivity && this.rootActivity.getId();\n }\n\n isRootActivitySampled(): boolean {\n return this.rootActivity && this.rootActivity.getIsSampled();\n }\n\n protected _initMetrics(): MetricsImpl {\n return new MetricsImpl(this.name, () => this.name);\n }\n}\n","import { Instrumentation } from '../interfaces';\nimport { utility } from 'o11y/shared';\n\nconst pathLimit = 5;\n\nexport class AutomaticClickTracker {\n private instr: Instrumentation;\n private ignoredEvent: Event;\n private isActive = false;\n private document: Document;\n private readonly _boundClickListener = this.clickListener.bind(this);\n\n constructor(instrumentation: Instrumentation, document: Document) {\n utility.requireArgument(instrumentation, 'instrumentation');\n utility.requireArgument(document, 'document');\n\n this.instr = instrumentation;\n this.document = document;\n }\n\n activate(): void {\n if (!this.isActive) {\n this.document.addEventListener('click', this._boundClickListener, true);\n this.isActive = true;\n }\n }\n\n deactivate(): void {\n if (this.isActive) {\n this.document.removeEventListener('click', this._boundClickListener, true);\n this.isActive = false;\n }\n }\n\n markEventHandled(event: MouseEvent): void {\n this.ignoredEvent = event;\n }\n\n private clickListener(event: MouseEvent): void {\n let eventTargets: EventTarget[] = event.composedPath && event.composedPath();\n if (!eventTargets || !eventTargets.length) {\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n eventTargets = (event as any).path;\n }\n const handledBy: HTMLElement = this.getClickableElement(eventTargets);\n\n if (handledBy) {\n // Immediate\n setTimeout(() => {\n if (event !== this.ignoredEvent) {\n this.instr.domEvent(event, handledBy, undefined, undefined, true);\n }\n });\n }\n }\n\n private getClickableElement(path: EventTarget[]): HTMLElement {\n const limit = path ? Math.min(path.length, pathLimit) : 0;\n for (let x = 0; x < limit; x += 1) {\n const currentElement = path[x] as HTMLElement;\n const tagName = currentElement.tagName && currentElement.tagName.toLowerCase();\n if (tagName === 'a' || tagName === 'button') {\n return currentElement;\n }\n if (tagName === 'input') {\n const inputElement = currentElement as HTMLInputElement;\n if (inputElement.type && inputElement.type.toLowerCase() === 'button') {\n return inputElement;\n }\n }\n }\n return undefined;\n }\n}\n","import {\n BufferedLog,\n Instrumentation,\n InstrumentedAppMethods,\n LogCollector,\n LogMeta,\n Metric,\n MetricsCollector,\n Nextgen,\n PayloadProvider,\n Schema,\n SchematizedPayload\n} from '../interfaces';\nimport { AppInstrumentationImpl } from './AppInstrumentationImpl';\nimport { AutomaticClickTracker } from './AutomaticClickTracker';\nimport { InstrumentationImpl } from './InstrumentationImpl';\nimport { Tracing } from './Tracing';\nimport { SchematizedData, utility } from 'o11y/shared';\nimport { LogCollectorOptions } from 'src/interfaces/LogCollectorOptions';\n\nconst maxInstrumentationLength = 80;\nconst truncatedText = '_CUT';\nconst maxInstrumentationLengthBeforeTruncated = maxInstrumentationLength - truncatedText.length;\n\nexport class NextgenImpl implements Nextgen {\n private readonly _logCollectors = new Set<LogCollector>();\n private readonly _instruments = new Map<string, InstrumentationImpl | AppInstrumentationImpl>();\n private _sequence = 0;\n private _appInstr: AppInstrumentationImpl;\n private _autoClickTracker: AutomaticClickTracker;\n private _metricsCollector: MetricsCollector;\n private _appPayloadProvider: PayloadProvider;\n private _pagePayloadProvider: PayloadProvider;\n private _forceDisabledLogCollectors = new Set<LogCollector>();\n private _logCollectorFailures = new Map<LogCollector, number>();\n private static _collectorFailureLimit = 5;\n private _isBufferingEnabled = false;\n private _buffer: BufferedLog[] = [];\n\n get pagePayloadProvider(): PayloadProvider {\n return this._pagePayloadProvider;\n }\n set pagePayloadProvider(provider: PayloadProvider) {\n this._pagePayloadProvider = provider;\n }\n\n get appPayloadProvider(): PayloadProvider {\n return this._appPayloadProvider;\n }\n set appPayloadProvider(provider: PayloadProvider) {\n this._appPayloadProvider = provider;\n }\n\n registerApp(name: string, enableBuffering?: boolean): InstrumentedAppMethods {\n utility.requireArgument(name, 'name', 'string');\n if (this._appInstr) {\n throw new Error('An app has already been registered with instrumentation.');\n }\n const instr = this._instruments.get(name);\n if (instr) {\n throw new Error(`The instrumentation name ${name} is already taken`);\n }\n this._appInstr = new AppInstrumentationImpl(this, name);\n this._instruments.set(name, this._appInstr);\n this._isBufferingEnabled = enableBuffering;\n\n const tracing = new Tracing(this._appInstr);\n\n return {\n log: this._appInstr.log.bind(this._appInstr),\n error: this._appInstr.error.bind(this._appInstr),\n startActivity: this._appInstr.startActivity.bind(this._appInstr),\n domEvent: this._appInstr.domEvent.bind(this._appInstr),\n incrementCounter: this._appInstr.incrementCounter.bind(this._appInstr),\n trackValue: this._appInstr.trackValue.bind(this._appInstr),\n networkInstrumentation: tracing.networkInstrumentation.bind(tracing),\n\n startRootActivity: this._appInstr.startRootActivity.bind(this._appInstr),\n registerLogCollector: this.registerLogCollector.bind(this),\n registerMetricsCollector: this.registerMetricsCollector.bind(this),\n activateClickTracker: this.activateClickTracker.bind(this),\n deactivateClickTracker: this.deactivateClickTracker.bind(this),\n disableBuffering: this.disableBuffering.bind(this)\n };\n }\n\n getInstrumentation(name: string): Instrumentation {\n utility.requireArgument(name, 'name', 'string');\n if (name.length > maxInstrumentationLength) {\n // don't throw if it's too long. just add truncated suffix, but stay within max length\n name = name.substr(0, maxInstrumentationLengthBeforeTruncated) + truncatedText;\n }\n let instr: InstrumentationImpl | AppInstrumentationImpl = this._instruments.get(name);\n if (!instr) {\n instr = new InstrumentationImpl(this, name);\n this._instruments.set(name, instr);\n } else if (instr === this._appInstr) {\n throw new Error(`The instrumentation name ${name} is being used by the app.`);\n }\n return instr;\n }\n\n get appName(): string {\n return this._appInstr && this._appInstr.name;\n }\n\n // This is an internal method that needs to be public\n addLog(\n loggerName: string,\n schema: Schema,\n data: SchematizedData,\n timestamp: number,\n rootId: string,\n pagePayload: SchematizedPayload,\n appPayload: SchematizedPayload\n ): number {\n this._sequence += 1;\n const sequence: number = this._sequence;\n const loggerAppName: string = this.appName;\n const connectionType: string = utility.getConnectionType();\n const logMeta: LogMeta = {\n timestamp,\n rootId,\n sequence,\n loggerName,\n pagePayload,\n appPayload,\n loggerAppName,\n connectionType\n };\n\n if (this._isBufferingEnabled) {\n this._buffer.push({ schema, data: utility.clone(data), logMeta });\n }\n\n for (const collector of this._logCollectors) {\n // Make a copy of the aguments passed to the collectors lest they change them.\n const dataClone = utility.clone(data);\n const failures: number = this._logCollectorFailures.get(collector);\n\n try {\n if (\n !this._forceDisabledLogCollectors.has(collector) &&\n !(collector.getIsCollectDisabled && collector.getIsCollectDisabled())\n ) {\n collector.collect(schema, dataClone, logMeta);\n // if it got here it means it succeeded/didn't throw so we want to decrement the failure count\n if (failures > 0) {\n this._logCollectorFailures.set(collector, failures - 1);\n }\n }\n } catch (err) {\n // If a collector fails too much we just disable it\n if (\n failures >= NextgenImpl._collectorFailureLimit &&\n !this._forceDisabledLogCollectors.has(collector)\n ) {\n this._forceDisabledLogCollectors.add(collector);\n } else {\n this._logCollectorFailures.set(collector, failures + 1);\n }\n }\n }\n return this._sequence;\n }\n\n getBuffer(): BufferedLog[] {\n return this._buffer;\n }\n\n disableBuffering(): void {\n this._isBufferingEnabled = false;\n this._buffer = [];\n }\n\n getClickTracker(): AutomaticClickTracker {\n return this._autoClickTracker;\n }\n\n getRootActivityId(): string {\n return this._appInstr && this._appInstr.getRootActivityId();\n }\n\n isRootActivitySampled(): boolean {\n return this._appInstr && this._appInstr.isRootActivitySampled();\n }\n\n activateClickTracker(): void {\n if (!this._autoClickTracker) {\n this._autoClickTracker = new AutomaticClickTracker(this._appInstr, window.document);\n }\n this._autoClickTracker.activate();\n }\n\n deactivateClickTracker(): void {\n if (this._autoClickTracker) {\n this._autoClickTracker.deactivate();\n // In case activateClickTracker is called later with a different instrumentation\n this._autoClickTracker = undefined;\n }\n }\n\n registerLogCollector(collector: LogCollector, options?: LogCollectorOptions): void {\n utility.requireArgument(collector, 'collector');\n this._logCollectors.add(collector);\n this._logCollectorFailures.set(collector, 0);\n if (\n (!collector.getIsCollectDisabled || !collector.getIsCollectDisabled()) &&\n options &&\n options.retroactive\n ) {\n for (const log of this._buffer) {\n collector.collect(log.schema, log.data, log.logMeta);\n }\n }\n }\n\n registerMetricsCollector(collector: MetricsCollector): void {\n utility.requireArgument(collector, 'collector');\n if (this._metricsCollector) {\n throw new Error('A metrics Collector is already registered.');\n }\n this._metricsCollector = collector;\n this._metricsCollector.receiveMetricsExtractors({\n getAllUpCounters: this.getAllUpCounters.bind(this),\n getAllValueRecorders: this.getAllValueRecorders.bind(this)\n });\n }\n\n private getAllUpCounters(): Metric<number>[] {\n const arrOfArrs = Array.from(this._instruments.values()).map((instr) =>\n instr.getUpCounters()\n );\n return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);\n }\n\n private getAllValueRecorders(): Metric<number[]>[] {\n const arrOfArrs = Array.from(this._instruments.values()).map((instr) =>\n instr.getValueRecorders()\n );\n return arrOfArrs.reduce((pv, cv) => pv.concat(cv), []);\n }\n}\n","import { Instrumentation, InstrumentedAppMethods, InstrumentedAppOptions } from './interfaces';\nimport { NextgenImpl } from './library/NextgenImpl';\nimport { utility } from 'o11y/shared';\n\nclass Index {\n private _nextgen: NextgenImpl;\n // We are lazily initializing the singleton to allow any options to be processed\n // before the instantiation.\n private get _lazyNextGen(): NextgenImpl {\n if (!this._nextgen) {\n this._nextgen = new NextgenImpl();\n }\n return this._nextgen;\n }\n\n public registerInstrumentedApp(\n name: string,\n options?: InstrumentedAppOptions\n ): InstrumentedAppMethods {\n if (options && options.isProduction) {\n // Do this before construction\n utility.markProduction();\n }\n const retVal: InstrumentedAppMethods = this._lazyNextGen.registerApp(\n name,\n options && options.enableBuffering\n );\n if (options) {\n this._nextgen.appPayloadProvider = options.appPayloadProvider;\n this._nextgen.pagePayloadProvider = options.pagePayloadProvider;\n }\n return retVal;\n }\n\n public getInstrumentation(name?: string): Instrumentation {\n return this._lazyNextGen.getInstrumentation(name);\n }\n}\nconst index = new Index(); // singleton\nconst registerInstrumentedApp = index.registerInstrumentedApp.bind(index);\nconst getInstrumentation = index.getInstrumentation.bind(index);\nconst time = utility.time.bind(utility);\n\nexport { registerInstrumentedApp, getInstrumentation, time };\n","import { Root, Type } from 'protobufjs';\nimport { coreEnvelopeSchema } from 'o11y_schema/sf_instrumentation';\n\nimport {\n Environment,\n Instrumentation,\n LogCollector,\n LogMeta,\n MetricsCollector,\n MetricsExtractorMethods,\n Schema\n} from '../../interfaces';\nimport { LazyMapToList, SchematizedData, schemaUtil } from 'o11y/shared';\n\nimport { CoreEnvelope } from './CoreEnvelope';\nimport { CoreEnvelopeBuilder } from './CoreEnvelopeBuilder';\nimport { LogMessage } from './LogMessage';\nimport { StaticAttributes } from './StaticAttributes';\nimport { protobufUtil } from '../protobuf-util';\nimport { getInstrumentation } from '../../index';\n\nconst maxUniqueSchemas = 10000;\nconst maxDelay_msecs = 10000;\nconst uploadThreshold_items = 10;\nconst formDataKey = 'telemetry';\n\nexport enum UploadMode {\n fetchBinary, // application/octet-stream\n fetchFile, // multipart/form-data\n noUpload\n}\n\nexport class CoreCollector implements LogCollector, MetricsCollector {\n private readonly _messageBuffers = new LazyMapToList<Schema, LogMessage>(maxUniqueSchemas);\n private readonly _coreEnvelopeType: Type;\n private _intervalHandle: NodeJS.Timeout;\n private _metricsExtractors: MetricsExtractorMethods;\n private _staticAttributes: StaticAttributes;\n private _immediateUpload: boolean;\n private _instr: Instrumentation = getInstrumentation('CoreCollector');\n\n constructor(\n private readonly _apiEndpoint?: string,\n private readonly _uploadMode?: UploadMode,\n readonly environment?: Environment\n ) {\n if (!_apiEndpoint) {\n this._uploadMode = UploadMode.noUpload;\n } else if (_uploadMode === undefined) {\n this._uploadMode = UploadMode.fetchBinary;\n } else if (!(_uploadMode in UploadMode)) {\n throw new Error(`Unsupported upload mode: ${_uploadMode}`);\n }\n\n const root = Root.fromJSON(coreEnvelopeSchema.pbjsSchema);\n this._coreEnvelopeType = root.lookupType('CoreEnvelope');\n\n if (environment) {\n this._staticAttributes = {\n appName: environment.appName,\n appVersion: environment.appVersion,\n appExperience: environment.appExperience,\n deviceId: environment.deviceId,\n deviceModel: environment.deviceModel,\n sdkVersion: environment.sdkVersion\n };\n }\n }\n\n getIsCollectDisabled(): boolean {\n return this._isFull();\n }\n\n getProtoEncodedCoreEnvelope(): Uint8Array {\n return this._getProtoEncodedCoreEnvelope();\n }\n\n getByteSize(): number {\n return this._messageBuffers.byteSizeOfValues;\n }\n\n private _isFull(): boolean {\n return this._messageBuffers.totalItemCount === this._messageBuffers.maxSize;\n }\n\n private _stopTimer(): void {\n if (this._intervalHandle !== undefined) {\n clearInterval(this._intervalHandle);\n }\n }\n\n private _restartTimer(): void {\n this._stopTimer();\n this._intervalHandle = setInterval(() => {\n this._upload();\n }, maxDelay_msecs);\n }\n\n collect(schema: Schema, data: SchematizedData, logMeta: LogMeta): void {\n const wasEmpty = this._messageBuffers.totalItemCount === 0;\n\n if (schemaUtil.isInternal(schema) && data.userPayload) {\n data.userPayload = protobufUtil.encodePayload(data.userPayload);\n }\n\n if (!this._messageBuffers.push(schema, protobufUtil.getLogMessage(schema, data, logMeta))) {\n // This means that the buffer is full, so we should disable, upload, and reenable once\n // are able to accept more logs\n this._instr.error(new Error('Buffer is full'), schemaUtil.getSchemaId(schema));\n this._stopTimer();\n this._upload();\n } else if (wasEmpty) {\n // Start the timer when we have at least one message\n this._restartTimer();\n }\n\n if (!this.getIsCollectDisabled() && this._shouldUpload()) {\n // Rethink how to do the timer in case we don't get any logs but possibly there are metrics.\n this._stopTimer();\n this._upload();\n }\n }\n\n private _shouldUpload(): boolean {\n return (\n this._immediateUpload || this._messageBuffers.totalItemCount >= uploadThreshold_items\n );\n }\n\n private async _upload(): Promise<void> {\n try {\n if (this._uploadMode === UploadMode.noUpload) {\n // do nothing\n return;\n }\n const buffer: Uint8Array = this._getProtoEncodedCoreEnvelope();\n if (!buffer) {\n // Nothing to upload\n return;\n }\n\n let requestInit;\n switch (this._uploadMode) {\n case UploadMode.fetchBinary:\n requestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/octet-stream'\n },\n body: buffer\n };\n break;\n case UploadMode.fetchFile:\n const formData = new FormData();\n formData.append(formDataKey, new Blob([buffer]));\n // Per [this article](https://muffinman.io/uploading-files-using-fetch-multipart-form-data/)\n // make sure not to set the Content-Type header.\n // The browser will set it for you, including the boundary parameter.\n requestInit = {\n method: 'POST',\n body: formData\n };\n break;\n }\n if (requestInit) {\n await fetch(this._apiEndpoint, requestInit);\n }\n } catch (err) {\n this._instr.error(err);\n }\n }\n\n private _getProtoEncodedCoreEnvelope(): Uint8Array {\n if (!this._messageBuffers.totalItemCount) {\n return undefined;\n }\n const coreEnvelopeBuilder = new CoreEnvelopeBuilder().withStaticAttributes(\n this._staticAttributes\n );\n\n const messages: Map<Schema, LogMessage[]> = this._messageBuffers.extractAllMessages();\n messages.forEach((logs, schema) => {\n coreEnvelopeBuilder.withLogs(schemaUtil.getSchemaId(schema), logs);\n });\n\n if (this._metricsExtractors) {\n coreEnvelopeBuilder\n .withUpCounters(this._metricsExtractors.getAllUpCounters())\n .withValueRecorders(this._metricsExtractors.getAllValueRecorders());\n }\n\n const coreEnvelope: CoreEnvelope = coreEnvelopeBuilder.build();\n const errorMessage = this._coreEnvelopeType.verify(coreEnvelope);\n if (errorMessage) {\n throw new Error(`Invalid CoreEnvelope: ${errorMessage}`);\n }\n\n const encodedCoreEnvelope = this._coreEnvelopeType.encode(coreEnvelope).finish();\n return encodedCoreEnvelope;\n }\n\n receiveMetricsExtractors(metricsExtractors: MetricsExtractorMethods): void {\n this._metricsExtractors = metricsExtractors;\n }\n}\n","import {\n LogCollector,\n LogMeta,\n Metric,\n MetricsCollector,\n MetricsExtractorMethods,\n Schema\n} from '../../interfaces';\nimport { SchematizedData, MetricsTags, schemaUtil, utility } from 'o11y/shared';\nimport { protobufUtil } from '../protobuf-util';\nimport { LogMessage } from '../core-collector/LogMessage';\nimport { EncodedSchematizedPayload } from '../EncodedSchematizedPayload';\nimport { MetricTag } from '../metrics/MetricTag';\nimport { UpCounter } from '../metrics/UpCounter';\nimport { ValueRecorder } from '../metrics/ValueRecorder';\nimport { Metrics } from '../metrics/Metrics';\n\nconst metricsCollectionMilliseconds = 30000;\n\n// The observability plugin expects encoded payloads, so can't use LogMeta as-is.\ninterface LogMetaObservability {\n timestamp: number;\n rootId: string;\n sequence: number;\n loggerName: string;\n pagePayload: EncodedSchematizedPayload;\n loggerAppName: string;\n connectionType: string;\n appPayload: EncodedSchematizedPayload;\n}\n\n// The following interface is expected to be fulfilled by the\n// observability plugin in Lightning SDK.\ndeclare type NimbusObservabilityPlugin = {\n // Called to send a collected message to native for handling\n log: (schema: string, encodedMessage: Uint8Array, logMeta: LogMetaObservability) => void;\n\n // Called to send metrics to native for handling\n logMetrics: (metrics: Metrics) => void;\n\n // Called to listen for root activity changes in native.\n //\n // The startListener is called with the id of the root activity when an activity is started\n // The stopListener is called when a root activity is stopped\n addRootActivityListeners: (\n startListener: (activityInfo: { id: string }) => void,\n stopListener: () => void\n ) => void;\n\n // Called to inform native that the web view has detected an idle state.\n idleDetected: (timestamp: number) => void;\n};\n\n// The `HybridCollector` uses nimbus to send log data immediately across\n// to be handled by the native observability library.\nexport class HybridCollector implements LogCollector, MetricsCollector {\n private readonly _observability: NimbusObservabilityPlugin;\n private _metricsExtractors: MetricsExtractorMethods;\n\n constructor() {\n if (typeof __nimbus === 'undefined') {\n throw new Error('Nimbus is unavailable');\n }\n if (!__nimbus.plugins || !__nimbus.plugins.observability) {\n throw new Error('Observability plugin not found in Nimbus plugins');\n }\n this._observability = __nimbus.plugins.observability as NimbusObservabilityPlugin;\n setInterval(() => {\n this._collectMetrics();\n }, metricsCollectionMilliseconds);\n }\n\n collect(schema: Schema, data: SchematizedData, logMeta: LogMeta): void {\n if (schemaUtil.isInternal(schema) && data.userPayload) {\n data.userPayload = protobufUtil.encodePayload(data.userPayload);\n }\n const logMessage: LogMessage = protobufUtil.getLogMessage(schema, data, logMeta);\n const logMetaObs: LogMetaObservability = {\n timestamp: logMeta.timestamp,\n rootId: logMeta.rootId,\n sequence: logMeta.sequence,\n loggerName: logMeta.loggerName,\n pagePayload: logMessage.pagePayload,\n loggerAppName: logMeta.loggerAppName,\n connectionType: logMeta.connectionType,\n appPayload: logMessage.appPayload\n };\n this._observability.log(schemaUtil.getSchemaId(schema), logMessage.data, logMetaObs);\n }\n\n receiveMetricsExtractors(metricsExtractors: MetricsExtractorMethods): void {\n this._metricsExtractors = metricsExtractors;\n }\n\n // An app can call this method to listen for root activities that start and stop\n // on the native side, in order to associate web activities with the same root id.\n addRootActivityListeners(\n activityStarted: (info: { id: string }) => void,\n activityEnded: () => void\n ): void {\n utility.requireArgument(activityStarted, 'activityStarted', 'function');\n utility.requireArgument(activityEnded, 'activityEnded', 'function');\n\n this._observability.addRootActivityListeners(activityStarted, activityEnded);\n }\n\n // An app should call this method when it detects idle in the web view in order\n // to inform the native app of the idle state.\n notifyIdleDetected(timestamp: number): void {\n this._observability.idleDetected(timestamp);\n }\n\n private _collectMetrics(): void {\n if (this._metricsExtractors) {\n const upCounters: Metric<number>[] = this._metricsExtractors.getAllUpCounters();\n const valueRecorders: Metric<number[]>[] =\n this._metricsExtractors.getAllValueRecorders();\n\n const recorders: ValueRecorder[] = [];\n const counters: UpCounter[] = [];\n\n for (const valueRecorder of valueRecorders) {\n const vr: ValueRecorder = {\n name: valueRecorder.getName(),\n createdTimestamp: valueRecorder.getCreatedOn(),\n lastUpdatedTimestamp: valueRecorder.getLastUpdatedOn(),\n values: valueRecorder.getData(),\n ownerName: valueRecorder.getOwnerName(),\n ownerAppName: valueRecorder.getOwnerAppName(),\n tags: this._getMetricTags(valueRecorder)\n };\n recorders.push(vr);\n valueRecorder.reset();\n }\n\n for (const upCounter of upCounters) {\n const uc: UpCounter = {\n name: upCounter.getName(),\n createdTimestamp: upCounter.getCreatedOn(),\n lastUpdatedTimestamp: upCounter.getLastUpdatedOn(),\n value: upCounter.getData(),\n ownerName: upCounter.getOwnerName(),\n ownerAppName: upCounter.getOwnerAppName(),\n tags: this._getMetricTags(upCounter)\n };\n counters.push(uc);\n upCounter.reset();\n }\n\n if (recorders.length > 0 || counters.length > 0) {\n const metrics: Metrics = {\n upCounters: counters,\n valueRecorders: recorders\n };\n this._observability.logMetrics(metrics);\n }\n }\n }\n\n private _getMetricTags<T>(metric: Metric<T>): MetricTag[] {\n const metricsTags: MetricsTags = metric.getTags();\n\n if (metricsTags) {\n return Object.entries(metricsTags).map((entry) => {\n const mt: MetricTag = {\n name: entry[0],\n value: entry[1].toString()\n };\n return mt;\n });\n }\n return [];\n }\n}\n"],"names":["activity","namespace","name","pbjsSchema","nested","sf","instrumentation","Activity","reserved","fields","duration","options","id","type","stopReason","isRoot","(meta.max_length)","isSampled","preRootId","userPayload","errorCount","Payload","payload","schemaName","core_envelope","MessageBundle","messages","rule","Metrics","valueRecorders","upCounters","CoreEnvelopeDiagnostics","schemaVersion","generatedTimestamp","bundleCount","upCounterCount","valueRecorderCount","key","LogMessage","appPayload","data","rootId","pagePayload","loggerAppName","loggerName","connectionType","age","seq","timestamp","CoreEnvelope","(meta.msg.desc)","diagnostics","bundles","metrics","staticAttributes","MetricTag","value","ValueRecorder","lastUpdatedTimestamp","ownerName","ownerAppName","createdTimestamp","values","tags","StaticAttributes","appVersion","appName","deviceModel","sdkVersion","deviceId","appExperience","UpCounter","error","Error","activityId","stack","message","instrumented_event","MouseEvent","cancelable","ctrlKey","button","offsetX","eventPhase","shiftKey","offsetY","composed","altKey","isTrusted","buttons","movementY","clientY","clientX","movementX","defaultPrevented","metaKey","timeStamp","bubbles","detail","pageY","pageX","screenX","screenY","InstrumentedEvent","oneofs","event","oneof","mouseEvent","auto","parentComponent","ownerComponent","simplePath","simple","Simple","text","version","coreEnvelopeKey","CoreEnvelopeBuilder","[object Object]","this","_envelope","undefined","logs","msgBundle","find","bundle","log","push","length","metric","getTags","Object","entries","map","entry","toString","getName","getCreatedOn","getLastUpdatedOn","getData","getOwnerName","getOwnerAppName","_getMetricTags","reset","utility","time","tsNow","__protobufjs","PublicSafety","_errorCounter","fn","err","_prodSafeCatch","noopValue","requireArgument","allowThrow","isProduction","_safeCatchMode","increment","errorText","internalError","console","defaultTraceIdLengthW3","defaultTraceIdLengthB3","defaultSpanIdLength","headerTraceParent","headerB3","headerTraceId","headerSpanId","headerSampled","headerParentSpanId","defaultActivityNameForFetch","defaultActivityNameForXhrSend","Tracing","instr","traceId","spanId","parentSpanId","b3","numChars","len","toLowerCase","i","c","substr","padStart","useB3Headers","_conformTextAsId","traceIdEffectiveLength","headers","useCompactHeader","_getB3CompactFormat","_getW3CompactFormat","_isNetworkInstrumentationEnabled","_originalFetch","_global","fetch","_originalXhr","XMLHttpRequest","_originalXhrSend","prototype","send","logErrors","activityName","useTracing","_overrideFetch","_overrideXhr","async","url","reqOptions","restArgs","startActivity","traceHeaders","getTraceHeaders","assign","call","ex","stop","args","xhr","_o11yActivity","forEach","setRequestHeader","xhrProxy","Proxy","target","newXhr","addEventListener","__err","discard","_disableNetworkInstrumentation","tracingOptions","_enableNetworkInstrumentation","definedValueOrDefault","tracingHeadersOptions","getGlobal","timedout","terminated","discarded","ActivityImpl","_name","_rootId","_onStopped","_onError","timeout","_isSampled","perfNow","_count","_id","generateUniqueId","_usePerf","performance","mark","measure","_perfName","_perfId","_startTimestamp","_startPerfTime","_timer","setTimeout","_stopReason","_safety","userSchemaOrText","userData","tryCatch","_errorCount","_getDetail","_stopInternal","stopPerfTime","clearMarks","clearMeasures","clearTimeout","isStopped","_stopPerfTime","activityDetail","startTimestamp","startPerfTime","getIsSampled","getHeaders","Array","fill","join","ActivityNoOp","__options","activityNoOp","freeze","DomEventHelpers","eventData","handledBy","instrumentedEvent","tagName","parentElement","getXpath","schemaUtil","makePayload","schema","e","singleton","domEventHelpers","maxFieldLength","minFieldLength","maxFourBytesPos","maxFourBytesNeg","maxFourBytesUnsigned","maxEightBytesPos","maxEightBytesNeg","maxEightBytesUnsigned","LogValidator","schemaTokens","checkSchema","nestedSchema","getTypes","errorMessage","validateFields","getSchemaId","custom","schemaId","isNullOrUndefinedOrEmpty","matchFieldTypes","val","fieldData","fieldType","descriptor","convertedSchemaType","extraContext","isArray","index","Uint8Array","checkNumberRange","Number","isFinite","ref","keys","x","fieldLength","max","min","logValidator","UpCounterImpl","_ownerName","_ownerAppName","_tags","_createdOn","_lastUpdatedOn","_value","Math","round","ValueRecorderImpl","_values","slice","SizeLimitedMap","maxSize","Map","_maxSize","ceil","_map","get","has","size","set","from","clear","maxCounters","maxValueRecorders","MetricType","MetricsImpl","_getOwnerAppName","operation","hasError","_tagError","_upCounter","_valueRecorder","record","sortedTags","_getKeyAndSortedTags","Counter","instrument","_upCounters","Percentile","_valueRecorders","getElements","status","metricType","sort","reduce","prev","curr","JSON","stringify","MockEvent","_composedPaths","maxActivityDurationMsecs","reservedMetricCharacters","reservedMetricNames","denyListMetricNames","InstrumentationImpl","_nextGen","_handleActivityStop","bind","_handleActivityError","reservedChar","indexOf","_incrementError","_metrics","_initMetrics","simpleTextOptions","getOptions","simpleSchema","_simpleTextMaxLength","MAX_VALUE","defaultAppName","incrementCounter","onlyIfBoth","userSchema","_wrapUserPayload","_logInternal","getRootActivityId","_checkInputs","_getPayloadFromProvider","appPayloadProvider","pagePayloadProvider","addLog","_errorInternal","loggedTimestamp","errorData","errorSchema","tryCatchReturn","_onActivityStoppedCallback","_onActivityErrorCallback","isRootActivitySampled","activityData","_getActivityData","_logActivity","activitySchema","provider","getPayload","htmlElement","Event","HTMLElement","template","host","acd","getClickTracker","markEventHandled","mouseEventData","getMouseEventData","getInstrumentedEventData","instrumentedEventSchema","notImplemented","checkForDenyListedValues","checkForReservedCharacters","trackValue","savedUserPayload","isInternal","validate","getUpCounters","filter","m","getValueRecorders","RootActivityImpl","onStopped","onError","super","_preRootId","RootActivityNoOp","rootActivityNoOp","AppInstrumentationImpl","handleRootActivityStop","newRootActivity","_onRootActivityStoppedCallback","rootActivity","getId","terminate","pathLimit","AutomaticClickTracker","document","clickListener","isActive","_boundClickListener","removeEventListener","ignoredEvent","eventTargets","composedPath","path","getClickableElement","domEvent","limit","currentElement","inputElement","maxInstrumentationLength","truncatedText","maxInstrumentationLengthBeforeTruncated","NextgenImpl","Set","_pagePayloadProvider","_appPayloadProvider","enableBuffering","_appInstr","_instruments","_isBufferingEnabled","tracing","networkInstrumentation","startRootActivity","registerLogCollector","registerMetricsCollector","activateClickTracker","deactivateClickTracker","disableBuffering","_sequence","logMeta","sequence","getConnectionType","_buffer","clone","collector","_logCollectors","dataClone","failures","_logCollectorFailures","_forceDisabledLogCollectors","getIsCollectDisabled","collect","_collectorFailureLimit","add","_autoClickTracker","window","activate","deactivate","retroactive","_metricsCollector","receiveMetricsExtractors","getAllUpCounters","getAllValueRecorders","pv","cv","concat","Index","_lazyNextGen","_nextgen","markProduction","retVal","registerApp","getInstrumentation","registerInstrumentedApp","metricsCollectionMilliseconds","HybridCollector","__nimbus","plugins","observability","_observability","setInterval","_collectMetrics","protobufUtil","encodePayload","logMessage","getLogMessage","logMetaObs","metricsExtractors","_metricsExtractors","activityStarted","activityEnded","addRootActivityListeners","idleDetected","recorders","counters","valueRecorder","vr","upCounter","uc","logMetrics","metricsTags"],"mappings":";;;;;;6l7DAAO,MAAMA,SAAS,CAACC,UAAU,qBAAqBC,KAAK,WAAWC,WAAW,CAACC,OAAS,CAACC,GAAK,CAACD,OAAS,CAACE,gBAAkB,CAACF,OAAS,CAACG,SAAW,CAACC,SAAW,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,IAAIC,OAAS,CAACC,SAAW,CAACC,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUC,WAAa,CAACH,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUE,OAAS,CAACJ,QAAU,GAAGC,GAAK,EAAEC,KAAO,QAAQX,KAAO,CAACS,QAAU,CAACK,oBAAoB,IAAIJ,GAAK,EAAEC,KAAO,UAAUI,UAAY,CAACN,QAAU,GAAGC,GAAK,GAAGC,KAAO,QAAQK,UAAY,CAACP,QAAU,GAAGC,GAAK,EAAEC,KAAO,UAAUD,GAAK,CAACD,QAAU,GAC/fC,GAAK,EAAEC,KAAO,UAAUM,YAAc,CAACR,QAAU,GAAGC,GAAK,EAAEC,KAAO,WAAWO,WAAa,CAACT,QAAU,GAAGC,GAAK,GAAGC,KAAO,YAAYQ,QAAU,CAACZ,OAAS,CAAC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