plutin 1.7.4 → 1.7.5

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,"sources":["../node_modules/dotenv/package.json","../node_modules/dotenv/lib/main.js","../node_modules/dotenv/lib/env-options.js","../node_modules/dotenv/lib/cli-options.js","../src/index.ts","../src/core/decorators/dependency-container.ts","../src/core/configs/global-error-handler.ts","../src/core/errors/api-common-error.ts","../src/core/errors/application-error.ts","../src/core/errors/conflict-error.ts","../src/core/errors/domain-error.ts","../src/core/errors/infra-error.ts","../src/core/errors/validation-error.ts","../src/core/http/base-controller.ts","../src/core/decorators/controller-http-decorator.ts","../src/core/entities/unique-object-id.ts","../src/core/entities/entity-object.ts","../src/core/entities/aggregate-object-root.ts","../src/core/entities/unique-entity-id.ts","../src/core/entities/entity.ts","../src/core/entities/aggregate-root.ts","../src/core/entities/value-object.ts","../src/core/entities/watched-list.ts","../src/core/http/get-take-and-skip.ts","../src/infra/adapters/http/express-adapter.ts","../src/infra/adapters/http/response-error-code.ts","../src/infra/adapters/http/validate-controller-metadata.ts","../src/infra/adapters/http/fastify-adapter.ts","../src/infra/adapters/notifications/discord.ts","../src/infra/adapters/notifications/in-memory.ts","../src/infra/adapters/notifications/sentry.ts","../src/infra/adapters/notifications/notification-factory.ts","../src/infra/adapters/validators/zod/zod-map-error.ts","../src/infra/adapters/validators/zod/index.ts","../src/infra/adapters/validators/zod/zod-validator.ts","../src/infra/adapters/logger/winston-otel-fastify.ts","../src/infra/adapters/observability/otel/opentelemetry.ts","../src/infra/adapters/observability/otel/span-decorator.ts","../src/infra/adapters/observability/otel/tracer-gateway-opentelemetry.ts","../src/infra/env/index.ts","../node_modules/dotenv/config.js"],"sourcesContent":["{\n \"name\": \"dotenv\",\n \"version\": \"16.5.0\",\n \"description\": \"Loads environment variables from .env file\",\n \"main\": \"lib/main.js\",\n \"types\": \"lib/main.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/main.d.ts\",\n \"require\": \"./lib/main.js\",\n \"default\": \"./lib/main.js\"\n },\n \"./config\": \"./config.js\",\n \"./config.js\": \"./config.js\",\n \"./lib/env-options\": \"./lib/env-options.js\",\n \"./lib/env-options.js\": \"./lib/env-options.js\",\n \"./lib/cli-options\": \"./lib/cli-options.js\",\n \"./lib/cli-options.js\": \"./lib/cli-options.js\",\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"dts-check\": \"tsc --project tests/types/tsconfig.json\",\n \"lint\": \"standard\",\n \"pretest\": \"npm run lint && npm run dts-check\",\n \"test\": \"tap run --allow-empty-coverage --disable-coverage --timeout=60000\",\n \"test:coverage\": \"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov\",\n \"prerelease\": \"npm test\",\n \"release\": \"standard-version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/motdotla/dotenv.git\"\n },\n \"homepage\": \"https://github.com/motdotla/dotenv#readme\",\n \"funding\": \"https://dotenvx.com\",\n \"keywords\": [\n \"dotenv\",\n \"env\",\n \".env\",\n \"environment\",\n \"variables\",\n \"config\",\n \"settings\"\n ],\n \"readmeFilename\": \"README.md\",\n \"license\": \"BSD-2-Clause\",\n \"devDependencies\": {\n \"@types/node\": \"^18.11.3\",\n \"decache\": \"^4.6.2\",\n \"sinon\": \"^14.0.1\",\n \"standard\": \"^17.0.0\",\n \"standard-version\": \"^9.5.0\",\n \"tap\": \"^19.2.0\",\n \"typescript\": \"^4.8.4\"\n },\n \"engines\": {\n \"node\": \">=12\"\n },\n \"browser\": {\n \"fs\": false\n }\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n const vaultPath = _vaultPath(options)\n\n // Parse .env.vault\n const result = DotenvModule.configDotenv({ path: vaultPath })\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _warn (message) {\n console.log(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n const debug = Boolean(options && options.debug)\n if (debug) {\n _debug('Loading env from encrypted .env.vault')\n }\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n const debug = Boolean(options && options.debug)\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsedAll, options)\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n }\n }\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","// ../config.js accepts options via environment variables\nconst options = {}\n\nif (process.env.DOTENV_CONFIG_ENCODING != null) {\n options.encoding = process.env.DOTENV_CONFIG_ENCODING\n}\n\nif (process.env.DOTENV_CONFIG_PATH != null) {\n options.path = process.env.DOTENV_CONFIG_PATH\n}\n\nif (process.env.DOTENV_CONFIG_DEBUG != null) {\n options.debug = process.env.DOTENV_CONFIG_DEBUG\n}\n\nif (process.env.DOTENV_CONFIG_OVERRIDE != null) {\n options.override = process.env.DOTENV_CONFIG_OVERRIDE\n}\n\nif (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {\n options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY\n}\n\nmodule.exports = options\n","const re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/\n\nmodule.exports = function optionMatcher (args) {\n return args.reduce(function (acc, cur) {\n const matches = cur.match(re)\n if (matches) {\n acc[matches[1]] = matches[2]\n }\n return acc\n }, {})\n}\n","// core configs\nexport * from './core/configs/global-error-handler'\n\n// core decorators\nexport * from './core/decorators/controller-http-decorator'\nexport * from './core/decorators/dependency-container'\n\n// core entities\nexport * from './core/entities/aggregate-object-root'\nexport * from './core/entities/aggregate-root'\nexport * from './core/entities/common-dto'\nexport * from './core/entities/domain-event'\nexport * from './core/entities/entity'\nexport * from './core/entities/entity-object'\nexport * from './core/entities/optional'\nexport * from './core/entities/replace'\nexport * from './core/entities/unique-entity-id'\nexport * from './core/entities/unique-object-id'\nexport * from './core/entities/value-object'\nexport * from './core/entities/watched-list'\n\n// core errors\nexport * from './core/errors/application-error'\nexport * from './core/errors/conflict-error'\nexport * from './core/errors/domain-error'\nexport * from './core/errors/http-client-error'\nexport * from './core/errors/infra-error'\n\n// core http\nexport * from './core/http/base-controller'\nexport * from './core/http/dto-response'\nexport * from './core/http/error-notifier'\nexport * from './core/http/get-take-and-skip'\nexport * from './core/http/health-connections'\nexport * from './core/http/http'\nexport * from './core/http/pagination'\nexport * from './core/http/validator'\n\n// infra adapters http\nexport * from './infra/adapters/http/express-adapter'\nexport * from './infra/adapters/http/fastify-adapter'\n\n// infra adapters notifications\nexport * from './infra/adapters/notifications/discord'\nexport * from './infra/adapters/notifications/in-memory'\nexport * from './infra/adapters/notifications/notification-factory'\nexport * from './infra/adapters/notifications/sentry'\n\n// infra adapters validations\nexport * from './infra/adapters/validators/zod/zod-validator'\n\n// infra adapters observability]\nexport * from './infra/adapters/logger/logger'\nexport * from './infra/adapters/logger/winston-otel-fastify'\nexport * from './infra/adapters/observability/otel/opentelemetry'\nexport * from './infra/adapters/observability/otel/span-decorator'\nexport * from './infra/adapters/observability/otel/tracer-gateway-opentelemetry'\nexport * from './infra/adapters/observability/tracer-gateway'\n\n// infra common\nexport * from './infra/env'\n","import 'reflect-metadata'\n\ntype Class<T = any> = new (...args: any[]) => T\n\ntype Registration =\n | { type: 'class'; myClass: Class; singleton: boolean }\n | { type: 'value'; value: any }\n\nexport class DependencyContainer {\n static registry = new Map<string, Registration>()\n static singletons = new Map<string, any>()\n\n static register<T>(\n token: string,\n myClass: Class<T>,\n options: { singleton: boolean }\n ) {\n this.registry.set(token, {\n type: 'class',\n myClass,\n singleton: options.singleton,\n })\n }\n\n static registerValue<T>(token: string, value: T) {\n this.registry.set(token, { type: 'value', value })\n }\n\n static resolve<T>(target: Class<T>): T {\n const injectMetadata: Record<number, string> =\n Reflect.getOwnMetadata('inject:params', target) || {}\n\n const paramCount = Object.keys(injectMetadata).length\n\n const params = Array.from({ length: paramCount }, (_, index) => {\n const token = injectMetadata[index]\n if (!token) {\n throw new Error(\n `Missing @Inject token for parameter index ${index} in ${target.name}`\n )\n }\n return this.resolveToken(token)\n })\n\n return new target(...params)\n }\n\n static resolveToken(token: string): any {\n const registration = this.registry.get(token)\n\n if (!registration) {\n throw new Error(\n `\"${token}\" not registered. Please register it in the container.`\n )\n }\n\n if (registration.type === 'value') {\n return registration.value\n }\n\n const { myClass, singleton } = registration\n\n if (singleton) {\n if (!this.singletons.has(token)) {\n const instance = this.resolve(myClass)\n this.singletons.set(token, instance)\n }\n return this.singletons.get(token)\n }\n\n return this.resolve(myClass)\n }\n}\n\nexport function Inject(token: string): ParameterDecorator {\n return (\n target: object,\n _propertyKey: string | symbol | undefined,\n parameterIndex: number\n ): void => {\n const constructor =\n typeof target === 'function' ? target : target.constructor\n\n const existingInjectedParams: Record<number, string> =\n Reflect.getOwnMetadata('inject:params', constructor) || {}\n\n existingInjectedParams[parameterIndex] = token\n\n Reflect.defineMetadata('inject:params', existingInjectedParams, constructor)\n }\n}\n","import { DependencyContainer } from '../../core/decorators/dependency-container'\nimport type { IErrorNotifier } from '../../core/http/error-notifier'\n\nexport class GlobalErrorHandler {\n protected readonly errorNotifier: IErrorNotifier\n\n constructor(readonly env: Record<string, any>) {\n this.errorNotifier = DependencyContainer.resolveToken('IErrorNotifier')\n }\n\n register() {\n process.on('uncaughtException', (err) => {\n this.errorNotifier.notify(err, { env: this.env.ENVIRONMENT })\n process.exit(1)\n })\n\n process.on('unhandledRejection', (reason) => {\n if (reason instanceof Error) {\n this.errorNotifier.notify(reason, { env: this.env.ENVIRONMENT })\n } else {\n this.errorNotifier.notify(new Error(String(reason)), {\n env: this.env.ENVIRONMENT,\n })\n }\n\n process.exit(1)\n })\n }\n}\n","export type PropertiesError = {\n receivedValue?: any\n type: string\n message: string\n property: string | number | undefined\n propertyType?: string\n path?: string\n}\n\nexport type CommonError = {\n location: string\n propertyErrors?: PropertiesError[]\n}\n\nexport type ApiCommonError = {\n code: number\n occurredAt: Date\n message: string\n errorCode: string\n errors?: CommonError[]\n}\n\nexport enum ApiErrorEnum {\n DOMAIN = 'ERR001',\n APPLICATION = 'ERR002',\n INFRA = 'ERR003',\n HTTP_CLIENT = 'ERR004',\n VALIDATOR = 'ERR005',\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class ApplicationError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.APPLICATION,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\ntype ConflictProps = { id: string; [key: string]: unknown }\n\nexport default class ConflictError<T extends ConflictProps> extends Error {\n props: ApiCommonError\n conflictProps: T | T[]\n\n constructor(conflictProps: T | T[]) {\n super('Resource already exists.')\n this.conflictProps = conflictProps\n this.props = {\n code: 409,\n errorCode: ApiErrorEnum.APPLICATION,\n message: this.message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class DomainError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.DOMAIN,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class InfraError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.INFRA,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import {\n type ApiCommonError,\n ApiErrorEnum,\n type CommonError,\n} from './api-common-error'\n\nexport default class ValidationError extends Error {\n props: ApiCommonError\n\n constructor(errors: CommonError[]) {\n super('Validation Error')\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.VALIDATOR,\n message: 'Validation Error',\n occurredAt: new Date(),\n errors,\n }\n }\n}\n","import { DependencyContainer } from '../../core/decorators/dependency-container'\nimport ApplicationError from '../../core/errors/application-error'\nimport ConflictError from '../../core/errors/conflict-error'\nimport DomainError from '../../core/errors/domain-error'\nimport InfraError from '../../core/errors/infra-error'\nimport ValidationError from '../../core/errors/validation-error'\nimport { MiddlewareFunction } from '../../infra/adapters/validators/zod/zod-validator'\n\nimport { IErrorNotifier } from './error-notifier'\n\nimport 'reflect-metadata'\n\ntype AnyObject = Record<string, any>\n\nexport type Request = {\n body: AnyObject\n params: AnyObject\n headers: AnyObject\n query: AnyObject\n}\n\nexport type Response = {\n code: number\n data: any\n}\n\nexport type ContextError = {\n env: string\n user?: {\n id?: string\n name?: string\n email?: string\n }\n request?: {\n method?: string\n requestId?: string\n url?: string\n headers?: any\n query?: any\n body?: any\n params?: any\n }\n}\n\nexport abstract class BaseController {\n protected readonly errorNotifier: IErrorNotifier\n\n abstract handle<T>(request: T | Request): Promise<Response>\n\n constructor() {\n this.errorNotifier = DependencyContainer.resolveToken('IErrorNotifier')\n }\n\n protected success<T>(dto?: T): Response {\n return {\n code: 200,\n data: { data: dto },\n }\n }\n\n protected noContent(): Response {\n return {\n code: 204,\n data: undefined,\n }\n }\n\n protected created<T>(dto?: T): Response {\n return {\n code: 201,\n data: dto ? { data: dto } : undefined,\n }\n }\n\n protected paginated<T>(dto?: T): Response {\n return {\n code: 200,\n data: dto,\n }\n }\n\n protected buildContextError(request: Request): ContextError {\n return {\n env: process.env.ENVIRONMENT as string,\n request: {\n body: request.body,\n headers: request.headers,\n params: request.params,\n query: request.query,\n },\n }\n }\n\n public async failure(error: Error, context: ContextError): Promise<Response> {\n if (error instanceof ConflictError) {\n return {\n code: error.props.code,\n data: {\n message: error.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n items: Array.isArray(error.conflictProps)\n ? error.conflictProps\n : [error.conflictProps],\n },\n }\n }\n\n if (\n error instanceof DomainError ||\n error instanceof ApplicationError ||\n error instanceof InfraError\n ) {\n return {\n code: error.props.code,\n data: {\n message: error.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n },\n }\n }\n\n if (error instanceof ValidationError) {\n return {\n code: error.props.code,\n data: {\n message: error.props.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n errors: error.props.errors,\n },\n }\n }\n\n if (process.env.SHOULD_NOTIFY_ERROR) {\n await this.errorNotifier.notify(error, context)\n }\n\n return {\n code: 500,\n data: {\n code: 500,\n message: 'Server failed. Contact the administrator!',\n },\n }\n }\n\n public async execute(request: Request): Promise<Response> {\n const routeMetadata = Reflect.getMetadata('route', this.constructor)\n\n if (!routeMetadata) {\n throw new InfraError('Route metadata not found.')\n }\n\n const middlewares: MiddlewareFunction[] = routeMetadata.middlewares || []\n\n let processedRequest = request\n\n if (middlewares.length) {\n for (const middleware of middlewares) {\n processedRequest = await middleware(processedRequest)\n }\n }\n\n return await this.handle(processedRequest)\n }\n}\n","import { BaseController } from '../../core/http/base-controller'\nimport { MiddlewareFunction } from '../../infra/adapters/validators/zod/zod-validator'\nimport type { MethodType } from '../http/http'\n\ntype Props = {\n method: MethodType\n path: string\n middlewares?: MiddlewareFunction[]\n}\n\nexport function Controller({\n method,\n path,\n middlewares = [],\n}: Props): ClassDecorator {\n return (target: any) => {\n if (!(target.prototype instanceof BaseController)) {\n throw new Error(\n `The class ${target.name} should extends abstract class BaseController`\n )\n }\n\n Reflect.defineMetadata(\n 'route',\n { method, path: `/api/${path}`, middlewares },\n target\n )\n }\n}\n","import { ObjectId } from 'bson'\n\nexport class UniqueObjectId {\n private value: ObjectId\n\n constructor(value?: string) {\n this.value = new ObjectId(value)\n }\n\n toString() {\n return this.value.toString()\n }\n\n toValue() {\n return this.value.toString()\n }\n\n public equals(id: UniqueObjectId) {\n return id.toValue() === this.toValue()\n }\n}\n","import type { CommonDTO } from './common-dto'\nimport { UniqueObjectId } from './unique-object-id'\n\ntype PropsWithCommonDTO<Props> = Props & CommonDTO\n\nexport abstract class EntityObject<Props> {\n private _id: UniqueObjectId\n protected props: PropsWithCommonDTO<Props>\n\n get id() {\n return this._id\n }\n\n set id(id: UniqueObjectId) {\n this._id = id\n }\n\n get createdAt() {\n return this.props.createdAt\n }\n\n set createdAt(date: Date) {\n this.props.createdAt = date\n }\n\n get updatedAt(): Date | undefined | null {\n return this.props.updatedAt\n }\n\n public touch() {\n this.props.updatedAt = new Date()\n }\n\n protected constructor(props: PropsWithCommonDTO<Props>, id?: UniqueObjectId) {\n this._id = id ?? new UniqueObjectId(id)\n this.props = props\n }\n\n public equals(entity: EntityObject<Props>) {\n if (entity === this) {\n return true\n }\n\n if (entity.id === this._id) {\n return true\n }\n\n return false\n }\n}\n","import { EntityObject } from './entity-object'\n\nexport abstract class AggregateObjectRoot<Props> extends EntityObject<Props> {}\n","import { randomUUID } from 'node:crypto'\n\nexport class UniqueEntityId {\n private value: string\n\n constructor(value?: string) {\n this.value = value ?? randomUUID()\n }\n\n toString() {\n return this.value\n }\n\n toValue() {\n return this.value\n }\n\n public equals(id: UniqueEntityId) {\n return id.toValue() === this.toValue()\n }\n}\n","import { CommonDTO } from './common-dto'\nimport { UniqueEntityId } from './unique-entity-id'\n\ntype PropsWithCommonDTO<Props> = Props & CommonDTO\n\nexport abstract class Entity<Props> {\n private _id: UniqueEntityId\n protected props: PropsWithCommonDTO<Props>\n\n get id() {\n return this._id\n }\n\n set id(id: UniqueEntityId) {\n this._id = id\n }\n\n get createdAt() {\n return this.props.createdAt\n }\n\n set createdAt(date: Date) {\n this.props.createdAt = date\n }\n\n get updatedAt(): Date | undefined | null {\n return this.props.updatedAt\n }\n\n public touch() {\n this.props.updatedAt = new Date()\n }\n\n protected constructor(props: PropsWithCommonDTO<Props>, id?: UniqueEntityId) {\n this._id = id ?? new UniqueEntityId(id)\n this.props = props\n }\n\n public equals(entity: Entity<any>) {\n if (entity === this) {\n return true\n }\n\n if (entity.id === this._id) {\n return true\n }\n\n return false\n }\n}\n","import { Entity } from './entity'\n\nexport abstract class AggregateRoot<Props> extends Entity<Props> {}\n","export abstract class ValueObject<Props> {\n protected props: Props\n\n protected constructor(props: Props) {\n this.props = props\n }\n}\n","export abstract class WatchedList<T> {\n public currentItems: T[]\n private initial: T[]\n private new: T[]\n private removed: T[]\n private updated: T[]\n\n constructor(initialItems?: T[]) {\n this.currentItems = initialItems || []\n this.initial = initialItems || []\n this.new = []\n this.removed = []\n this.updated = []\n }\n\n abstract compareItems(a: T, b: T): boolean\n\n public getItems(): T[] {\n return this.currentItems\n }\n\n public getNewItems(): T[] {\n return this.new\n }\n\n public getRemovedItems(): T[] {\n return this.removed\n }\n\n public getUpdatedItems(): T[] {\n return this.updated\n }\n\n public addUpdatedItem(item: T) {\n return this.updated.push(item)\n }\n\n private isCurrentItem(item: T): boolean {\n return (\n this.currentItems.filter((v: T) => this.compareItems(item, v)).length !==\n 0\n )\n }\n\n private isNewItem(item: T): boolean {\n return this.new.filter((v: T) => this.compareItems(item, v)).length !== 0\n }\n\n private isRemovedItem(item: T): boolean {\n return (\n this.removed.filter((v: T) => this.compareItems(item, v)).length !== 0\n )\n }\n\n private removeFromNew(item: T): void {\n this.new = this.new.filter((v) => !this.compareItems(v, item))\n }\n\n private removeFromCurrent(item: T): void {\n this.currentItems = this.currentItems.filter(\n (v) => !this.compareItems(item, v)\n )\n }\n\n private removeFromRemoved(item: T): void {\n this.removed = this.removed.filter((v) => !this.compareItems(item, v))\n }\n\n private wasAddedInitially(item: T): boolean {\n return (\n this.initial.filter((v: T) => this.compareItems(item, v)).length !== 0\n )\n }\n\n public exists(item: T): boolean {\n return this.isCurrentItem(item)\n }\n\n public add(item: T): void {\n if (this.isRemovedItem(item)) {\n this.removeFromRemoved(item)\n }\n\n if (!this.isNewItem(item) && !this.wasAddedInitially(item)) {\n this.new.push(item)\n }\n\n if (!this.isCurrentItem(item)) {\n this.currentItems.push(item)\n }\n }\n\n public remove(item: T): void {\n this.removeFromCurrent(item)\n\n if (this.isNewItem(item)) {\n this.removeFromNew(item)\n\n return\n }\n\n if (!this.isRemovedItem(item)) {\n this.removed.push(item)\n }\n }\n\n public update(items: T[]): void {\n const newItems = items.filter((a) => {\n return !this.getItems().some((b) => this.compareItems(a, b))\n })\n\n const removedItems = this.getItems().filter((a) => {\n return !items.some((b) => this.compareItems(a, b))\n })\n\n const updatedItems = items.filter(\n (item) =>\n !newItems.some(\n (a) =>\n this.compareItems(item, a) &&\n !removedItems.some((b) => this.compareItems(item, b))\n )\n )\n\n this.currentItems = items\n this.new = newItems\n this.removed = removedItems\n this.updated = updatedItems\n }\n}\n","export function getTakeAndSkip(size: string, page: string) {\n const take = size ? Number(size) : 20\n const skip = page ? Number(page) : 1\n\n return { take, skip }\n}\n","import cors from 'cors'\nimport express, { Express, Request, Response } from 'express'\n\nimport type { BaseController } from '../../../core/http/base-controller'\nimport { IHttp } from '../../../core/http/http'\n\nimport { ErrorResponseCode } from './response-error-code'\nimport { validateControllerMetadata } from './validate-controller-metadata'\n\nexport class ExpressAdapter implements IHttp {\n readonly instance: Express\n private server: any\n\n constructor(\n readonly env: Record<string, any>,\n readonly logger: any\n ) {\n this.instance = express()\n this.instance.use(cors())\n this.instance.use(express.json({ limit: '10mb' }))\n this.instance.use(express.urlencoded({ limit: '10mb', extended: false }))\n this.instance.disable('x-powered-by')\n }\n\n registerRoute(controllerClass: BaseController): void {\n const { metadata } = validateControllerMetadata(controllerClass)\n\n this.instance[metadata.method](\n metadata.path,\n async (request: Request, response: Response) => {\n const requestData = {\n body: request.body,\n params: request.params,\n headers: request.headers,\n query: request.query,\n }\n\n try {\n const output = await controllerClass.execute(requestData)\n response\n .status(output.code || 204)\n .json(output.data || { code: ErrorResponseCode.NO_CONTENT_BODY })\n } catch (err: any) {\n const error = await controllerClass.failure(err, {\n env: this.env.ENVIRONMENT,\n request: {\n body: requestData.body,\n headers: requestData.headers,\n params: request.params,\n query: requestData.query,\n url: metadata.path,\n method: metadata.method,\n },\n })\n response.status(error.code).json(\n error.data || {\n error: ErrorResponseCode.NO_CONTENT_ERROR,\n }\n )\n }\n }\n )\n }\n\n async startServer(port: number): Promise<void> {\n return new Promise((resolve) => {\n this.server = this.instance.listen(port, () => {\n this.logger.info(`Server is running on PORT ${port}`)\n resolve()\n })\n })\n }\n\n async closeServer(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (this.server) {\n this.server.close((err: any) => {\n if (err) return reject(err)\n resolve()\n })\n } else {\n resolve()\n }\n })\n }\n}\n","export enum ErrorResponseCode {\n NO_CONTENT_BODY = 'B001',\n NO_CONTENT_ERROR = 'B002',\n}\n","import { BaseController } from '../../../core/http/base-controller'\nimport type { MethodType } from '../../../core/http/http'\n\nimport 'reflect-metadata'\n\nexport function validateControllerMetadata(controller: BaseController) {\n const metadata = Reflect.getMetadata('route', controller.constructor) as {\n method: MethodType\n path: string\n }\n\n if (!metadata) {\n throw new Error(\n `Controller ${controller.constructor.name} not have metadata. Need to add decorator.`\n )\n }\n\n return {\n metadata,\n }\n}\n","import cors from '@fastify/cors'\nimport { IHttp } from 'core/http/http'\nimport fastify, { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport qs from 'qs'\n\nimport { BaseController, Request } from '../../../core/http/base-controller'\n\nimport { ErrorResponseCode } from './response-error-code'\nimport { validateControllerMetadata } from './validate-controller-metadata'\n\nexport class FastifyAdapter implements IHttp {\n readonly instance: FastifyInstance\n\n constructor(\n readonly env: Record<string, any>,\n readonly logger: any\n ) {\n this.instance = fastify({\n bodyLimit: 10 * 1024 * 1024,\n querystringParser: (str) => qs.parse(str),\n loggerInstance: env.ENVIRONMENT !== 'test' ? logger : false,\n })\n\n this.instance.register(cors)\n }\n\n registerRoute(controllerClass: BaseController): void {\n const { metadata } = validateControllerMetadata(controllerClass)\n\n this.instance[metadata.method](\n metadata.path,\n async (request: FastifyRequest, reply: FastifyReply) => {\n const requestData = {\n body: request.body,\n params: request.params,\n headers: request.headers,\n query: request.query,\n } as Request\n\n try {\n const output = await controllerClass.execute(requestData)\n return reply.status(output.code || 200).send(\n output.data || {\n code: ErrorResponseCode.NO_CONTENT_BODY,\n }\n )\n } catch (err: any) {\n const error = await controllerClass.failure(err, {\n env: this.env.ENVIRONMENT,\n request: {\n body: requestData.body,\n headers: requestData.headers,\n params: request.params,\n query: requestData.query,\n url: metadata.path,\n method: metadata.method,\n },\n })\n return reply.status(error.code || 200).send(\n error.data || {\n code: ErrorResponseCode.NO_CONTENT_ERROR,\n }\n )\n }\n }\n )\n }\n\n async startServer(port: number): Promise<void> {\n await this.instance.listen({ port })\n\n if (this.env.NODE_ENV !== 'test') {\n this.logger.info(`Server is running on PORT ${port}`)\n }\n }\n\n async closeServer() {\n await this.instance.close()\n }\n}\n","import { Inject } from 'core/decorators/dependency-container'\nimport { MessageBuilder, Webhook } from 'discord-webhook-node'\n\nimport type { ContextError } from '../../../core/http/base-controller'\nimport type { IErrorNotifier } from '../../../core/http/error-notifier'\n\ntype DiscordOptions = {\n url: string\n env: string\n}\n\nexport class DiscordNotifier implements IErrorNotifier {\n private webhook: Webhook\n\n constructor(\n @Inject('DiscordConfig') private readonly options: DiscordOptions\n ) {\n this.webhook = new Webhook(this.options.url)\n }\n\n async notify(error: Error, context: ContextError): Promise<void> {\n const embed = new MessageBuilder()\n .setTitle('🚨 Error')\n .addField('Message', `\\`\\`\\`${error.message.slice(0, 300)}\\`\\`\\``)\n .addField(\n 'Route:',\n `\\`[${context?.request?.method}] ${context?.request?.url}\\``,\n true\n )\n .addField(\n 'Params:',\n '```json\\n' +\n JSON.stringify(context?.request?.params, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Query:',\n '```json\\n' +\n JSON.stringify(context?.request?.query, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Headers:',\n '```json\\n' +\n JSON.stringify(context?.request?.headers, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Body:',\n '```json\\n' + JSON.stringify(context?.request?.body, null, 2) + '\\n```'\n )\n .addField(\n 'Stack Trace:',\n '```' + (error.stack || 'No stack provided').slice(0, 900) + '```'\n )\n .setFooter(`Env: ${this.options.env || 'development'}`)\n .setTimestamp()\n\n await this.webhook.send(embed)\n }\n}\n","import type { ContextError } from '../../../core/http/base-controller'\nimport type { IErrorNotifier } from '../../../core/http/error-notifier'\n\nexport class NotificationErrorInMemory implements IErrorNotifier {\n public errors: any[] = []\n\n async notify(error: Error, context?: ContextError): Promise<void> {\n console.error(error)\n\n this.errors.push({\n error: error.message,\n context,\n })\n }\n}\n","import * as Sentry from '@sentry/node'\nimport type { ContextError } from 'core/http/base-controller'\n\nimport { Inject } from '../../../core/decorators/dependency-container'\nimport { IErrorNotifier } from '../../../core/http/error-notifier'\n\ntype SentryOptions = {\n dsn: string\n environment: string\n}\n\nexport class SentryNotifier implements IErrorNotifier {\n constructor(@Inject('SentryConfig') private readonly options: SentryOptions) {\n Sentry.init({\n dsn: this.options.dsn,\n environment: this.options.environment,\n attachStacktrace: true,\n tracesSampleRate: this.options.environment === 'production' ? 0.1 : 1.0,\n maxBreadcrumbs: 100,\n debug: this.options.environment !== 'production',\n })\n }\n\n async notify(error: Error, context: ContextError): Promise<void> {\n Sentry.withScope((scope) => {\n scope.setLevel('error')\n\n if (context?.env) scope.setTag('env', context.env)\n\n if (context?.user) {\n scope.setUser({\n id: context.user.id,\n username: context.user.name,\n email: context.user.email,\n })\n }\n\n if (context?.request) {\n const { body, query, params, headers, method, url, requestId } =\n context.request\n\n scope.setContext('http', {\n method,\n requestId,\n url,\n headers,\n query,\n body,\n params,\n })\n }\n\n Sentry.captureException(error)\n })\n }\n}\n","import type { z } from 'zod'\n\nimport type { baseEnvSchema } from '../../env'\n\nimport { DiscordNotifier } from './discord'\nimport { NotificationErrorInMemory } from './in-memory'\nimport { SentryNotifier } from './sentry'\n\ntype OptionsNotifications = 'console' | 'discord' | 'sentry'\ntype EnvironmentEnum = z.infer<typeof baseEnvSchema>['ENVIRONMENT']\n\ntype Props = {\n test?: OptionsNotifications\n development?: OptionsNotifications\n staging?: OptionsNotifications\n production?: OptionsNotifications\n}\n\nexport class NotificationFactory {\n static define(env: EnvironmentEnum, definitions?: Props): any {\n const defaultDefinition = {\n test: this.defineProvider(definitions?.test ?? 'console'),\n development: this.defineProvider(definitions?.development ?? 'console'),\n staging: this.defineProvider(definitions?.staging ?? 'discord'),\n production: this.defineProvider(definitions?.production ?? 'sentry'),\n }\n\n return defaultDefinition[env]\n }\n\n private static defineProvider(provider: OptionsNotifications) {\n switch (provider) {\n case 'console':\n return NotificationErrorInMemory\n case 'discord':\n return DiscordNotifier\n case 'sentry':\n return SentryNotifier\n default:\n return NotificationErrorInMemory\n }\n }\n}\n","import type { ZodIssue } from 'zod'\n\nimport type {\n CommonError,\n PropertiesError,\n} from '../../../../core/errors/api-common-error'\n\ntype ZodError = ZodIssue & {\n expected: string\n received: string\n}\n\ntype ZodInvalidUnion = ZodError & {\n code: 'invalid_union'\n}\n\nexport default class ZodMapError {\n private static mapCommon(error: ZodError): PropertiesError {\n return {\n type: error.code,\n path: error.path.join('.'),\n property: error.path.pop(),\n propertyType: error.expected,\n receivedValue: error.received,\n message: error.message,\n }\n }\n\n private static mapInvalidUnion(error: ZodInvalidUnion): PropertiesError[] {\n const [errors] = error.unionErrors\n .flat()\n .map((err) => err.issues.map((item: any) => this.mapCommon(item)))\n\n return errors\n }\n\n private static mapInvalidType(error: ZodError): PropertiesError[] {\n return [this.mapCommon(error)]\n }\n\n private static mapErrorsFactory(error: ZodError): PropertiesError[] {\n if (error.code === 'invalid_union') {\n return this.mapInvalidUnion(error)\n }\n\n return this.mapInvalidType(error)\n }\n\n static mapErrors(errors: ZodIssue[][]) {\n const standardizedErrors = new Map<string | number, CommonError>()\n\n errors.flat().forEach((error) => {\n const keyError = standardizedErrors.get(error.path[0])\n\n if (keyError) {\n if (!keyError.propertyErrors) {\n keyError.propertyErrors = []\n }\n\n keyError.propertyErrors.push(\n ...this.mapErrorsFactory(error as ZodError)\n )\n\n return\n }\n\n standardizedErrors.set(error.path[0], {\n location: error.path[0],\n propertyErrors: Array.from([\n ...this.mapErrorsFactory(error as ZodError),\n ]),\n } as CommonError)\n })\n\n return Array.from(standardizedErrors, ([, arr]) => ({\n ...arr,\n })).flat()\n }\n}\n","import { ZodEffects, type ZodError, ZodObject } from 'zod'\n\nimport ValidationError from '../../../../core/errors/validation-error'\nimport IValidationHTTP, { RequestHttp } from '../../../../core/http/validator'\n\nimport ZodMapError from './zod-map-error'\nimport { zodValidator } from './zod-validator'\n\ntype SchemaDefinition = {\n headers: ZodObject<Record<string, any>>\n params: ZodObject<Record<string, any>>\n query: ZodObject<Record<string, any>>\n body:\n | ZodObject<Record<string, any>>\n | ZodEffects<ZodObject<Record<string, any>>>\n}\n\ntype ZodSchemaObject = ZodObject<SchemaDefinition>\n\nexport default class ZodValidator implements IValidationHTTP {\n constructor(private zodSchema: ZodSchemaObject) {}\n\n async validate<T>(requestHttp: RequestHttp): Promise<T> {\n const errors = []\n\n const {\n data: headersData = {},\n error: headersErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.headers\n ? await this.zodSchema.shape.headers.safeParseAsync(requestHttp.headers, {\n path: ['headers'],\n })\n : {}\n\n if (headersErrors?.errors) {\n errors.push(headersErrors?.errors)\n }\n\n const {\n data: paramsData = {},\n error: paramsErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.params\n ? await this.zodSchema.shape.params.safeParseAsync(requestHttp.params, {\n path: ['params'],\n })\n : {}\n\n if (paramsErrors?.errors) {\n errors.push(paramsErrors?.errors)\n }\n\n const {\n data: queryData = {},\n error: queryErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.query\n ? await this.zodSchema.shape.query.safeParseAsync(requestHttp.query, {\n path: ['query'],\n })\n : {}\n\n if (queryErrors?.errors) {\n errors.push(queryErrors?.errors)\n }\n\n const {\n data: bodyData = {},\n error: bodyErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.body\n ? await this.zodSchema.shape.body.safeParseAsync(requestHttp.body, {\n path: ['body'],\n })\n : {}\n\n if (bodyErrors?.errors) {\n errors.push(bodyErrors?.errors)\n }\n\n if (errors.length) {\n throw new ValidationError(ZodMapError.mapErrors(errors))\n }\n\n return {\n body: bodyData,\n headers: headersData,\n params: paramsData,\n query: queryData,\n } as T\n }\n}\n\nexport { zodValidator }\n","import { z } from 'zod'\n\nimport { Request } from '../../../../core/http/base-controller'\n\nimport ZodValidator from './index'\n\nexport type ZodSchema = z.ZodObject<{\n headers: z.ZodObject<Record<string, any>>\n params: z.ZodObject<Record<string, any>>\n query: z.ZodObject<Record<string, any>>\n body:\n | z.ZodObject<Record<string, any>>\n | z.ZodEffects<z.ZodObject<Record<string, any>>>\n}>\n\nexport type MiddlewareFunction = (request: Request) => Promise<Request>\n\nexport function zodValidator(schema: ZodSchema): MiddlewareFunction {\n return async (request: Request): Promise<Request> => {\n const validator = new ZodValidator(schema)\n const validatedRequest = await validator.validate<Request>(request)\n return validatedRequest\n }\n}\n","import opentelemetry from '@opentelemetry/api'\nimport { Logger, logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { FastifyReply, FastifyRequest } from 'fastify'\nimport winston from 'winston'\n\nimport type { ILogger } from './logger'\n\nclass WinstonOtelFastify implements ILogger {\n logger: Logger\n consoleLogger: winston.Logger\n level: 'info' | 'error' | 'debug' | 'fatal' | 'warn' = 'info'\n\n constructor() {\n if (process.env.OTEL_ENABLE) {\n this.logger = logs.getLogger(\n process.env.OTEL_SERVICE_NAME!,\n process.env.OTEL_SERVICE_VERSION\n )\n\n this.level = process.env.LOG_LEVEL as any\n\n const transports =\n process.env.NODE_ENV === 'test'\n ? [new winston.transports.Console({ silent: true })]\n : [new winston.transports.Console()]\n\n this.consoleLogger = winston.createLogger({\n level: this.level,\n format: winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),\n winston.format((info) => {\n if (process.env.NODE_ENV !== 'test') {\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span) {\n info.spanId = span.spanContext().spanId\n info.traceId = span.spanContext().traceId\n }\n }\n\n return info\n })(),\n winston.format.json()\n ),\n transports,\n })\n } else {\n this.consoleLogger = winston.createLogger({\n level: this.level,\n format: winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),\n winston.format.json()\n ),\n })\n }\n }\n\n private bodyIsFastifyRequest(\n body: string | FastifyRequest | FastifyReply\n ): body is FastifyRequest {\n return (body as FastifyRequest).method !== undefined\n }\n\n private bodyIsFastifyReply(\n body: string | FastifyRequest | FastifyReply\n ): body is FastifyReply {\n return (body as FastifyReply).statusCode !== undefined\n }\n\n private buildMessage(\n body: string | { req?: FastifyRequest; res?: FastifyReply }\n ) {\n if (\n typeof body === 'object' &&\n body.req &&\n this.bodyIsFastifyRequest(body.req)\n ) {\n return `${body.req.method} ${body.req.url}`\n } else if (\n typeof body === 'object' &&\n body.res &&\n this.bodyIsFastifyReply(body.res)\n ) {\n return `${body.res.request.method} ${body.res.request.url} ${body.res.statusCode} - ${body.res.elapsedTime} ms`\n } else if (typeof body === 'string') {\n return body\n } else {\n return ''\n }\n }\n\n private logMessage(\n body: string | { req?: FastifyRequest; res?: FastifyReply },\n severityNumber: SeverityNumber,\n severityText: string\n ) {\n const message = this.buildMessage(body)\n\n this.consoleLogger[severityText.toLowerCase() as keyof Logger](message)\n\n if (process.env.NODE_ENV !== 'test') {\n this.logger.emit({\n body: message,\n severityNumber,\n severityText,\n })\n }\n }\n\n info(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.INFO, 'INFO')\n }\n\n error(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.ERROR, 'ERROR')\n }\n\n debug(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.DEBUG, 'DEBUG')\n }\n\n fatal(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.FATAL, 'FATAL')\n }\n\n warn(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.WARN, 'WARN')\n }\n\n trace(message: string) {\n if (process.env.NODE_ENV !== 'test') {\n this.logger.emit({\n body: message,\n severityNumber: SeverityNumber.TRACE,\n severityText: 'TRACE',\n })\n }\n }\n\n child(): WinstonOtelFastify {\n return new WinstonOtelFastify()\n }\n}\n\nexport { WinstonOtelFastify }\n","import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'\nimport { Resource } from '@opentelemetry/resources'\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport {\n SEMRESATTRS_SERVICE_NAME,\n SEMRESATTRS_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions'\n\nclass OpenTelemetry {\n sdk: NodeSDK\n\n constructor(private readonly env: Record<string, any>) {\n this.sdk = new NodeSDK({\n resource: new Resource({\n [SEMRESATTRS_SERVICE_NAME]: this.env.OTEL_SERVICE_NAME,\n [SEMRESATTRS_SERVICE_VERSION]: this.env.OTEL_SERVICE_VERSION,\n }),\n traceExporter: new OTLPTraceExporter({\n url: this.env.OTEL_OTLP_TRACES_EXPORTER_URL,\n }),\n logRecordProcessor: new BatchLogRecordProcessor(\n new OTLPLogExporter({\n url: this.env.OTEL_OTLP_LOGS_EXPORTER_URL,\n }),\n {\n maxQueueSize: 100,\n maxExportBatchSize: 5,\n scheduledDelayMillis: 1000,\n exportTimeoutMillis: 30000,\n }\n ),\n metricReader: new PeriodicExportingMetricReader({\n exporter: new OTLPMetricExporter({\n url: this.env.OTEL_OTLP_METRICS_EXPORTER_URL,\n }),\n }),\n })\n }\n\n startSdk() {\n this.sdk.start()\n }\n}\n\nexport { OpenTelemetry }\n","import opentelemetry, { SpanStatusCode, Tracer } from '@opentelemetry/api'\n\nimport 'reflect-metadata'\n\nexport function Span(): MethodDecorator {\n return function (\n target: any,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ) {\n if (!process.env.OTEL_ENABLE) {\n return descriptor\n }\n\n const originalMethod = descriptor.value\n\n descriptor.value = function (...args: any[]) {\n const tracer: Tracer = opentelemetry.trace.getTracer(\n process.env.OTEL_SERVICE_NAME!,\n process.env.OTEL_SERVICE_VERSION!\n )\n\n const className = target.constructor?.name || 'UnknownClass'\n const methodName = String(propertyKey)\n const spanName = `${className}.${methodName}`\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n const result = originalMethod.apply(this, args)\n\n if (result instanceof Promise) {\n try {\n const awaitedResult = await result\n span.addEvent(`Method [${methodName}] executed successfully`)\n span.end()\n return awaitedResult\n } catch (error) {\n handleSpanError(span, error)\n throw error\n }\n } else {\n span.addEvent(`Method [${methodName}] executed successfully`)\n span.end()\n return result\n }\n } catch (error) {\n handleSpanError(span, error)\n throw error\n }\n })\n }\n\n return descriptor\n }\n}\n\nfunction handleSpanError(span: any, error: unknown): void {\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n if (error instanceof Error) {\n span.recordException(error)\n } else {\n span.recordException(new Error(String(error)))\n }\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n })\n\n span.end()\n}\n","import opentelemetry from '@opentelemetry/api'\n\nimport type { ITracerGateway } from '../tracer-gateway'\n\nexport class TracerGatewayOpentelemetry implements ITracerGateway {\n addEvent(name: string, attributes?: Record<string, any>): void {\n if (!process.env.OTEL_ENABLE) {\n return\n }\n\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span && attributes) {\n span.addEvent(name, attributes)\n } else if (span) {\n span.addEvent(name)\n }\n }\n\n setAttribute(key: string, value: string | number | boolean): void {\n if (!process.env.OTEL_ENABLE) {\n return\n }\n\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span) {\n span.setAttribute(key, value)\n }\n }\n}\n","import { z } from 'zod'\n\nimport 'dotenv/config'\n\nexport const baseEnvSchema = z.object({\n NODE_ENV: z.enum(['test', 'development', 'production']).default('production'),\n ENVIRONMENT: z\n .enum(['test', 'development', 'staging', 'production'])\n .default('development'),\n PORT: z.coerce.number().default(3333),\n SHOULD_NOTIFY_ERROR: z.coerce.boolean().default(true),\n SENTRY_DSN: z.string().optional(),\n DISCORD_WEBHOOK_URL: z.string().optional(),\n LOG_LEVEL: z\n .enum(['info', 'error', 'debug', 'fatal', 'warn'])\n .default('info'),\n OTEL_ENABLE: z.coerce.boolean().default(false),\n OTEL_SERVICE_NAME: z.string().optional(),\n OTEL_SERVICE_VERSION: z.string().optional(),\n OTEL_OTLP_TRACES_EXPORTER_URL: z.string().url().optional(),\n OTEL_OTLP_LOGS_EXPORTER_URL: z.string().url().optional(),\n OTEL_OTLP_METRICS_EXPORTER_URL: z.string().url().optional(),\n})\n","(function () {\n require('./lib/main').config(\n Object.assign(\n {},\n require('./lib/env-options'),\n require('./lib/cli-options')(process.argv)\n )\n )\n})()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,8CAAAA,SAAA;AAAA,IAAAA,QAAA;AAAA,MACE,MAAQ;AAAA,MACR,SAAW;AAAA,MACX,aAAe;AAAA,MACf,MAAQ;AAAA,MACR,OAAS;AAAA,MACT,SAAW;AAAA,QACT,KAAK;AAAA,UACH,OAAS;AAAA,UACT,SAAW;AAAA,UACX,SAAW;AAAA,QACb;AAAA,QACA,YAAY;AAAA,QACZ,eAAe;AAAA,QACf,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,qBAAqB;AAAA,QACrB,wBAAwB;AAAA,QACxB,kBAAkB;AAAA,MACpB;AAAA,MACA,SAAW;AAAA,QACT,aAAa;AAAA,QACb,MAAQ;AAAA,QACR,SAAW;AAAA,QACX,MAAQ;AAAA,QACR,iBAAiB;AAAA,QACjB,YAAc;AAAA,QACd,SAAW;AAAA,MACb;AAAA,MACA,YAAc;AAAA,QACZ,MAAQ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obj","lines","toString","replace","match","exec","key","value","trim","maybeQuote","_parseVault","options","vaultPath","_vaultPath","result","DotenvModule","configDotenv","parsed","err","Error","code","keys","_dotenvKey","split","length","decrypted","i","attrs","_instructions","decrypt","ciphertext","error","_warn","message","console","log","_debug","DOTENV_KEY","process","env","dotenvKey","uri","URL","password","environment","searchParams","get","environmentKey","toUpperCase","possibleVaultPath","Array","isArray","filepath","existsSync","endsWith","resolve","cwd","_resolveHome","envPath","join","homedir","slice","_configVault","debug","Boolean","processEnv","populate","dotenvPath","encoding","optionPaths","push","lastError","parsedAll","readFileSync","e","config","encrypted","keyStr","Buffer","from","nonce","subarray","authTag","aesgcm","createDecipheriv","setAuthTag","update","final","isRange","RangeError","invalidKeyLength","decryptionFailed","override","Object","prototype","hasOwnProperty","call","exports","module","options","process","env","DOTENV_CONFIG_ENCODING","encoding","DOTENV_CONFIG_PATH","path","DOTENV_CONFIG_DEBUG","debug","DOTENV_CONFIG_OVERRIDE","override","DOTENV_CONFIG_DOTENV_KEY","DOTENV_KEY","exports","module","re","exports","optionMatcher","args","reduce","acc","cur","matches","match","DependencyContainer","registry","Map","singletons","register","token","myClass","options","set","type","singleton","registerValue","value","resolve","target","injectMetadata","Reflect","getOwnMetadata","paramCount","Object","keys","length","params","Array","from","_","index","Error","name","resolveToken","registration","get","has","instance","Inject","_propertyKey","parameterIndex","constructor","existingInjectedParams","defineMetadata","GlobalErrorHandler","errorNotifier","constructor","env","DependencyContainer","resolveToken","register","process","on","err","notify","ENVIRONMENT","exit","reason","Error","String","ApiErrorEnum","ApplicationError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","APPLICATION","occurredAt","Date","ConflictError","Error","props","conflictProps","constructor","code","errorCode","ApiErrorEnum","APPLICATION","message","occurredAt","Date","DomainError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","DOMAIN","occurredAt","Date","InfraError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","INFRA","occurredAt","Date","ValidationError","Error","props","constructor","errors","code","errorCode","ApiErrorEnum","VALIDATOR","message","occurredAt","Date","import_reflect_metadata","BaseController","errorNotifier","constructor","DependencyContainer","resolveToken","success","dto","code","data","noContent","undefined","created","paginated","buildContextError","request","env","process","ENVIRONMENT","body","headers","params","query","failure","error","context","ConflictError","props","message","errorCode","occurredAt","items","Array","isArray","conflictProps","DomainError","ApplicationError","InfraError","ValidationError","errors","SHOULD_NOTIFY_ERROR","notify","execute","routeMetadata","Reflect","getMetadata","middlewares","processedRequest","length","middleware","handle","Controller","method","path","middlewares","target","prototype","BaseController","Error","name","Reflect","defineMetadata","UniqueObjectId","value","constructor","ObjectId","toString","toValue","equals","id","EntityObject","_id","props","id","createdAt","date","updatedAt","touch","Date","UniqueObjectId","equals","entity","AggregateObjectRoot","EntityObject","UniqueEntityId","value","constructor","randomUUID","toString","toValue","equals","id","Entity","_id","props","id","createdAt","date","updatedAt","touch","Date","UniqueEntityId","equals","entity","AggregateRoot","Entity","ValueObject","props","WatchedList","currentItems","initial","new","removed","updated","constructor","initialItems","getItems","getNewItems","getRemovedItems","getUpdatedItems","addUpdatedItem","item","push","isCurrentItem","filter","v","compareItems","length","isNewItem","isRemovedItem","removeFromNew","removeFromCurrent","removeFromRemoved","wasAddedInitially","exists","add","remove","update","items","newItems","a","some","b","removedItems","updatedItems","getTakeAndSkip","size","page","take","Number","skip","ErrorResponseCode","import_reflect_metadata","validateControllerMetadata","controller","metadata","Reflect","getMetadata","constructor","Error","name","ExpressAdapter","instance","server","constructor","env","logger","express","use","cors","json","limit","urlencoded","extended","disable","registerRoute","controllerClass","metadata","validateControllerMetadata","method","path","request","response","requestData","body","params","headers","query","output","execute","status","code","data","ErrorResponseCode","NO_CONTENT_BODY","err","error","failure","ENVIRONMENT","url","NO_CONTENT_ERROR","startServer","port","Promise","resolve","listen","info","closeServer","reject","close","import_cors","FastifyAdapter","instance","constructor","env","logger","fastify","bodyLimit","querystringParser","str","qs","parse","loggerInstance","ENVIRONMENT","register","cors","registerRoute","controllerClass","metadata","validateControllerMetadata","method","path","request","reply","requestData","body","params","headers","query","output","execute","status","code","send","data","ErrorResponseCode","NO_CONTENT_BODY","err","error","failure","url","NO_CONTENT_ERROR","startServer","port","listen","NODE_ENV","info","closeServer","close","DiscordNotifier","webhook","constructor","options","Webhook","url","notify","error","context","embed","MessageBuilder","setTitle","addField","message","slice","request","method","JSON","stringify","params","query","headers","body","stack","setFooter","env","setTimestamp","send","NotificationErrorInMemory","errors","notify","error","context","console","push","message","SentryNotifier","constructor","options","Sentry","init","dsn","environment","attachStacktrace","tracesSampleRate","maxBreadcrumbs","debug","notify","error","context","withScope","scope","setLevel","env","setTag","user","setUser","id","username","name","email","request","body","query","params","headers","method","url","requestId","setContext","captureException","NotificationFactory","define","env","definitions","defaultDefinition","test","defineProvider","development","staging","production","provider","NotificationErrorInMemory","DiscordNotifier","SentryNotifier","ZodMapError","mapCommon","error","type","code","path","join","property","pop","propertyType","expected","receivedValue","received","message","mapInvalidUnion","errors","unionErrors","flat","map","err","issues","item","mapInvalidType","mapErrorsFactory","mapErrors","standardizedErrors","Map","forEach","keyError","get","propertyErrors","push","set","location","Array","from","arr","ZodValidator","constructor","zodSchema","validate","requestHttp","errors","data","headersData","error","headersErrors","headers","shape","safeParseAsync","path","push","paramsData","paramsErrors","params","queryData","queryErrors","query","bodyData","bodyErrors","body","length","ValidationError","ZodMapError","mapErrors","zodValidator","schema","request","validator","ZodValidator","validatedRequest","validate","WinstonOtelFastify","logger","consoleLogger","level","constructor","process","env","OTEL_ENABLE","logs","getLogger","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","LOG_LEVEL","transports","NODE_ENV","winston","Console","silent","createLogger","format","combine","timestamp","info","span","opentelemetry","trace","getActiveSpan","spanId","spanContext","traceId","json","bodyIsFastifyRequest","body","method","undefined","bodyIsFastifyReply","statusCode","buildMessage","req","url","res","request","elapsedTime","logMessage","severityNumber","severityText","message","toLowerCase","emit","SeverityNumber","INFO","error","ERROR","debug","DEBUG","fatal","FATAL","warn","WARN","TRACE","child","OpenTelemetry","sdk","constructor","env","NodeSDK","resource","Resource","SEMRESATTRS_SERVICE_NAME","OTEL_SERVICE_NAME","SEMRESATTRS_SERVICE_VERSION","OTEL_SERVICE_VERSION","traceExporter","OTLPTraceExporter","url","OTEL_OTLP_TRACES_EXPORTER_URL","logRecordProcessor","BatchLogRecordProcessor","OTLPLogExporter","OTEL_OTLP_LOGS_EXPORTER_URL","maxQueueSize","maxExportBatchSize","scheduledDelayMillis","exportTimeoutMillis","metricReader","PeriodicExportingMetricReader","exporter","OTLPMetricExporter","OTEL_OTLP_METRICS_EXPORTER_URL","startSdk","start","import_api","import_reflect_metadata","Span","target","propertyKey","descriptor","process","env","OTEL_ENABLE","originalMethod","value","args","tracer","opentelemetry","trace","getTracer","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","className","constructor","name","methodName","String","spanName","startActiveSpan","span","result","apply","Promise","awaitedResult","addEvent","end","error","handleSpanError","errorMessage","Error","message","recordException","setStatus","code","SpanStatusCode","ERROR","import_api","TracerGatewayOpentelemetry","addEvent","name","attributes","process","env","OTEL_ENABLE","span","opentelemetry","trace","getActiveSpan","setAttribute","key","value","require","config","Object","assign","process","argv","baseEnvSchema","z","object","NODE_ENV","enum","default","ENVIRONMENT","PORT","coerce","number","SHOULD_NOTIFY_ERROR","boolean","SENTRY_DSN","string","optional","DISCORD_WEBHOOK_URL","LOG_LEVEL","OTEL_ENABLE","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","OTEL_OTLP_TRACES_EXPORTER_URL","url","OTEL_OTLP_LOGS_EXPORTER_URL","OTEL_OTLP_METRICS_EXPORTER_URL"]}
1
+ {"version":3,"sources":["../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/context-async-hooks/src/AbstractAsyncHooksContextManager.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/context-async-hooks/src/AsyncHooksContextManager.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/context-async-hooks/src/AsyncLocalStorageContextManager.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/context-async-hooks/src/index.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/baggage/constants.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/baggage/utils.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/baggage/propagation/W3CBaggagePropagator.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/anchored-clock.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/attributes.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/globalThis.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/hex-to-binary.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/hex-to-base64.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/RandomIdGenerator.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/performance.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/version.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/node/index.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/platform/index.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/common/types.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/propagation/composite.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/TraceState.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/IdGenerator.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/rpc-metadata.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOffSampler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOnSampler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/sampler/ParentBasedSampler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/trace/sampler/TraceIdRatioBasedSampler.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/merge.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/timeout.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/wrap.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/propagator-b3/node_modules/@opentelemetry/core/src/index.ts","../node_modules/@opentelemetry/propagator-b3/src/common.ts","../node_modules/@opentelemetry/propagator-b3/src/constants.ts","../node_modules/@opentelemetry/propagator-b3/src/B3MultiPropagator.ts","../node_modules/@opentelemetry/propagator-b3/src/B3SinglePropagator.ts","../node_modules/@opentelemetry/propagator-b3/src/types.ts","../node_modules/@opentelemetry/propagator-b3/src/B3Propagator.ts","../node_modules/@opentelemetry/propagator-b3/src/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/baggage/constants.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/baggage/utils.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/baggage/propagation/W3CBaggagePropagator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/anchored-clock.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/attributes.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/environment.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/globalThis.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/hex-to-binary.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/hex-to-base64.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/RandomIdGenerator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/performance.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/version.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/node/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/platform/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/common/types.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/propagation/composite.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/TraceState.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/IdGenerator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/rpc-metadata.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOffSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOnSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/sampler/ParentBasedSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/trace/sampler/TraceIdRatioBasedSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/merge.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/timeout.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/wrap.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/internal/exporter.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/core/src/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/enums.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/Span.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/Sampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOffSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/sampler/AlwaysOnSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/sampler/ParentBasedSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/sampler/TraceIdRatioBasedSampler.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/config.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/utility.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/BatchSpanProcessorBase.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/export/BatchSpanProcessor.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/RandomIdGenerator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/platform/node/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/platform/index.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/Tracer.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/MultiSpanProcessor.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/NoopSpanProcessor.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/BasicTracerProvider.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/ConsoleSpanExporter.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/InMemorySpanExporter.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/ReadableSpan.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/SimpleSpanProcessor.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/export/SpanExporter.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/SpanProcessor.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/TimedEvent.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/types.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/IdGenerator.ts","../node_modules/@opentelemetry/sdk-trace-node/node_modules/@opentelemetry/sdk-trace-base/src/index.ts","../node_modules/semver/internal/constants.js","../node_modules/semver/internal/debug.js","../node_modules/semver/internal/re.js","../node_modules/semver/internal/parse-options.js","../node_modules/semver/internal/identifiers.js","../node_modules/semver/classes/semver.js","../node_modules/semver/functions/parse.js","../node_modules/semver/functions/valid.js","../node_modules/semver/functions/clean.js","../node_modules/semver/functions/inc.js","../node_modules/semver/functions/diff.js","../node_modules/semver/functions/major.js","../node_modules/semver/functions/minor.js","../node_modules/semver/functions/patch.js","../node_modules/semver/functions/prerelease.js","../node_modules/semver/functions/compare.js","../node_modules/semver/functions/rcompare.js","../node_modules/semver/functions/compare-loose.js","../node_modules/semver/functions/compare-build.js","../node_modules/semver/functions/sort.js","../node_modules/semver/functions/rsort.js","../node_modules/semver/functions/gt.js","../node_modules/semver/functions/lt.js","../node_modules/semver/functions/eq.js","../node_modules/semver/functions/neq.js","../node_modules/semver/functions/gte.js","../node_modules/semver/functions/lte.js","../node_modules/semver/functions/cmp.js","../node_modules/semver/functions/coerce.js","../node_modules/semver/internal/lrucache.js","../node_modules/semver/classes/range.js","../node_modules/semver/classes/comparator.js","../node_modules/semver/functions/satisfies.js","../node_modules/semver/ranges/to-comparators.js","../node_modules/semver/ranges/max-satisfying.js","../node_modules/semver/ranges/min-satisfying.js","../node_modules/semver/ranges/min-version.js","../node_modules/semver/ranges/valid.js","../node_modules/semver/ranges/outside.js","../node_modules/semver/ranges/gtr.js","../node_modules/semver/ranges/ltr.js","../node_modules/semver/ranges/intersects.js","../node_modules/semver/ranges/simplify.js","../node_modules/semver/ranges/subset.js","../node_modules/semver/index.js","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/baggage/constants.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/baggage/utils.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/baggage/propagation/W3CBaggagePropagator.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/anchored-clock.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/attributes.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/sampling.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/environment.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/globalThis.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/hex-to-binary.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/hex-to-base64.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/RandomIdGenerator.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/performance.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/version.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/node/index.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/platform/index.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/common/types.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/ExportResult.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/propagation/composite.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/TraceState.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/IdGenerator.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/rpc-metadata.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOffSampler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOnSampler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/sampler/ParentBasedSampler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/trace/sampler/TraceIdRatioBasedSampler.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/merge.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/timeout.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/wrap.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/promise.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/utils/callback.ts","../node_modules/@opentelemetry/propagator-jaeger/node_modules/@opentelemetry/core/src/index.ts","../node_modules/@opentelemetry/propagator-jaeger/src/JaegerPropagator.ts","../node_modules/@opentelemetry/propagator-jaeger/src/index.ts","../node_modules/@opentelemetry/sdk-trace-node/src/NodeTracerProvider.ts","../node_modules/@opentelemetry/sdk-trace-node/src/index.ts","../node_modules/dotenv/package.json","../node_modules/dotenv/lib/main.js","../node_modules/dotenv/lib/env-options.js","../node_modules/dotenv/lib/cli-options.js","../src/index.ts","../src/core/decorators/dependency-container.ts","../src/core/configs/global-error-handler.ts","../src/core/errors/api-common-error.ts","../src/core/errors/application-error.ts","../src/core/errors/conflict-error.ts","../src/core/errors/domain-error.ts","../src/core/errors/infra-error.ts","../src/core/errors/validation-error.ts","../src/core/http/base-controller.ts","../src/core/decorators/controller-http-decorator.ts","../src/core/entities/unique-object-id.ts","../src/core/entities/entity-object.ts","../src/core/entities/aggregate-object-root.ts","../src/core/entities/unique-entity-id.ts","../src/core/entities/entity.ts","../src/core/entities/aggregate-root.ts","../src/core/entities/value-object.ts","../src/core/entities/watched-list.ts","../src/core/http/get-take-and-skip.ts","../src/infra/adapters/http/express-adapter.ts","../src/infra/adapters/http/response-error-code.ts","../src/infra/adapters/http/validate-controller-metadata.ts","../src/infra/adapters/http/fastify-adapter.ts","../src/infra/adapters/notifications/discord.ts","../src/infra/adapters/notifications/in-memory.ts","../src/infra/adapters/notifications/sentry.ts","../src/infra/adapters/notifications/notification-factory.ts","../src/infra/adapters/validators/zod/zod-map-error.ts","../src/infra/adapters/validators/zod/index.ts","../src/infra/adapters/validators/zod/zod-validator.ts","../src/infra/adapters/logger/winston-otel-fastify.ts","../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../node_modules/@opentelemetry/core/src/propagation/composite.ts","../node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../node_modules/@opentelemetry/core/src/internal/validators.ts","../node_modules/@opentelemetry/core/src/trace/TraceState.ts","../src/infra/adapters/observability/otel/opentelemetry.ts","../src/infra/adapters/observability/otel/span-decorator.ts","../src/infra/adapters/observability/otel/tracer-gateway-opentelemetry.ts","../src/infra/env/index.ts","../node_modules/dotenv/config.js"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextManager, Context } from '@opentelemetry/api';\nimport { EventEmitter } from 'events';\n\ntype Func<T> = (...args: unknown[]) => T;\n\n/**\n * Store a map for each event of all original listeners and their \"patched\"\n * version. So when a listener is removed by the user, the corresponding\n * patched function will be also removed.\n */\ninterface PatchMap {\n [name: string]: WeakMap<Func<void>, Func<void>>;\n}\n\nconst ADD_LISTENER_METHODS = [\n 'addListener' as const,\n 'on' as const,\n 'once' as const,\n 'prependListener' as const,\n 'prependOnceListener' as const,\n];\n\nexport abstract class AbstractAsyncHooksContextManager\n implements ContextManager\n{\n abstract active(): Context;\n\n abstract with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F>;\n\n abstract enable(): this;\n\n abstract disable(): this;\n\n /**\n * Binds a the certain context or the active one to the target function and then returns the target\n * @param context A context (span) to be bind to target\n * @param target a function or event emitter. When target or one of its callbacks is called,\n * the provided context will be used as the active context for the duration of the call.\n */\n bind<T>(context: Context, target: T): T {\n if (target instanceof EventEmitter) {\n return this._bindEventEmitter(context, target);\n }\n\n if (typeof target === 'function') {\n return this._bindFunction(context, target);\n }\n return target;\n }\n\n private _bindFunction<T extends Function>(context: Context, target: T): T {\n const manager = this;\n const contextWrapper = function (this: never, ...args: unknown[]) {\n return manager.with(context, () => target.apply(this, args));\n };\n Object.defineProperty(contextWrapper, 'length', {\n enumerable: false,\n configurable: true,\n writable: false,\n value: target.length,\n });\n /**\n * It isn't possible to tell Typescript that contextWrapper is the same as T\n * so we forced to cast as any here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return contextWrapper as any;\n }\n\n /**\n * By default, EventEmitter call their callback with their context, which we do\n * not want, instead we will bind a specific context to all callbacks that\n * go through it.\n * @param context the context we want to bind\n * @param ee EventEmitter an instance of EventEmitter to patch\n */\n private _bindEventEmitter<T extends EventEmitter>(\n context: Context,\n ee: T\n ): T {\n const map = this._getPatchMap(ee);\n if (map !== undefined) return ee;\n this._createPatchMap(ee);\n\n // patch methods that add a listener to propagate context\n ADD_LISTENER_METHODS.forEach(methodName => {\n if (ee[methodName] === undefined) return;\n ee[methodName] = this._patchAddListener(ee, ee[methodName], context);\n });\n // patch methods that remove a listener\n if (typeof ee.removeListener === 'function') {\n ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);\n }\n if (typeof ee.off === 'function') {\n ee.off = this._patchRemoveListener(ee, ee.off);\n }\n // patch method that remove all listeners\n if (typeof ee.removeAllListeners === 'function') {\n ee.removeAllListeners = this._patchRemoveAllListeners(\n ee,\n ee.removeAllListeners\n );\n }\n return ee;\n }\n\n /**\n * Patch methods that remove a given listener so that we match the \"patched\"\n * version of that listener (the one that propagate context).\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveListener(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n const events = contextManager._getPatchMap(ee)?.[event];\n if (events === undefined) {\n return original.call(this, event, listener);\n }\n const patchedListener = events.get(listener);\n return original.call(this, event, patchedListener || listener);\n };\n }\n\n /**\n * Patch methods that remove all listeners so we remove our\n * internal references for a given event.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n */\n private _patchRemoveAllListeners(ee: EventEmitter, original: Function) {\n const contextManager = this;\n return function (this: never, event: string) {\n const map = contextManager._getPatchMap(ee);\n if (map !== undefined) {\n if (arguments.length === 0) {\n contextManager._createPatchMap(ee);\n } else if (map[event] !== undefined) {\n delete map[event];\n }\n }\n return original.apply(this, arguments);\n };\n }\n\n /**\n * Patch methods on an event emitter instance that can add listeners so we\n * can force them to propagate a given context.\n * @param ee EventEmitter instance\n * @param original reference to the patched method\n * @param [context] context to propagate when calling listeners\n */\n private _patchAddListener(\n ee: EventEmitter,\n original: Function,\n context: Context\n ) {\n const contextManager = this;\n return function (this: never, event: string, listener: Func<void>) {\n /**\n * This check is required to prevent double-wrapping the listener.\n * The implementation for ee.once wraps the listener and calls ee.on.\n * Without this check, we would wrap that wrapped listener.\n * This causes an issue because ee.removeListener depends on the onceWrapper\n * to properly remove the listener. If we wrap their wrapper, we break\n * that detection.\n */\n if (contextManager._wrapped) {\n return original.call(this, event, listener);\n }\n let map = contextManager._getPatchMap(ee);\n if (map === undefined) {\n map = contextManager._createPatchMap(ee);\n }\n let listeners = map[event];\n if (listeners === undefined) {\n listeners = new WeakMap();\n map[event] = listeners;\n }\n const patchedListener = contextManager.bind(context, listener);\n // store a weak reference of the user listener to ours\n listeners.set(listener, patchedListener);\n\n /**\n * See comment at the start of this function for the explanation of this property.\n */\n contextManager._wrapped = true;\n try {\n return original.call(this, event, patchedListener);\n } finally {\n contextManager._wrapped = false;\n }\n };\n }\n\n private _createPatchMap(ee: EventEmitter): PatchMap {\n const map = Object.create(null);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (ee as any)[this._kOtListeners] = map;\n return map;\n }\n private _getPatchMap(ee: EventEmitter): PatchMap | undefined {\n return (ee as never)[this._kOtListeners];\n }\n\n private readonly _kOtListeners = Symbol('OtListeners');\n private _wrapped = false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, ROOT_CONTEXT } from '@opentelemetry/api';\nimport * as asyncHooks from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\nexport class AsyncHooksContextManager extends AbstractAsyncHooksContextManager {\n private _asyncHook: asyncHooks.AsyncHook;\n private _contexts: Map<number, Context> = new Map();\n private _stack: Array<Context | undefined> = [];\n\n constructor() {\n super();\n this._asyncHook = asyncHooks.createHook({\n init: this._init.bind(this),\n before: this._before.bind(this),\n after: this._after.bind(this),\n destroy: this._destroy.bind(this),\n promiseResolve: this._destroy.bind(this),\n });\n }\n\n active(): Context {\n return this._stack[this._stack.length - 1] ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n this._enterContext(context);\n try {\n return fn.call(thisArg!, ...args);\n } finally {\n this._exitContext();\n }\n }\n\n enable(): this {\n this._asyncHook.enable();\n return this;\n }\n\n disable(): this {\n this._asyncHook.disable();\n this._contexts.clear();\n this._stack = [];\n return this;\n }\n\n /**\n * Init hook will be called when userland create a async context, setting the\n * context as the current one if it exist.\n * @param uid id of the async context\n * @param type the resource type\n */\n private _init(uid: number, type: string) {\n // ignore TIMERWRAP as they combine timers with same timeout which can lead to\n // false context propagation. TIMERWRAP has been removed in node 11\n // every timer has it's own `Timeout` resource anyway which is used to propagate\n // context.\n if (type === 'TIMERWRAP') return;\n\n const context = this._stack[this._stack.length - 1];\n if (context !== undefined) {\n this._contexts.set(uid, context);\n }\n }\n\n /**\n * Destroy hook will be called when a given context is no longer used so we can\n * remove its attached context.\n * @param uid uid of the async context\n */\n private _destroy(uid: number) {\n this._contexts.delete(uid);\n }\n\n /**\n * Before hook is called just before executing a async context.\n * @param uid uid of the async context\n */\n private _before(uid: number) {\n const context = this._contexts.get(uid);\n if (context !== undefined) {\n this._enterContext(context);\n }\n }\n\n /**\n * After hook is called just after completing the execution of a async context.\n */\n private _after() {\n this._exitContext();\n }\n\n /**\n * Set the given context as active\n */\n private _enterContext(context: Context) {\n this._stack.push(context);\n }\n\n /**\n * Remove the context at the root of the stack\n */\n private _exitContext() {\n this._stack.pop();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, ROOT_CONTEXT } from '@opentelemetry/api';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager';\n\nexport class AsyncLocalStorageContextManager extends AbstractAsyncHooksContextManager {\n private _asyncLocalStorage: AsyncLocalStorage<Context>;\n\n constructor() {\n super();\n this._asyncLocalStorage = new AsyncLocalStorage();\n }\n\n active(): Context {\n return this._asyncLocalStorage.getStore() ?? ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n const cb = thisArg == null ? fn : fn.bind(thisArg);\n return this._asyncLocalStorage.run(context, cb as never, ...args);\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n this._asyncLocalStorage.disable();\n return this;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './AsyncHooksContextManager';\nexport * from './AsyncLocalStorageContextManager';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0) return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart) return;\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n const key = decodeURIComponent(\n keyPairPart.substring(0, separatorIndex).trim()\n );\n const value = decodeURIComponent(\n keyPairPart.substring(separatorIndex + 1).trim()\n );\n let metadata;\n if (valueProps.length > 0) {\n metadata = baggageEntryMetadataFromString(\n valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)\n );\n }\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n if (typeof value !== 'string' || value.length === 0) return {};\n return value\n .split(BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce<Record<string, string>>((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair!.key] = keyPair!.value;\n return headers;\n }, {});\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaggageEntry,\n Context,\n propagation,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport { getKeyPairs, parsePairKeyValue, serializeKeyPairs } from '../utils';\n\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nexport class W3CBaggagePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const baggage = propagation.getBaggage(context);\n if (!baggage || isTracingSuppressed(context)) return;\n const keyPairs = getKeyPairs(baggage)\n .filter((pair: string) => {\n return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = serializeKeyPairs(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, BAGGAGE_HEADER, headerValue);\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const headerValue = getter.get(carrier, BAGGAGE_HEADER);\n const baggageString = Array.isArray(headerValue)\n ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString) return context;\n const baggage: Record<string, BaggageEntry> = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n if (keyPair) {\n const baggageEntry: BaggageEntry = { value: keyPair.value };\n if (keyPair.metadata) {\n baggageEntry.metadata = keyPair.metadata;\n }\n baggage[keyPair.key] = baggageEntry;\n }\n });\n if (Object.entries(baggage).length === 0) {\n return context;\n }\n return propagation.setBaggage(context, propagation.createBaggage(baggage));\n }\n\n fields(): string[] {\n return [BAGGAGE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Clock {\n /**\n * Return the current time in milliseconds from some epoch such as the Unix epoch or process start\n */\n now(): number;\n}\n\n/**\n * A utility for returning wall times anchored to a given point in time. Wall time measurements will\n * not be taken from the system, but instead are computed by adding a monotonic clock time\n * to the anchor point.\n *\n * This is needed because the system time can change and result in unexpected situations like\n * spans ending before they are started. Creating an anchored clock for each local root span\n * ensures that span timings and durations are accurate while preventing span times from drifting\n * too far from the system clock.\n *\n * Only creating an anchored clock once per local trace ensures span times are correct relative\n * to each other. For example, a child span will never have a start time before its parent even\n * if the system clock is corrected during the local trace.\n *\n * Heavily inspired by the OTel Java anchored clock\n * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java\n */\nexport class AnchoredClock implements Clock {\n private _monotonicClock: Clock;\n private _epochMillis: number;\n private _performanceMillis: number;\n\n /**\n * Create a new AnchoredClock anchored to the current time returned by systemClock.\n *\n * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date\n * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance\n */\n public constructor(systemClock: Clock, monotonicClock: Clock) {\n this._monotonicClock = monotonicClock;\n this._epochMillis = systemClock.now();\n this._performanceMillis = monotonicClock.now();\n }\n\n /**\n * Returns the current time by adding the number of milliseconds since the\n * AnchoredClock was created to the creation epoch time\n */\n public now(): number {\n const delta = this._monotonicClock.now() - this._performanceMillis;\n return this._epochMillis + delta;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, SpanAttributeValue, SpanAttributes } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): SpanAttributes {\n const out: SpanAttributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const [key, val] of Object.entries(attributes)) {\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key.length > 0;\n}\n\nexport function isAttributeValue(val: unknown): val is SpanAttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValue(val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n\n if (!type) {\n if (isValidPrimitiveAttributeValue(element)) {\n type = typeof element;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n if (typeof element === type) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValue(val: unknown): boolean {\n switch (typeof val) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nfunction intValue(charCode: number): number {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n\n // A-F\n return charCode - 55;\n}\n\nexport function hexToBinary(hexStr: string): Uint8Array {\n const buf = new Uint8Array(hexStr.length / 2);\n let offset = 0;\n\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf[offset++] = (hi << 4) | lo;\n }\n\n return buf;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { hexToBinary } from '../../common/hex-to-binary';\n\nexport function hexToBase64(hexStr: string): string {\n return Buffer.from(hexToBinary(hexStr)).toString('base64');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../trace/IdGenerator';\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n */\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { performance } from 'perf_hooks';\n\nexport const otperformance = performance;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.24.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../../version';\nimport {\n TelemetrySdkLanguageValues,\n SemanticResourceAttributes,\n} from '@opentelemetry/semantic-conventions';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [SemanticResourceAttributes.TELEMETRY_SDK_NAME]: 'opentelemetry',\n [SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'node',\n [SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]:\n TelemetrySdkLanguageValues.NODEJS,\n [SemanticResourceAttributes.TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { getEnvWithoutDefaults, getEnv } from './environment';\nexport * from './globalThis';\nexport * from './hex-to-base64';\nexport * from './RandomIdGenerator';\nexport * from './performance';\nexport * from './sdk-info';\nexport * from './timer-util';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport * from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\nimport { TimeOriginLegacy } from './types';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\nexport function getTimeOrigin(): number {\n let timeOrigin = performance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf: TimeOriginLegacy = performance as unknown as TimeOriginLegacy;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\n\n/**\n * This interface defines a fallback to read a timeOrigin when it is not available on performance.timeOrigin,\n * this happens for example on Safari Mac\n * then the timeOrigin is taken from fetchStart - which is the closest to timeOrigin\n */\nexport interface TimeOriginLegacy {\n timing: {\n fetchStart: number;\n };\n}\n\n/**\n * This interface defines the params that are be added to the wrapped function\n * using the \"shimmer.wrap\"\n */\nexport interface ShimWrapped extends Function {\n __wrapped: boolean;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __unwrap: Function;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __original: Function;\n}\n\n/**\n * An instrumentation library consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n * @deprecated Use {@link InstrumentationScope} instead.\n */\nexport interface InstrumentationLibrary {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/**\n * An instrumentation scope consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n */\nexport interface InstrumentationScope {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/** Defines an error handler function */\nexport type ErrorHandler = (ex: Exception) => void;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\n )\n );\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * IdGenerator provides an interface for generating Trace Id and Span Id.\n */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey, Span } from '@opentelemetry/api';\n\nconst RPC_METADATA_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key RPC_METADATA'\n);\n\nexport enum RPCType {\n HTTP = 'http',\n}\n\ntype HTTPMetadata = {\n type: RPCType.HTTP;\n route?: string;\n span: Span;\n};\n\n/**\n * Allows for future rpc metadata to be used with this mechanism\n */\nexport type RPCMetadata = HTTPMetadata;\n\nexport function setRPCMetadata(context: Context, meta: RPCMetadata): Context {\n return context.setValue(RPC_METADATA_KEY, meta);\n}\n\nexport function deleteRPCMetadata(context: Context): Context {\n return context.deleteValue(RPC_METADATA_KEY);\n}\n\nexport function getRPCMetadata(context: Context): RPCMetadata | undefined {\n return context.getValue(RPC_METADATA_KEY) as RPCMetadata | undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples no traces.\n */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples all traces.\n */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n Sampler,\n SamplingResult,\n SpanAttributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '../../common/global-error-handler';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Sampler,\n SamplingDecision,\n SamplingResult,\n isValidTraceId,\n} from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples a given fraction of traces based of trace id deterministically.\n */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ShimWrapped } from '../common/types';\n\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nexport function isWrapped(func: unknown): func is ShimWrapped {\n return (\n typeof func === 'function' &&\n typeof (func as ShimWrapped).__original === 'function' &&\n typeof (func as ShimWrapped).__unwrap === 'function' &&\n (func as ShimWrapped).__wrapped === true\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './baggage/propagation/W3CBaggagePropagator';\nexport * from './common/anchored-clock';\nexport * from './common/attributes';\nexport * from './common/global-error-handler';\nexport * from './common/logging-error-handler';\nexport * from './common/time';\nexport * from './common/types';\nexport * from './common/hex-to-binary';\nexport * from './ExportResult';\nexport * as baggageUtils from './baggage/utils';\nexport * from './platform';\nexport * from './propagation/composite';\nexport * from './trace/W3CTraceContextPropagator';\nexport * from './trace/IdGenerator';\nexport * from './trace/rpc-metadata';\nexport * from './trace/sampler/AlwaysOffSampler';\nexport * from './trace/sampler/AlwaysOnSampler';\nexport * from './trace/sampler/ParentBasedSampler';\nexport * from './trace/sampler/TraceIdRatioBasedSampler';\nexport * from './trace/suppress-tracing';\nexport * from './trace/TraceState';\nexport * from './utils/environment';\nexport * from './utils/merge';\nexport * from './utils/sampling';\nexport * from './utils/timeout';\nexport * from './utils/url';\nexport * from './utils/wrap';\nexport * from './utils/callback';\nexport * from './version';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createContextKey } from '@opentelemetry/api';\n\n/** shared context for storing an extracted b3 debug flag */\nexport const B3_DEBUG_FLAG_KEY = createContextKey(\n 'OpenTelemetry Context Key B3 Debug Flag'\n);\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** B3 single-header key */\nexport const B3_CONTEXT_HEADER = 'b3';\n\n/* b3 multi-header keys */\nexport const X_B3_TRACE_ID = 'x-b3-traceid';\nexport const X_B3_SPAN_ID = 'x-b3-spanid';\nexport const X_B3_SAMPLED = 'x-b3-sampled';\nexport const X_B3_PARENT_SPAN_ID = 'x-b3-parentspanid';\nexport const X_B3_FLAGS = 'x-b3-flags';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n isValidSpanId,\n isValidTraceId,\n trace,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from '@opentelemetry/core';\nimport { B3_DEBUG_FLAG_KEY } from './common';\nimport {\n X_B3_FLAGS,\n X_B3_PARENT_SPAN_ID,\n X_B3_SAMPLED,\n X_B3_SPAN_ID,\n X_B3_TRACE_ID,\n} from './constants';\n\nconst VALID_SAMPLED_VALUES = new Set([true, 'true', 'True', '1', 1]);\nconst VALID_UNSAMPLED_VALUES = new Set([false, 'false', 'False', '0', 0]);\n\nfunction isValidSampledValue(sampled: TraceFlags | undefined): boolean {\n return sampled === TraceFlags.SAMPLED || sampled === TraceFlags.NONE;\n}\n\nfunction parseHeader(header: unknown) {\n return Array.isArray(header) ? header[0] : header;\n}\n\nfunction getHeaderValue(carrier: unknown, getter: TextMapGetter, key: string) {\n const header = getter.get(carrier, key);\n return parseHeader(header);\n}\n\nfunction getTraceId(carrier: unknown, getter: TextMapGetter): string {\n const traceId = getHeaderValue(carrier, getter, X_B3_TRACE_ID);\n if (typeof traceId === 'string') {\n return traceId.padStart(32, '0');\n }\n return '';\n}\n\nfunction getSpanId(carrier: unknown, getter: TextMapGetter): string {\n const spanId = getHeaderValue(carrier, getter, X_B3_SPAN_ID);\n if (typeof spanId === 'string') {\n return spanId;\n }\n return '';\n}\n\nfunction getDebug(carrier: unknown, getter: TextMapGetter): string | undefined {\n const debug = getHeaderValue(carrier, getter, X_B3_FLAGS);\n return debug === '1' ? '1' : undefined;\n}\n\nfunction getTraceFlags(\n carrier: unknown,\n getter: TextMapGetter\n): TraceFlags | undefined {\n const traceFlags = getHeaderValue(carrier, getter, X_B3_SAMPLED);\n const debug = getDebug(carrier, getter);\n if (debug === '1' || VALID_SAMPLED_VALUES.has(traceFlags)) {\n return TraceFlags.SAMPLED;\n }\n if (traceFlags === undefined || VALID_UNSAMPLED_VALUES.has(traceFlags)) {\n return TraceFlags.NONE;\n }\n // This indicates to isValidSampledValue that this is not valid\n return;\n}\n\n/**\n * Propagator for the B3 multiple-header HTTP format.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nexport class B3MultiPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n !isSpanContextValid(spanContext) ||\n isTracingSuppressed(context)\n )\n return;\n\n const debug = context.getValue(B3_DEBUG_FLAG_KEY);\n setter.set(carrier, X_B3_TRACE_ID, spanContext.traceId);\n setter.set(carrier, X_B3_SPAN_ID, spanContext.spanId);\n // According to the B3 spec, if the debug flag is set,\n // the sampled flag shouldn't be propagated as well.\n if (debug === '1') {\n setter.set(carrier, X_B3_FLAGS, debug);\n } else if (spanContext.traceFlags !== undefined) {\n // We set the header only if there is an existing sampling decision.\n // Otherwise we will omit it => Absent.\n setter.set(\n carrier,\n X_B3_SAMPLED,\n (TraceFlags.SAMPLED & spanContext.traceFlags) === TraceFlags.SAMPLED\n ? '1'\n : '0'\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceId = getTraceId(carrier, getter);\n const spanId = getSpanId(carrier, getter);\n const traceFlags = getTraceFlags(carrier, getter) as TraceFlags;\n const debug = getDebug(carrier, getter);\n\n if (\n isValidTraceId(traceId) &&\n isValidSpanId(spanId) &&\n isValidSampledValue(traceFlags)\n ) {\n context = context.setValue(B3_DEBUG_FLAG_KEY, debug);\n return trace.setSpanContext(context, {\n traceId,\n spanId,\n isRemote: true,\n traceFlags,\n });\n }\n return context;\n }\n\n fields(): string[] {\n return [\n X_B3_TRACE_ID,\n X_B3_SPAN_ID,\n X_B3_FLAGS,\n X_B3_SAMPLED,\n X_B3_PARENT_SPAN_ID,\n ];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n isValidSpanId,\n isValidTraceId,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from '@opentelemetry/core';\nimport { B3_DEBUG_FLAG_KEY } from './common';\nimport { B3_CONTEXT_HEADER } from './constants';\n\nconst B3_CONTEXT_REGEX =\n /((?:[0-9a-f]{16}){1,2})-([0-9a-f]{16})(?:-([01d](?![0-9a-f])))?(?:-([0-9a-f]{16}))?/;\nconst PADDING = '0'.repeat(16);\nconst SAMPLED_VALUES = new Set(['d', '1']);\nconst DEBUG_STATE = 'd';\n\nfunction convertToTraceId128(traceId: string): string {\n return traceId.length === 32 ? traceId : `${PADDING}${traceId}`;\n}\n\nfunction convertToTraceFlags(samplingState: string | undefined): TraceFlags {\n if (samplingState && SAMPLED_VALUES.has(samplingState)) {\n return TraceFlags.SAMPLED;\n }\n return TraceFlags.NONE;\n}\n\n/**\n * Propagator for the B3 single-header HTTP format.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nexport class B3SinglePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n !isSpanContextValid(spanContext) ||\n isTracingSuppressed(context)\n )\n return;\n\n const samplingState =\n context.getValue(B3_DEBUG_FLAG_KEY) || spanContext.traceFlags & 0x1;\n const value = `${spanContext.traceId}-${spanContext.spanId}-${samplingState}`;\n setter.set(carrier, B3_CONTEXT_HEADER, value);\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const header = getter.get(carrier, B3_CONTEXT_HEADER);\n const b3Context = Array.isArray(header) ? header[0] : header;\n if (typeof b3Context !== 'string') return context;\n\n const match = b3Context.match(B3_CONTEXT_REGEX);\n if (!match) return context;\n\n const [, extractedTraceId, spanId, samplingState] = match;\n const traceId = convertToTraceId128(extractedTraceId);\n\n if (!isValidTraceId(traceId) || !isValidSpanId(spanId)) return context;\n\n const traceFlags = convertToTraceFlags(samplingState);\n\n if (samplingState === DEBUG_STATE) {\n context = context.setValue(B3_DEBUG_FLAG_KEY, samplingState);\n }\n\n return trace.setSpanContext(context, {\n traceId,\n spanId,\n isRemote: true,\n traceFlags,\n });\n }\n\n fields(): string[] {\n return [B3_CONTEXT_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Enumeration of B3 inject encodings */\nexport enum B3InjectEncoding {\n SINGLE_HEADER,\n MULTI_HEADER,\n}\n\n/** Configuration for the B3Propagator */\nexport interface B3PropagatorConfig {\n injectEncoding?: B3InjectEncoding;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from '@opentelemetry/core';\nimport { B3MultiPropagator } from './B3MultiPropagator';\nimport { B3SinglePropagator } from './B3SinglePropagator';\nimport { B3_CONTEXT_HEADER } from './constants';\nimport { B3InjectEncoding, B3PropagatorConfig } from './types';\n\n/**\n * Propagator that extracts B3 context in both single and multi-header variants,\n * with configurable injection format defaulting to B3 single-header. Due to\n * the asymmetry in injection and extraction formats this is not suitable to\n * be implemented as a composite propagator.\n * Based on: https://github.com/openzipkin/b3-propagation\n */\nexport class B3Propagator implements TextMapPropagator {\n private readonly _b3MultiPropagator: B3MultiPropagator =\n new B3MultiPropagator();\n private readonly _b3SinglePropagator: B3SinglePropagator =\n new B3SinglePropagator();\n private readonly _inject: (\n context: Context,\n carrier: unknown,\n setter: TextMapSetter\n ) => void;\n public readonly _fields: string[];\n\n constructor(config: B3PropagatorConfig = {}) {\n if (config.injectEncoding === B3InjectEncoding.MULTI_HEADER) {\n this._inject = this._b3MultiPropagator.inject;\n this._fields = this._b3MultiPropagator.fields();\n } else {\n this._inject = this._b3SinglePropagator.inject;\n this._fields = this._b3SinglePropagator.fields();\n }\n }\n\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n if (isTracingSuppressed(context)) {\n return;\n }\n this._inject(context, carrier, setter);\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const header = getter.get(carrier, B3_CONTEXT_HEADER);\n const b3Context = Array.isArray(header) ? header[0] : header;\n\n if (b3Context) {\n return this._b3SinglePropagator.extract(context, carrier, getter);\n } else {\n return this._b3MultiPropagator.extract(context, carrier, getter);\n }\n }\n\n fields(): string[] {\n return this._fields;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './B3Propagator';\nexport * from './constants';\nexport * from './types';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0) return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart) return;\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n const key = decodeURIComponent(\n keyPairPart.substring(0, separatorIndex).trim()\n );\n const value = decodeURIComponent(\n keyPairPart.substring(separatorIndex + 1).trim()\n );\n let metadata;\n if (valueProps.length > 0) {\n metadata = baggageEntryMetadataFromString(\n valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)\n );\n }\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n if (typeof value !== 'string' || value.length === 0) return {};\n return value\n .split(BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce<Record<string, string>>((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair!.key] = keyPair!.value;\n return headers;\n }, {});\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaggageEntry,\n Context,\n propagation,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport { getKeyPairs, parsePairKeyValue, serializeKeyPairs } from '../utils';\n\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nexport class W3CBaggagePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const baggage = propagation.getBaggage(context);\n if (!baggage || isTracingSuppressed(context)) return;\n const keyPairs = getKeyPairs(baggage)\n .filter((pair: string) => {\n return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = serializeKeyPairs(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, BAGGAGE_HEADER, headerValue);\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const headerValue = getter.get(carrier, BAGGAGE_HEADER);\n const baggageString = Array.isArray(headerValue)\n ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString) return context;\n const baggage: Record<string, BaggageEntry> = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n if (keyPair) {\n const baggageEntry: BaggageEntry = { value: keyPair.value };\n if (keyPair.metadata) {\n baggageEntry.metadata = keyPair.metadata;\n }\n baggage[keyPair.key] = baggageEntry;\n }\n });\n if (Object.entries(baggage).length === 0) {\n return context;\n }\n return propagation.setBaggage(context, propagation.createBaggage(baggage));\n }\n\n fields(): string[] {\n return [BAGGAGE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Clock {\n /**\n * Return the current time in milliseconds from some epoch such as the Unix epoch or process start\n */\n now(): number;\n}\n\n/**\n * A utility for returning wall times anchored to a given point in time. Wall time measurements will\n * not be taken from the system, but instead are computed by adding a monotonic clock time\n * to the anchor point.\n *\n * This is needed because the system time can change and result in unexpected situations like\n * spans ending before they are started. Creating an anchored clock for each local root span\n * ensures that span timings and durations are accurate while preventing span times from drifting\n * too far from the system clock.\n *\n * Only creating an anchored clock once per local trace ensures span times are correct relative\n * to each other. For example, a child span will never have a start time before its parent even\n * if the system clock is corrected during the local trace.\n *\n * Heavily inspired by the OTel Java anchored clock\n * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java\n */\nexport class AnchoredClock implements Clock {\n private _monotonicClock: Clock;\n private _epochMillis: number;\n private _performanceMillis: number;\n\n /**\n * Create a new AnchoredClock anchored to the current time returned by systemClock.\n *\n * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date\n * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance\n */\n public constructor(systemClock: Clock, monotonicClock: Clock) {\n this._monotonicClock = monotonicClock;\n this._epochMillis = systemClock.now();\n this._performanceMillis = monotonicClock.now();\n }\n\n /**\n * Returns the current time by adding the number of milliseconds since the\n * AnchoredClock was created to the creation epoch time\n */\n public now(): number {\n const delta = this._monotonicClock.now() - this._performanceMillis;\n return this._epochMillis + delta;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, SpanAttributeValue, SpanAttributes } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): SpanAttributes {\n const out: SpanAttributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const [key, val] of Object.entries(attributes)) {\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key.length > 0;\n}\n\nexport function isAttributeValue(val: unknown): val is SpanAttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValue(val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n\n if (!type) {\n if (isValidPrimitiveAttributeValue(element)) {\n type = typeof element;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n if (typeof element === type) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValue(val: unknown): boolean {\n switch (typeof val) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DEFAULT_ENVIRONMENT,\n ENVIRONMENT,\n RAW_ENVIRONMENT,\n parseEnvironment,\n} from '../../utils/environment';\n\n/**\n * Gets the environment variables\n */\nexport function getEnv(): Required<ENVIRONMENT> {\n const processEnv = parseEnvironment(process.env as RAW_ENVIRONMENT);\n return Object.assign({}, DEFAULT_ENVIRONMENT, processEnv);\n}\n\nexport function getEnvWithoutDefaults(): ENVIRONMENT {\n return parseEnvironment(process.env as RAW_ENVIRONMENT);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nfunction intValue(charCode: number): number {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n\n // A-F\n return charCode - 55;\n}\n\nexport function hexToBinary(hexStr: string): Uint8Array {\n const buf = new Uint8Array(hexStr.length / 2);\n let offset = 0;\n\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf[offset++] = (hi << 4) | lo;\n }\n\n return buf;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { hexToBinary } from '../../common/hex-to-binary';\n\nexport function hexToBase64(hexStr: string): string {\n return Buffer.from(hexToBinary(hexStr)).toString('base64');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../trace/IdGenerator';\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n */\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { performance } from 'perf_hooks';\n\nexport const otperformance = performance;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.24.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../../version';\nimport {\n TelemetrySdkLanguageValues,\n SemanticResourceAttributes,\n} from '@opentelemetry/semantic-conventions';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [SemanticResourceAttributes.TELEMETRY_SDK_NAME]: 'opentelemetry',\n [SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'node',\n [SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]:\n TelemetrySdkLanguageValues.NODEJS,\n [SemanticResourceAttributes.TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { getEnvWithoutDefaults, getEnv } from './environment';\nexport * from './globalThis';\nexport * from './hex-to-base64';\nexport * from './RandomIdGenerator';\nexport * from './performance';\nexport * from './sdk-info';\nexport * from './timer-util';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport * from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\nimport { TimeOriginLegacy } from './types';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\nexport function getTimeOrigin(): number {\n let timeOrigin = performance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf: TimeOriginLegacy = performance as unknown as TimeOriginLegacy;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\n\n/**\n * This interface defines a fallback to read a timeOrigin when it is not available on performance.timeOrigin,\n * this happens for example on Safari Mac\n * then the timeOrigin is taken from fetchStart - which is the closest to timeOrigin\n */\nexport interface TimeOriginLegacy {\n timing: {\n fetchStart: number;\n };\n}\n\n/**\n * This interface defines the params that are be added to the wrapped function\n * using the \"shimmer.wrap\"\n */\nexport interface ShimWrapped extends Function {\n __wrapped: boolean;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __unwrap: Function;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __original: Function;\n}\n\n/**\n * An instrumentation library consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n * @deprecated Use {@link InstrumentationScope} instead.\n */\nexport interface InstrumentationLibrary {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/**\n * An instrumentation scope consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n */\nexport interface InstrumentationScope {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/** Defines an error handler function */\nexport type ErrorHandler = (ex: Exception) => void;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\n )\n );\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * IdGenerator provides an interface for generating Trace Id and Span Id.\n */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey, Span } from '@opentelemetry/api';\n\nconst RPC_METADATA_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key RPC_METADATA'\n);\n\nexport enum RPCType {\n HTTP = 'http',\n}\n\ntype HTTPMetadata = {\n type: RPCType.HTTP;\n route?: string;\n span: Span;\n};\n\n/**\n * Allows for future rpc metadata to be used with this mechanism\n */\nexport type RPCMetadata = HTTPMetadata;\n\nexport function setRPCMetadata(context: Context, meta: RPCMetadata): Context {\n return context.setValue(RPC_METADATA_KEY, meta);\n}\n\nexport function deleteRPCMetadata(context: Context): Context {\n return context.deleteValue(RPC_METADATA_KEY);\n}\n\nexport function getRPCMetadata(context: Context): RPCMetadata | undefined {\n return context.getValue(RPC_METADATA_KEY) as RPCMetadata | undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples no traces.\n */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples all traces.\n */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n Sampler,\n SamplingResult,\n SpanAttributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '../../common/global-error-handler';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Sampler,\n SamplingDecision,\n SamplingResult,\n isValidTraceId,\n} from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples a given fraction of traces based of trace id deterministically.\n */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * based on lodash in order to support esm builds without esModuleInterop.\n * lodash is using MIT License.\n **/\n\nconst objectTag = '[object Object]';\nconst nullTag = '[object Null]';\nconst undefinedTag = '[object Undefined]';\nconst funcProto = Function.prototype;\nconst funcToString = funcProto.toString;\nconst objectCtorString = funcToString.call(Object);\nconst getPrototype = overArg(Object.getPrototypeOf, Object);\nconst objectProto = Object.prototype;\nconst hasOwnProperty = objectProto.hasOwnProperty;\nconst symToStringTag = Symbol ? Symbol.toStringTag : undefined;\nconst nativeObjectToString = objectProto.toString;\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func: Function, transform: any): any {\n return function (arg: any) {\n return func(transform(arg));\n };\n}\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nexport function isPlainObject(value: any) {\n if (!isObjectLike(value) || baseGetTag(value) !== objectTag) {\n return false;\n }\n const proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return (\n typeof Ctor == 'function' &&\n Ctor instanceof Ctor &&\n funcToString.call(Ctor) === objectCtorString\n );\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value: any) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value: any) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return symToStringTag && symToStringTag in Object(value)\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value: any) {\n const isOwn = hasOwnProperty.call(value, symToStringTag as any),\n tag = value[symToStringTag as any];\n let unmasked = false;\n\n try {\n value[symToStringTag as any] = undefined;\n unmasked = true;\n } catch (e) {\n // silence\n }\n\n const result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag as any] = tag;\n } else {\n delete value[symToStringTag as any];\n }\n }\n return result;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value: any) {\n return nativeObjectToString.call(value);\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ShimWrapped } from '../common/types';\n\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nexport function isWrapped(func: unknown): func is ShimWrapped {\n return (\n typeof func === 'function' &&\n typeof (func as ShimWrapped).__original === 'function' &&\n typeof (func as ShimWrapped).__unwrap === 'function' &&\n (func as ShimWrapped).__wrapped === true\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context } from '@opentelemetry/api';\nimport { ExportResult } from '../ExportResult';\nimport { suppressTracing } from '../trace/suppress-tracing';\n\nexport interface Exporter<T> {\n export(arg: T, resultCallback: (result: ExportResult) => void): void;\n}\n\n/**\n * @internal\n * Shared functionality used by Exporters while exporting data, including suppression of Traces.\n */\nexport function _export<T>(\n exporter: Exporter<T>,\n arg: T\n): Promise<ExportResult> {\n return new Promise(resolve => {\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n exporter.export(arg, (result: ExportResult) => {\n resolve(result);\n });\n });\n });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './baggage/propagation/W3CBaggagePropagator';\nexport * from './common/anchored-clock';\nexport * from './common/attributes';\nexport * from './common/global-error-handler';\nexport * from './common/logging-error-handler';\nexport * from './common/time';\nexport * from './common/types';\nexport * from './common/hex-to-binary';\nexport * from './ExportResult';\nexport * as baggageUtils from './baggage/utils';\nexport * from './platform';\nexport * from './propagation/composite';\nexport * from './trace/W3CTraceContextPropagator';\nexport * from './trace/IdGenerator';\nexport * from './trace/rpc-metadata';\nexport * from './trace/sampler/AlwaysOffSampler';\nexport * from './trace/sampler/AlwaysOnSampler';\nexport * from './trace/sampler/ParentBasedSampler';\nexport * from './trace/sampler/TraceIdRatioBasedSampler';\nexport * from './trace/suppress-tracing';\nexport * from './trace/TraceState';\nexport * from './utils/environment';\nexport * from './utils/merge';\nexport * from './utils/sampling';\nexport * from './utils/timeout';\nexport * from './utils/url';\nexport * from './utils/wrap';\nexport * from './utils/callback';\nexport * from './version';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Event name definitions\nexport const ExceptionEventName = 'exception';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n diag,\n Exception,\n HrTime,\n Link,\n Span as APISpan,\n SpanAttributes,\n SpanAttributeValue,\n SpanContext,\n SpanKind,\n SpanStatus,\n SpanStatusCode,\n TimeInput,\n} from '@opentelemetry/api';\nimport {\n addHrTimes,\n millisToHrTime,\n getTimeOrigin,\n hrTime,\n hrTimeDuration,\n InstrumentationLibrary,\n isAttributeValue,\n isTimeInput,\n isTimeInputHrTime,\n otperformance,\n sanitizeAttributes,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { SemanticAttributes } from '@opentelemetry/semantic-conventions';\nimport { ExceptionEventName } from './enums';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { SpanProcessor } from './SpanProcessor';\nimport { TimedEvent } from './TimedEvent';\nimport { Tracer } from './Tracer';\nimport { SpanLimits } from './types';\n\n/**\n * This class represents a span.\n */\nexport class Span implements APISpan, ReadableSpan {\n // Below properties are included to implement ReadableSpan for export\n // purposes but are not intended to be written-to directly.\n private readonly _spanContext: SpanContext;\n readonly kind: SpanKind;\n readonly parentSpanId?: string;\n readonly attributes: SpanAttributes = {};\n readonly links: Link[] = [];\n readonly events: TimedEvent[] = [];\n readonly startTime: HrTime;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n private _droppedAttributesCount = 0;\n private _droppedEventsCount: number = 0;\n private _droppedLinksCount: number = 0;\n\n name: string;\n status: SpanStatus = {\n code: SpanStatusCode.UNSET,\n };\n endTime: HrTime = [0, 0];\n private _ended = false;\n private _duration: HrTime = [-1, -1];\n private readonly _spanProcessor: SpanProcessor;\n private readonly _spanLimits: SpanLimits;\n private readonly _attributeValueLengthLimit: number;\n\n private readonly _performanceStartTime: number;\n private readonly _performanceOffset: number;\n private readonly _startTimeProvided: boolean;\n\n /**\n * Constructs a new Span instance.\n *\n * @deprecated calling Span constructor directly is not supported. Please use tracer.startSpan.\n * */\n constructor(\n parentTracer: Tracer,\n context: Context,\n spanName: string,\n spanContext: SpanContext,\n kind: SpanKind,\n parentSpanId?: string,\n links: Link[] = [],\n startTime?: TimeInput,\n _deprecatedClock?: unknown, // keeping this argument even though it is unused to ensure backwards compatibility\n attributes?: SpanAttributes\n ) {\n this.name = spanName;\n this._spanContext = spanContext;\n this.parentSpanId = parentSpanId;\n this.kind = kind;\n this.links = links;\n\n const now = Date.now();\n this._performanceStartTime = otperformance.now();\n this._performanceOffset =\n now - (this._performanceStartTime + getTimeOrigin());\n this._startTimeProvided = startTime != null;\n\n this.startTime = this._getTime(startTime ?? now);\n\n this.resource = parentTracer.resource;\n this.instrumentationLibrary = parentTracer.instrumentationLibrary;\n this._spanLimits = parentTracer.getSpanLimits();\n this._attributeValueLengthLimit =\n this._spanLimits.attributeValueLengthLimit || 0;\n\n if (attributes != null) {\n this.setAttributes(attributes);\n }\n\n this._spanProcessor = parentTracer.getActiveSpanProcessor();\n this._spanProcessor.onStart(this, context);\n }\n\n spanContext(): SpanContext {\n return this._spanContext;\n }\n\n setAttribute(key: string, value?: SpanAttributeValue): this;\n setAttribute(key: string, value: unknown): this {\n if (value == null || this._isSpanEnded()) return this;\n if (key.length === 0) {\n diag.warn(`Invalid attribute key: ${key}`);\n return this;\n }\n if (!isAttributeValue(value)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n return this;\n }\n\n if (\n Object.keys(this.attributes).length >=\n this._spanLimits.attributeCountLimit! &&\n !Object.prototype.hasOwnProperty.call(this.attributes, key)\n ) {\n this._droppedAttributesCount++;\n return this;\n }\n this.attributes[key] = this._truncateToSize(value);\n return this;\n }\n\n setAttributes(attributes: SpanAttributes): this {\n for (const [k, v] of Object.entries(attributes)) {\n this.setAttribute(k, v);\n }\n return this;\n }\n\n /**\n *\n * @param name Span Name\n * @param [attributesOrStartTime] Span attributes or start time\n * if type is {@type TimeInput} and 3rd param is undefined\n * @param [timeStamp] Specified time stamp for the event\n */\n addEvent(\n name: string,\n attributesOrStartTime?: SpanAttributes | TimeInput,\n timeStamp?: TimeInput\n ): this {\n if (this._isSpanEnded()) return this;\n if (this._spanLimits.eventCountLimit === 0) {\n diag.warn('No events allowed.');\n this._droppedEventsCount++;\n return this;\n }\n if (this.events.length >= this._spanLimits.eventCountLimit!) {\n if (this._droppedEventsCount === 0) {\n diag.debug('Dropping extra events.');\n }\n this.events.shift();\n this._droppedEventsCount++;\n }\n\n if (isTimeInput(attributesOrStartTime)) {\n if (!isTimeInput(timeStamp)) {\n timeStamp = attributesOrStartTime;\n }\n attributesOrStartTime = undefined;\n }\n\n const attributes = sanitizeAttributes(attributesOrStartTime);\n\n this.events.push({\n name,\n attributes,\n time: this._getTime(timeStamp),\n droppedAttributesCount: 0,\n });\n return this;\n }\n\n setStatus(status: SpanStatus): this {\n if (this._isSpanEnded()) return this;\n this.status = status;\n return this;\n }\n\n updateName(name: string): this {\n if (this._isSpanEnded()) return this;\n this.name = name;\n return this;\n }\n\n end(endTime?: TimeInput): void {\n if (this._isSpanEnded()) {\n diag.error(\n `${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`\n );\n return;\n }\n this._ended = true;\n\n this.endTime = this._getTime(endTime);\n this._duration = hrTimeDuration(this.startTime, this.endTime);\n\n if (this._duration[0] < 0) {\n diag.warn(\n 'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',\n this.startTime,\n this.endTime\n );\n this.endTime = this.startTime.slice() as HrTime;\n this._duration = [0, 0];\n }\n\n if (this._droppedEventsCount > 0) {\n diag.warn(\n `Dropped ${this._droppedEventsCount} events because eventCountLimit reached`\n );\n }\n\n this._spanProcessor.onEnd(this);\n }\n\n private _getTime(inp?: TimeInput): HrTime {\n if (typeof inp === 'number' && inp < otperformance.now()) {\n // must be a performance timestamp\n // apply correction and convert to hrtime\n return hrTime(inp + this._performanceOffset);\n }\n\n if (typeof inp === 'number') {\n return millisToHrTime(inp);\n }\n\n if (inp instanceof Date) {\n return millisToHrTime(inp.getTime());\n }\n\n if (isTimeInputHrTime(inp)) {\n return inp;\n }\n\n if (this._startTimeProvided) {\n // if user provided a time for the start manually\n // we can't use duration to calculate event/end times\n return millisToHrTime(Date.now());\n }\n\n const msDuration = otperformance.now() - this._performanceStartTime;\n return addHrTimes(this.startTime, millisToHrTime(msDuration));\n }\n\n isRecording(): boolean {\n return this._ended === false;\n }\n\n recordException(exception: Exception, time?: TimeInput): void {\n const attributes: SpanAttributes = {};\n if (typeof exception === 'string') {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception;\n } else if (exception) {\n if (exception.code) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] =\n exception.code.toString();\n } else if (exception.name) {\n attributes[SemanticAttributes.EXCEPTION_TYPE] = exception.name;\n }\n if (exception.message) {\n attributes[SemanticAttributes.EXCEPTION_MESSAGE] = exception.message;\n }\n if (exception.stack) {\n attributes[SemanticAttributes.EXCEPTION_STACKTRACE] = exception.stack;\n }\n }\n\n // these are minimum requirements from spec\n if (\n attributes[SemanticAttributes.EXCEPTION_TYPE] ||\n attributes[SemanticAttributes.EXCEPTION_MESSAGE]\n ) {\n this.addEvent(ExceptionEventName, attributes, time);\n } else {\n diag.warn(`Failed to record an exception ${exception}`);\n }\n }\n\n get duration(): HrTime {\n return this._duration;\n }\n\n get ended(): boolean {\n return this._ended;\n }\n\n get droppedAttributesCount(): number {\n return this._droppedAttributesCount;\n }\n\n get droppedEventsCount(): number {\n return this._droppedEventsCount;\n }\n\n get droppedLinksCount(): number {\n return this._droppedLinksCount;\n }\n\n private _isSpanEnded(): boolean {\n if (this._ended) {\n diag.warn(\n `Can not execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`\n );\n }\n return this._ended;\n }\n\n // Utility function to truncate given value within size\n // for value type of string, will truncate to given limit\n // for type of non-string, will return same value\n private _truncateToLimitUtil(value: string, limit: number): string {\n if (value.length <= limit) {\n return value;\n }\n return value.substr(0, limit);\n }\n\n /**\n * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then\n * return string with truncated to {@code attributeValueLengthLimit} characters\n *\n * If the given attribute value is array of strings then\n * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters\n *\n * Otherwise return same Attribute {@code value}\n *\n * @param value Attribute value\n * @returns truncated attribute value if required, otherwise same value\n */\n private _truncateToSize(value: SpanAttributeValue): SpanAttributeValue {\n const limit = this._attributeValueLengthLimit;\n // Check limit\n if (limit <= 0) {\n // Negative values are invalid, so do not truncate\n diag.warn(`Attribute value limit must be positive, got ${limit}`);\n return value;\n }\n\n // String\n if (typeof value === 'string') {\n return this._truncateToLimitUtil(value, limit);\n }\n\n // Array of strings\n if (Array.isArray(value)) {\n return (value as []).map(val =>\n typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val\n );\n }\n\n // Other types, no need to apply value length limit\n return value;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n Link,\n SpanAttributes,\n SpanKind,\n TraceState,\n} from '@opentelemetry/api';\n\n/**\n * A sampling decision that determines how a {@link Span} will be recorded\n * and collected.\n */\nexport enum SamplingDecision {\n /**\n * `Span.isRecording() === false`, span will not be recorded and all events\n * and attributes will be dropped.\n */\n NOT_RECORD,\n /**\n * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags}\n * MUST NOT be set.\n */\n RECORD,\n /**\n * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags}\n * MUST be set.\n */\n RECORD_AND_SAMPLED,\n}\n\n/**\n * A sampling result contains a decision for a {@link Span} and additional\n * attributes the sampler would like to added to the Span.\n */\nexport interface SamplingResult {\n /**\n * A sampling decision, refer to {@link SamplingDecision} for details.\n */\n decision: SamplingDecision;\n /**\n * The list of attributes returned by SamplingResult MUST be immutable.\n * Caller may call {@link Sampler}.shouldSample any number of times and\n * can safely cache the returned value.\n */\n attributes?: Readonly<SpanAttributes>;\n /**\n * A {@link TraceState} that will be associated with the {@link Span} through\n * the new {@link SpanContext}. Samplers SHOULD return the TraceState from\n * the passed-in {@link Context} if they do not intend to change it. Leaving\n * the value undefined will also leave the TraceState unchanged.\n */\n traceState?: TraceState;\n}\n\n/**\n * This interface represent a sampler. Sampling is a mechanism to control the\n * noise and overhead introduced by OpenTelemetry by reducing the number of\n * samples of traces collected and sent to the backend.\n */\nexport interface Sampler {\n /**\n * Checks whether span needs to be created and tracked.\n *\n * @param context Parent Context which may contain a span.\n * @param traceId of the span to be created. It can be different from the\n * traceId in the {@link SpanContext}. Typically in situations when the\n * span to be created starts a new trace.\n * @param spanName of the span to be created.\n * @param spanKind of the span to be created.\n * @param attributes Initial set of SpanAttributes for the Span being constructed.\n * @param links Collection of links that will be associated with the Span to\n * be created. Typically useful for batch operations.\n * @returns a {@link SamplingResult}.\n */\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult;\n\n /** Returns the sampler name or short description with the configuration. */\n toString(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples no traces. */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples all traces. */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n SpanAttributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\nimport { Sampler, SamplingResult } from '../Sampler';\n\n/**\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isValidTraceId } from '@opentelemetry/api';\nimport { Sampler, SamplingDecision, SamplingResult } from '../Sampler';\n\n/** Sampler that samples a given fraction of traces based of trace id deterministically. */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\nimport { getEnv, TracesSamplerValues, ENVIRONMENT } from '@opentelemetry/core';\nimport { Sampler } from './Sampler';\nimport { AlwaysOffSampler } from './sampler/AlwaysOffSampler';\nimport { AlwaysOnSampler } from './sampler/AlwaysOnSampler';\nimport { ParentBasedSampler } from './sampler/ParentBasedSampler';\nimport { TraceIdRatioBasedSampler } from './sampler/TraceIdRatioBasedSampler';\n\nconst env = getEnv();\nconst FALLBACK_OTEL_TRACES_SAMPLER = TracesSamplerValues.AlwaysOn;\nconst DEFAULT_RATIO = 1;\n\n/**\n * Load default configuration. For fields with primitive values, any user-provided\n * value will override the corresponding default value. For fields with\n * non-primitive values (like `spanLimits`), the user-provided value will be\n * used to extend the default value.\n */\n\n// object needs to be wrapped in this function and called when needed otherwise\n// envs are parsed before tests are ran - causes tests using these envs to fail\nexport function loadDefaultConfig() {\n return {\n sampler: buildSamplerFromEnv(env),\n forceFlushTimeoutMillis: 30000,\n generalLimits: {\n attributeValueLengthLimit: getEnv().OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: getEnv().OTEL_ATTRIBUTE_COUNT_LIMIT,\n },\n spanLimits: {\n attributeValueLengthLimit:\n getEnv().OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n attributeCountLimit: getEnv().OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT,\n linkCountLimit: getEnv().OTEL_SPAN_LINK_COUNT_LIMIT,\n eventCountLimit: getEnv().OTEL_SPAN_EVENT_COUNT_LIMIT,\n attributePerEventCountLimit:\n getEnv().OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n attributePerLinkCountLimit:\n getEnv().OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n },\n };\n}\n\n/**\n * Based on environment, builds a sampler, complies with specification.\n * @param environment optional, by default uses getEnv(), but allows passing a value to reuse parsed environment\n */\nexport function buildSamplerFromEnv(\n environment: Required<ENVIRONMENT> = getEnv()\n): Sampler {\n switch (environment.OTEL_TRACES_SAMPLER) {\n case TracesSamplerValues.AlwaysOn:\n return new AlwaysOnSampler();\n case TracesSamplerValues.AlwaysOff:\n return new AlwaysOffSampler();\n case TracesSamplerValues.ParentBasedAlwaysOn:\n return new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n case TracesSamplerValues.ParentBasedAlwaysOff:\n return new ParentBasedSampler({\n root: new AlwaysOffSampler(),\n });\n case TracesSamplerValues.TraceIdRatio:\n return new TraceIdRatioBasedSampler(\n getSamplerProbabilityFromEnv(environment)\n );\n case TracesSamplerValues.ParentBasedTraceIdRatio:\n return new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(\n getSamplerProbabilityFromEnv(environment)\n ),\n });\n default:\n diag.error(\n `OTEL_TRACES_SAMPLER value \"${environment.OTEL_TRACES_SAMPLER} invalid, defaulting to ${FALLBACK_OTEL_TRACES_SAMPLER}\".`\n );\n return new AlwaysOnSampler();\n }\n}\n\nfunction getSamplerProbabilityFromEnv(\n environment: Required<ENVIRONMENT>\n): number | undefined {\n if (\n environment.OTEL_TRACES_SAMPLER_ARG === undefined ||\n environment.OTEL_TRACES_SAMPLER_ARG === ''\n ) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n const probability = Number(environment.OTEL_TRACES_SAMPLER_ARG);\n\n if (isNaN(probability)) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n if (probability < 0 || probability > 1) {\n diag.error(\n `OTEL_TRACES_SAMPLER_ARG=${environment.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`\n );\n return DEFAULT_RATIO;\n }\n\n return probability;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { buildSamplerFromEnv, loadDefaultConfig } from './config';\nimport { Sampler } from './Sampler';\nimport { SpanLimits, TracerConfig, GeneralLimits } from './types';\nimport {\n DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n getEnvWithoutDefaults,\n} from '@opentelemetry/core';\n\n/**\n * Function to merge Default configuration (as specified in './config') with\n * user provided configurations.\n */\nexport function mergeConfig(userConfig: TracerConfig): TracerConfig & {\n sampler: Sampler;\n spanLimits: SpanLimits;\n generalLimits: GeneralLimits;\n} {\n const perInstanceDefaults: Partial<TracerConfig> = {\n sampler: buildSamplerFromEnv(),\n };\n\n const DEFAULT_CONFIG = loadDefaultConfig();\n\n const target = Object.assign(\n {},\n DEFAULT_CONFIG,\n perInstanceDefaults,\n userConfig\n );\n\n target.generalLimits = Object.assign(\n {},\n DEFAULT_CONFIG.generalLimits,\n userConfig.generalLimits || {}\n );\n\n target.spanLimits = Object.assign(\n {},\n DEFAULT_CONFIG.spanLimits,\n userConfig.spanLimits || {}\n );\n\n return target;\n}\n\n/**\n * When general limits are provided and model specific limits are not,\n * configures the model specific limits by using the values from the general ones.\n * @param userConfig User provided tracer configuration\n */\nexport function reconfigureLimits(userConfig: TracerConfig): TracerConfig {\n const spanLimits = Object.assign({}, userConfig.spanLimits);\n\n const parsedEnvConfig = getEnvWithoutDefaults();\n\n /**\n * Reassign span attribute count limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeCountLimit =\n userConfig.spanLimits?.attributeCountLimit ??\n userConfig.generalLimits?.attributeCountLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_COUNT_LIMIT ??\n DEFAULT_ATTRIBUTE_COUNT_LIMIT;\n\n /**\n * Reassign span attribute value length limit to use first non null value defined by user or use default value\n */\n spanLimits.attributeValueLengthLimit =\n userConfig.spanLimits?.attributeValueLengthLimit ??\n userConfig.generalLimits?.attributeValueLengthLimit ??\n parsedEnvConfig.OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n parsedEnvConfig.OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT ??\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT;\n\n return Object.assign({}, userConfig, { spanLimits });\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, Context, diag, TraceFlags } from '@opentelemetry/api';\nimport {\n BindOnceFuture,\n ExportResultCode,\n getEnv,\n globalErrorHandler,\n suppressTracing,\n unrefTimer,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { BufferConfig } from '../types';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\n\n/**\n * Implementation of the {@link SpanProcessor} that batches spans exported by\n * the SDK then pushes them to the exporter pipeline.\n */\nexport abstract class BatchSpanProcessorBase<T extends BufferConfig>\n implements SpanProcessor\n{\n private readonly _maxExportBatchSize: number;\n private readonly _maxQueueSize: number;\n private readonly _scheduledDelayMillis: number;\n private readonly _exportTimeoutMillis: number;\n\n private _isExporting = false;\n private _finishedSpans: ReadableSpan[] = [];\n private _timer: NodeJS.Timeout | undefined;\n private _shutdownOnce: BindOnceFuture<void>;\n private _droppedSpansCount: number = 0;\n\n constructor(\n private readonly _exporter: SpanExporter,\n config?: T\n ) {\n const env = getEnv();\n this._maxExportBatchSize =\n typeof config?.maxExportBatchSize === 'number'\n ? config.maxExportBatchSize\n : env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE;\n this._maxQueueSize =\n typeof config?.maxQueueSize === 'number'\n ? config.maxQueueSize\n : env.OTEL_BSP_MAX_QUEUE_SIZE;\n this._scheduledDelayMillis =\n typeof config?.scheduledDelayMillis === 'number'\n ? config.scheduledDelayMillis\n : env.OTEL_BSP_SCHEDULE_DELAY;\n this._exportTimeoutMillis =\n typeof config?.exportTimeoutMillis === 'number'\n ? config.exportTimeoutMillis\n : env.OTEL_BSP_EXPORT_TIMEOUT;\n\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n\n if (this._maxExportBatchSize > this._maxQueueSize) {\n diag.warn(\n 'BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'\n );\n this._maxExportBatchSize = this._maxQueueSize;\n }\n }\n\n forceFlush(): Promise<void> {\n if (this._shutdownOnce.isCalled) {\n return this._shutdownOnce.promise;\n }\n return this._flushAll();\n }\n\n // does nothing.\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n this._addToBuffer(span);\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown() {\n return Promise.resolve()\n .then(() => {\n return this.onShutdown();\n })\n .then(() => {\n return this._flushAll();\n })\n .then(() => {\n return this._exporter.shutdown();\n });\n }\n\n /** Add a span in the buffer. */\n private _addToBuffer(span: ReadableSpan) {\n if (this._finishedSpans.length >= this._maxQueueSize) {\n // limit reached, drop span\n\n if (this._droppedSpansCount === 0) {\n diag.debug('maxQueueSize reached, dropping spans');\n }\n this._droppedSpansCount++;\n\n return;\n }\n\n if (this._droppedSpansCount > 0) {\n // some spans were dropped, log once with count of spans dropped\n diag.warn(\n `Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`\n );\n this._droppedSpansCount = 0;\n }\n\n this._finishedSpans.push(span);\n this._maybeStartTimer();\n }\n\n /**\n * Send all spans to the exporter respecting the batch size limit\n * This function is used only on forceFlush or shutdown,\n * for all other cases _flush should be used\n * */\n private _flushAll(): Promise<void> {\n return new Promise((resolve, reject) => {\n const promises = [];\n // calculate number of batches\n const count = Math.ceil(\n this._finishedSpans.length / this._maxExportBatchSize\n );\n for (let i = 0, j = count; i < j; i++) {\n promises.push(this._flushOneBatch());\n }\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(reject);\n });\n }\n\n private _flushOneBatch(): Promise<void> {\n this._clearTimer();\n if (this._finishedSpans.length === 0) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n // don't wait anymore for export, this way the next batch can start\n reject(new Error('Timeout'));\n }, this._exportTimeoutMillis);\n // prevent downstream exporter calls from generating spans\n context.with(suppressTracing(context.active()), () => {\n // Reset the finished spans buffer here because the next invocations of the _flush method\n // could pass the same finished spans to the exporter if the buffer is cleared\n // outside the execution of this callback.\n let spans: ReadableSpan[];\n if (this._finishedSpans.length <= this._maxExportBatchSize) {\n spans = this._finishedSpans;\n this._finishedSpans = [];\n } else {\n spans = this._finishedSpans.splice(0, this._maxExportBatchSize);\n }\n\n const doExport = () =>\n this._exporter.export(spans, result => {\n clearTimeout(timer);\n if (result.code === ExportResultCode.SUCCESS) {\n resolve();\n } else {\n reject(\n result.error ??\n new Error('BatchSpanProcessor: span export failed')\n );\n }\n });\n\n let pendingResources: Array<Promise<void>> | null = null;\n for (let i = 0, len = spans.length; i < len; i++) {\n const span = spans[i];\n if (\n span.resource.asyncAttributesPending &&\n span.resource.waitForAsyncAttributes\n ) {\n pendingResources ??= [];\n pendingResources.push(span.resource.waitForAsyncAttributes());\n }\n }\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (pendingResources === null) {\n doExport();\n } else {\n Promise.all(pendingResources).then(doExport, err => {\n globalErrorHandler(err);\n reject(err);\n });\n }\n });\n });\n }\n\n private _maybeStartTimer() {\n if (this._isExporting) return;\n const flush = () => {\n this._isExporting = true;\n this._flushOneBatch()\n .finally(() => {\n this._isExporting = false;\n if (this._finishedSpans.length > 0) {\n this._clearTimer();\n this._maybeStartTimer();\n }\n })\n .catch(e => {\n this._isExporting = false;\n globalErrorHandler(e);\n });\n };\n // we only wait if the queue doesn't have enough elements yet\n if (this._finishedSpans.length >= this._maxExportBatchSize) {\n return flush();\n }\n if (this._timer !== undefined) return;\n this._timer = setTimeout(() => flush(), this._scheduledDelayMillis);\n unrefTimer(this._timer);\n }\n\n private _clearTimer() {\n if (this._timer !== undefined) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n\n protected abstract onShutdown(): void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchSpanProcessorBase } from '../../../export/BatchSpanProcessorBase';\nimport { BufferConfig } from '../../../types';\n\nexport class BatchSpanProcessor extends BatchSpanProcessorBase<BufferConfig> {\n protected onShutdown(): void {}\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../IdGenerator';\n\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './export/BatchSpanProcessor';\nexport * from './RandomIdGenerator';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport {\n InstrumentationLibrary,\n sanitizeAttributes,\n isTracingSuppressed,\n} from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { BasicTracerProvider } from './BasicTracerProvider';\nimport { Span } from './Span';\nimport { GeneralLimits, SpanLimits, TracerConfig } from './types';\nimport { mergeConfig } from './utility';\nimport { SpanProcessor } from './SpanProcessor';\nimport { Sampler } from './Sampler';\nimport { IdGenerator } from './IdGenerator';\nimport { RandomIdGenerator } from './platform';\n\n/**\n * This class represents a basic tracer.\n */\nexport class Tracer implements api.Tracer {\n private readonly _sampler: Sampler;\n private readonly _generalLimits: GeneralLimits;\n private readonly _spanLimits: SpanLimits;\n private readonly _idGenerator: IdGenerator;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n\n /**\n * Constructs a new Tracer instance.\n */\n constructor(\n instrumentationLibrary: InstrumentationLibrary,\n config: TracerConfig,\n private _tracerProvider: BasicTracerProvider\n ) {\n const localConfig = mergeConfig(config);\n this._sampler = localConfig.sampler;\n this._generalLimits = localConfig.generalLimits;\n this._spanLimits = localConfig.spanLimits;\n this._idGenerator = config.idGenerator || new RandomIdGenerator();\n this.resource = _tracerProvider.resource;\n this.instrumentationLibrary = instrumentationLibrary;\n }\n\n /**\n * Starts a new Span or returns the default NoopSpan based on the sampling\n * decision.\n */\n startSpan(\n name: string,\n options: api.SpanOptions = {},\n context = api.context.active()\n ): api.Span {\n // remove span from context in case a root span is requested via options\n if (options.root) {\n context = api.trace.deleteSpan(context);\n }\n const parentSpan = api.trace.getSpan(context);\n\n if (isTracingSuppressed(context)) {\n api.diag.debug('Instrumentation suppressed, returning Noop Span');\n const nonRecordingSpan = api.trace.wrapSpanContext(\n api.INVALID_SPAN_CONTEXT\n );\n return nonRecordingSpan;\n }\n\n const parentSpanContext = parentSpan?.spanContext();\n const spanId = this._idGenerator.generateSpanId();\n let traceId;\n let traceState;\n let parentSpanId;\n if (\n !parentSpanContext ||\n !api.trace.isSpanContextValid(parentSpanContext)\n ) {\n // New root span.\n traceId = this._idGenerator.generateTraceId();\n } else {\n // New child span.\n traceId = parentSpanContext.traceId;\n traceState = parentSpanContext.traceState;\n parentSpanId = parentSpanContext.spanId;\n }\n\n const spanKind = options.kind ?? api.SpanKind.INTERNAL;\n const links = (options.links ?? []).map(link => {\n return {\n context: link.context,\n attributes: sanitizeAttributes(link.attributes),\n };\n });\n const attributes = sanitizeAttributes(options.attributes);\n // make sampling decision\n const samplingResult = this._sampler.shouldSample(\n context,\n traceId,\n name,\n spanKind,\n attributes,\n links\n );\n\n traceState = samplingResult.traceState ?? traceState;\n\n const traceFlags =\n samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED\n ? api.TraceFlags.SAMPLED\n : api.TraceFlags.NONE;\n const spanContext = { traceId, spanId, traceFlags, traceState };\n if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) {\n api.diag.debug(\n 'Recording is off, propagating context in a non-recording span'\n );\n const nonRecordingSpan = api.trace.wrapSpanContext(spanContext);\n return nonRecordingSpan;\n }\n\n // Set initial span attributes. The attributes object may have been mutated\n // by the sampler, so we sanitize the merged attributes before setting them.\n const initAttributes = sanitizeAttributes(\n Object.assign(attributes, samplingResult.attributes)\n );\n\n const span = new Span(\n this,\n context,\n name,\n spanContext,\n spanKind,\n parentSpanId,\n links,\n options.startTime,\n undefined,\n initAttributes\n );\n return span;\n }\n\n /**\n * Starts a new {@link Span} and calls the given function passing it the\n * created span as first argument.\n * Additionally the new span gets set in context and this context is activated\n * for the duration of the function call.\n *\n * @param name The name of the span\n * @param [options] SpanOptions used for span creation\n * @param [context] Context to use to extract parent\n * @param fn function called in the context of the span and receives the newly created span as an argument\n * @returns return value of fn\n * @example\n * const something = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * span.setStatus({code: SpanStatusCode.OK});\n * return something;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * } finally {\n * span.end();\n * }\n * });\n * @example\n * const span = tracer.startActiveSpan('op', span => {\n * try {\n * do some work\n * return span;\n * } catch (err) {\n * span.setStatus({\n * code: SpanStatusCode.ERROR,\n * message: err.message,\n * });\n * throw err;\n * }\n * });\n * do some more work\n * span.end();\n */\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n opts: api.SpanOptions,\n ctx: api.Context,\n fn: F\n ): ReturnType<F>;\n startActiveSpan<F extends (span: api.Span) => ReturnType<F>>(\n name: string,\n arg2?: F | api.SpanOptions,\n arg3?: F | api.Context,\n arg4?: F\n ): ReturnType<F> | undefined {\n let opts: api.SpanOptions | undefined;\n let ctx: api.Context | undefined;\n let fn: F;\n\n if (arguments.length < 2) {\n return;\n } else if (arguments.length === 2) {\n fn = arg2 as F;\n } else if (arguments.length === 3) {\n opts = arg2 as api.SpanOptions | undefined;\n fn = arg3 as F;\n } else {\n opts = arg2 as api.SpanOptions | undefined;\n ctx = arg3 as api.Context | undefined;\n fn = arg4 as F;\n }\n\n const parentContext = ctx ?? api.context.active();\n const span = this.startSpan(name, opts, parentContext);\n const contextWithSpanSet = api.trace.setSpan(parentContext, span);\n\n return api.context.with(contextWithSpanSet, fn, undefined, span);\n }\n\n /** Returns the active {@link GeneralLimits}. */\n getGeneralLimits(): GeneralLimits {\n return this._generalLimits;\n }\n\n /** Returns the active {@link SpanLimits}. */\n getSpanLimits(): SpanLimits {\n return this._spanLimits;\n }\n\n getActiveSpanProcessor(): SpanProcessor {\n return this._tracerProvider.getActiveSpanProcessor();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { globalErrorHandler } from '@opentelemetry/core';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\nimport { SpanProcessor } from './SpanProcessor';\n\n/**\n * Implementation of the {@link SpanProcessor} that simply forwards all\n * received events to a list of {@link SpanProcessor}s.\n */\nexport class MultiSpanProcessor implements SpanProcessor {\n constructor(private readonly _spanProcessors: SpanProcessor[]) {}\n\n forceFlush(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.forceFlush());\n }\n return new Promise(resolve => {\n Promise.all(promises)\n .then(() => {\n resolve();\n })\n .catch(error => {\n globalErrorHandler(\n error || new Error('MultiSpanProcessor: forceFlush failed')\n );\n resolve();\n });\n });\n }\n\n onStart(span: Span, context: Context): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onStart(span, context);\n }\n }\n\n onEnd(span: ReadableSpan): void {\n for (const spanProcessor of this._spanProcessors) {\n spanProcessor.onEnd(span);\n }\n }\n\n shutdown(): Promise<void> {\n const promises: Promise<void>[] = [];\n\n for (const spanProcessor of this._spanProcessors) {\n promises.push(spanProcessor.shutdown());\n }\n return new Promise((resolve, reject) => {\n Promise.all(promises).then(() => {\n resolve();\n }, reject);\n });\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { ReadableSpan } from './ReadableSpan';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\n\n/** No-op implementation of SpanProcessor */\nexport class NoopSpanProcessor implements SpanProcessor {\n onStart(_span: Span, _context: Context): void {}\n onEnd(_span: ReadableSpan): void {}\n shutdown(): Promise<void> {\n return Promise.resolve();\n }\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n context,\n diag,\n propagation,\n TextMapPropagator,\n trace,\n TracerProvider,\n} from '@opentelemetry/api';\nimport {\n CompositePropagator,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n getEnv,\n merge,\n} from '@opentelemetry/core';\nimport { IResource, Resource } from '@opentelemetry/resources';\nimport { SpanProcessor, Tracer } from '.';\nimport { loadDefaultConfig } from './config';\nimport { MultiSpanProcessor } from './MultiSpanProcessor';\nimport { NoopSpanProcessor } from './export/NoopSpanProcessor';\nimport { SDKRegistrationConfig, TracerConfig } from './types';\nimport { SpanExporter } from './export/SpanExporter';\nimport { BatchSpanProcessor } from './platform';\nimport { reconfigureLimits } from './utility';\n\nexport type PROPAGATOR_FACTORY = () => TextMapPropagator;\nexport type EXPORTER_FACTORY = () => SpanExporter;\n\nexport enum ForceFlushState {\n 'resolved',\n 'timeout',\n 'error',\n 'unresolved',\n}\n\n/**\n * This class represents a basic tracer provider which platform libraries can extend\n */\nexport class BasicTracerProvider implements TracerProvider {\n protected static readonly _registeredPropagators = new Map<\n string,\n PROPAGATOR_FACTORY\n >([\n ['tracecontext', () => new W3CTraceContextPropagator()],\n ['baggage', () => new W3CBaggagePropagator()],\n ]);\n\n protected static readonly _registeredExporters = new Map<\n string,\n EXPORTER_FACTORY\n >();\n\n private readonly _config: TracerConfig;\n private readonly _registeredSpanProcessors: SpanProcessor[] = [];\n private readonly _tracers: Map<string, Tracer> = new Map();\n\n activeSpanProcessor: SpanProcessor;\n readonly resource: IResource;\n\n constructor(config: TracerConfig = {}) {\n const mergedConfig = merge(\n {},\n loadDefaultConfig(),\n reconfigureLimits(config)\n );\n this.resource = mergedConfig.resource ?? Resource.empty();\n this.resource = Resource.default().merge(this.resource);\n this._config = Object.assign({}, mergedConfig, {\n resource: this.resource,\n });\n\n const defaultExporter = this._buildExporterFromEnv();\n if (defaultExporter !== undefined) {\n const batchProcessor = new BatchSpanProcessor(defaultExporter);\n this.activeSpanProcessor = batchProcessor;\n } else {\n this.activeSpanProcessor = new NoopSpanProcessor();\n }\n }\n\n getTracer(\n name: string,\n version?: string,\n options?: { schemaUrl?: string }\n ): Tracer {\n const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`;\n if (!this._tracers.has(key)) {\n this._tracers.set(\n key,\n new Tracer(\n { name, version, schemaUrl: options?.schemaUrl },\n this._config,\n this\n )\n );\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return this._tracers.get(key)!;\n }\n\n /**\n * Adds a new {@link SpanProcessor} to this tracer.\n * @param spanProcessor the new SpanProcessor to be added.\n */\n addSpanProcessor(spanProcessor: SpanProcessor): void {\n if (this._registeredSpanProcessors.length === 0) {\n // since we might have enabled by default a batchProcessor, we disable it\n // before adding the new one\n this.activeSpanProcessor\n .shutdown()\n .catch(err =>\n diag.error(\n 'Error while trying to shutdown current span processor',\n err\n )\n );\n }\n this._registeredSpanProcessors.push(spanProcessor);\n this.activeSpanProcessor = new MultiSpanProcessor(\n this._registeredSpanProcessors\n );\n }\n\n getActiveSpanProcessor(): SpanProcessor {\n return this.activeSpanProcessor;\n }\n\n /**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\n register(config: SDKRegistrationConfig = {}): void {\n trace.setGlobalTracerProvider(this);\n if (config.propagator === undefined) {\n config.propagator = this._buildPropagatorFromEnv();\n }\n\n if (config.contextManager) {\n context.setGlobalContextManager(config.contextManager);\n }\n\n if (config.propagator) {\n propagation.setGlobalPropagator(config.propagator);\n }\n }\n\n forceFlush(): Promise<void> {\n const timeout = this._config.forceFlushTimeoutMillis;\n const promises = this._registeredSpanProcessors.map(\n (spanProcessor: SpanProcessor) => {\n return new Promise(resolve => {\n let state: ForceFlushState;\n const timeoutInterval = setTimeout(() => {\n resolve(\n new Error(\n `Span processor did not completed within timeout period of ${timeout} ms`\n )\n );\n state = ForceFlushState.timeout;\n }, timeout);\n\n spanProcessor\n .forceFlush()\n .then(() => {\n clearTimeout(timeoutInterval);\n if (state !== ForceFlushState.timeout) {\n state = ForceFlushState.resolved;\n resolve(state);\n }\n })\n .catch(error => {\n clearTimeout(timeoutInterval);\n state = ForceFlushState.error;\n resolve(error);\n });\n });\n }\n );\n\n return new Promise<void>((resolve, reject) => {\n Promise.all(promises)\n .then(results => {\n const errors = results.filter(\n result => result !== ForceFlushState.resolved\n );\n if (errors.length > 0) {\n reject(errors);\n } else {\n resolve();\n }\n })\n .catch(error => reject([error]));\n });\n }\n\n shutdown(): Promise<void> {\n return this.activeSpanProcessor.shutdown();\n }\n\n /**\n * TS cannot yet infer the type of this.constructor:\n * https://github.com/Microsoft/TypeScript/issues/3841#issuecomment-337560146\n * There is no need to override either of the getters in your child class.\n * The type of the registered component maps should be the same across all\n * classes in the inheritance tree.\n */\n protected _getPropagator(name: string): TextMapPropagator | undefined {\n return (\n this.constructor as typeof BasicTracerProvider\n )._registeredPropagators.get(name)?.();\n }\n\n protected _getSpanExporter(name: string): SpanExporter | undefined {\n return (\n this.constructor as typeof BasicTracerProvider\n )._registeredExporters.get(name)?.();\n }\n\n protected _buildPropagatorFromEnv(): TextMapPropagator | undefined {\n // per spec, propagators from env must be deduplicated\n const uniquePropagatorNames = Array.from(\n new Set(getEnv().OTEL_PROPAGATORS)\n );\n\n const propagators = uniquePropagatorNames.map(name => {\n const propagator = this._getPropagator(name);\n if (!propagator) {\n diag.warn(\n `Propagator \"${name}\" requested through environment variable is unavailable.`\n );\n }\n\n return propagator;\n });\n const validPropagators = propagators.reduce<TextMapPropagator[]>(\n (list, item) => {\n if (item) {\n list.push(item);\n }\n return list;\n },\n []\n );\n\n if (validPropagators.length === 0) {\n return;\n } else if (uniquePropagatorNames.length === 1) {\n return validPropagators[0];\n } else {\n return new CompositePropagator({\n propagators: validPropagators,\n });\n }\n }\n\n protected _buildExporterFromEnv(): SpanExporter | undefined {\n const exporterName = getEnv().OTEL_TRACES_EXPORTER;\n if (exporterName === 'none' || exporterName === '') return;\n const exporter = this._getSpanExporter(exporterName);\n if (!exporter) {\n diag.error(\n `Exporter \"${exporterName}\" requested through environment variable is unavailable.`\n );\n }\n return exporter;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport {\n ExportResult,\n ExportResultCode,\n hrTimeToMicroseconds,\n} from '@opentelemetry/core';\n\n/**\n * This is implementation of {@link SpanExporter} that prints spans to the\n * console. This class can be used for diagnostic purposes.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleSpanExporter implements SpanExporter {\n /**\n * Export spans.\n * @param spans\n * @param resultCallback\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n return this._sendSpans(spans, resultCallback);\n }\n\n /**\n * Shutdown the exporter.\n */\n shutdown(): Promise<void> {\n this._sendSpans([]);\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * converts span info into more readable format\n * @param span\n */\n private _exportInfo(span: ReadableSpan) {\n return {\n resource: {\n attributes: span.resource.attributes,\n },\n traceId: span.spanContext().traceId,\n parentId: span.parentSpanId,\n traceState: span.spanContext().traceState?.serialize(),\n name: span.name,\n id: span.spanContext().spanId,\n kind: span.kind,\n timestamp: hrTimeToMicroseconds(span.startTime),\n duration: hrTimeToMicroseconds(span.duration),\n attributes: span.attributes,\n status: span.status,\n events: span.events,\n links: span.links,\n };\n }\n\n /**\n * Showing spans in console\n * @param spans\n * @param done\n */\n private _sendSpans(\n spans: ReadableSpan[],\n done?: (result: ExportResult) => void\n ): void {\n for (const span of spans) {\n console.dir(this._exportInfo(span), { depth: 3 });\n }\n if (done) {\n return done({ code: ExportResultCode.SUCCESS });\n }\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SpanExporter } from './SpanExporter';\nimport { ReadableSpan } from './ReadableSpan';\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\n\n/**\n * This class can be used for testing purposes. It stores the exported spans\n * in a list in memory that can be retrieved using the `getFinishedSpans()`\n * method.\n */\nexport class InMemorySpanExporter implements SpanExporter {\n private _finishedSpans: ReadableSpan[] = [];\n /**\n * Indicates if the exporter has been \"shutdown.\"\n * When false, exported spans will not be stored in-memory.\n */\n protected _stopped = false;\n\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._stopped)\n return resultCallback({\n code: ExportResultCode.FAILED,\n error: new Error('Exporter has been stopped'),\n });\n this._finishedSpans.push(...spans);\n\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n shutdown(): Promise<void> {\n this._stopped = true;\n this._finishedSpans = [];\n return this.forceFlush();\n }\n\n /**\n * Exports any pending spans in the exporter\n */\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset(): void {\n this._finishedSpans = [];\n }\n\n getFinishedSpans(): ReadableSpan[] {\n return this._finishedSpans;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n SpanKind,\n SpanStatus,\n SpanAttributes,\n HrTime,\n Link,\n SpanContext,\n} from '@opentelemetry/api';\nimport { IResource } from '@opentelemetry/resources';\nimport { InstrumentationLibrary } from '@opentelemetry/core';\nimport { TimedEvent } from '../TimedEvent';\n\nexport interface ReadableSpan {\n readonly name: string;\n readonly kind: SpanKind;\n readonly spanContext: () => SpanContext;\n readonly parentSpanId?: string;\n readonly startTime: HrTime;\n readonly endTime: HrTime;\n readonly status: SpanStatus;\n readonly attributes: SpanAttributes;\n readonly links: Link[];\n readonly events: TimedEvent[];\n readonly duration: HrTime;\n readonly ended: boolean;\n readonly resource: IResource;\n readonly instrumentationLibrary: InstrumentationLibrary;\n readonly droppedAttributesCount: number;\n readonly droppedEventsCount: number;\n readonly droppedLinksCount: number;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, TraceFlags } from '@opentelemetry/api';\nimport {\n internal,\n ExportResultCode,\n globalErrorHandler,\n BindOnceFuture,\n ExportResult,\n} from '@opentelemetry/core';\nimport { Span } from '../Span';\nimport { SpanProcessor } from '../SpanProcessor';\nimport { ReadableSpan } from './ReadableSpan';\nimport { SpanExporter } from './SpanExporter';\nimport { Resource } from '@opentelemetry/resources';\n\n/**\n * An implementation of the {@link SpanProcessor} that converts the {@link Span}\n * to {@link ReadableSpan} and passes it to the configured exporter.\n *\n * Only spans that are sampled are converted.\n */\nexport class SimpleSpanProcessor implements SpanProcessor {\n private _shutdownOnce: BindOnceFuture<void>;\n private _unresolvedExports: Set<Promise<void>>;\n\n constructor(private readonly _exporter: SpanExporter) {\n this._shutdownOnce = new BindOnceFuture(this._shutdown, this);\n this._unresolvedExports = new Set<Promise<void>>();\n }\n\n async forceFlush(): Promise<void> {\n // await unresolved resources before resolving\n await Promise.all(Array.from(this._unresolvedExports));\n if (this._exporter.forceFlush) {\n await this._exporter.forceFlush();\n }\n }\n\n onStart(_span: Span, _parentContext: Context): void {}\n\n onEnd(span: ReadableSpan): void {\n if (this._shutdownOnce.isCalled) {\n return;\n }\n\n if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n return;\n }\n\n const doExport = () =>\n internal\n ._export(this._exporter, [span])\n .then((result: ExportResult) => {\n if (result.code !== ExportResultCode.SUCCESS) {\n globalErrorHandler(\n result.error ??\n new Error(\n `SimpleSpanProcessor: span export failed (status ${result})`\n )\n );\n }\n })\n .catch(error => {\n globalErrorHandler(error);\n });\n\n // Avoid scheduling a promise to make the behavior more predictable and easier to test\n if (span.resource.asyncAttributesPending) {\n const exportPromise = (span.resource as Resource)\n .waitForAsyncAttributes?.()\n .then(\n () => {\n if (exportPromise != null) {\n this._unresolvedExports.delete(exportPromise);\n }\n return doExport();\n },\n err => globalErrorHandler(err)\n );\n\n // store the unresolved exports\n if (exportPromise != null) {\n this._unresolvedExports.add(exportPromise);\n }\n } else {\n void doExport();\n }\n }\n\n shutdown(): Promise<void> {\n return this._shutdownOnce.call();\n }\n\n private _shutdown(): Promise<void> {\n return this._exporter.shutdown();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExportResult } from '@opentelemetry/core';\nimport { ReadableSpan } from './ReadableSpan';\n\n/**\n * An interface that allows different tracing services to export recorded data\n * for sampled spans in their own format.\n *\n * To export data this MUST be register to the Tracer SDK using a optional\n * config.\n */\nexport interface SpanExporter {\n /**\n * Called to export sampled {@link ReadableSpan}s.\n * @param spans the list of sampled Spans to be exported.\n */\n export(\n spans: ReadableSpan[],\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /** Stops the exporter. */\n shutdown(): Promise<void>;\n\n /** Immediately export all spans */\n forceFlush?(): Promise<void>;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from '@opentelemetry/api';\nimport { ReadableSpan } from './export/ReadableSpan';\nimport { Span } from './Span';\n\n/**\n * SpanProcessor is the interface Tracer SDK uses to allow synchronous hooks\n * for when a {@link Span} is started or when a {@link Span} is ended.\n */\nexport interface SpanProcessor {\n /**\n * Forces to export all finished spans\n */\n forceFlush(): Promise<void>;\n\n /**\n * Called when a {@link Span} is started, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just started.\n */\n onStart(span: Span, parentContext: Context): void;\n\n /**\n * Called when a {@link ReadableSpan} is ended, if the `span.isRecording()`\n * returns true.\n * @param span the Span that just ended.\n */\n onEnd(span: ReadableSpan): void;\n\n /**\n * Shuts down the processor. Called when SDK is shut down. This is an\n * opportunity for processor to do any cleanup required.\n */\n shutdown(): Promise<void>;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HrTime, SpanAttributes } from '@opentelemetry/api';\n\n/**\n * Represents a timed event.\n * A timed event is an event with a timestamp.\n */\nexport interface TimedEvent {\n time: HrTime;\n /** The name of the event. */\n name: string;\n /** The attributes of the event. */\n attributes?: SpanAttributes;\n /** Count of attributes of the event that were dropped due to collection limits */\n droppedAttributesCount?: number;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ContextManager, TextMapPropagator } from '@opentelemetry/api';\nimport { IResource } from '@opentelemetry/resources';\nimport { IdGenerator } from './IdGenerator';\nimport { Sampler } from './Sampler';\n\n/**\n * TracerConfig provides an interface for configuring a Basic Tracer.\n */\nexport interface TracerConfig {\n /**\n * Sampler determines if a span should be recorded or should be a NoopSpan.\n */\n sampler?: Sampler;\n\n /** General Limits */\n generalLimits?: GeneralLimits;\n\n /** Span Limits */\n spanLimits?: SpanLimits;\n\n /** Resource associated with trace telemetry */\n resource?: IResource;\n\n /**\n * Generator of trace and span IDs\n * The default idGenerator generates random ids\n */\n idGenerator?: IdGenerator;\n\n /**\n * How long the forceFlush can run before it is cancelled.\n * The default value is 30000ms\n */\n forceFlushTimeoutMillis?: number;\n}\n\n/**\n * Configuration options for registering the API with the SDK.\n * Undefined values may be substituted for defaults, and null\n * values will not be registered.\n */\nexport interface SDKRegistrationConfig {\n /** Propagator to register as the global propagator */\n propagator?: TextMapPropagator | null;\n\n /** Context manager to register as the global context manager */\n contextManager?: ContextManager | null;\n}\n\n/** Global configuration limits of trace service */\nexport interface GeneralLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per trace */\n attributeCountLimit?: number;\n}\n\n/** Global configuration of trace service */\nexport interface SpanLimits {\n /** attributeValueLengthLimit is maximum allowed attribute value size */\n attributeValueLengthLimit?: number;\n /** attributeCountLimit is number of attributes per span */\n attributeCountLimit?: number;\n /** linkCountLimit is number of links per span */\n linkCountLimit?: number;\n /** eventCountLimit is number of message events per span */\n eventCountLimit?: number;\n /** attributePerEventCountLimit is the maximum number of attributes allowed per span event */\n attributePerEventCountLimit?: number;\n /** attributePerLinkCountLimit is the maximum number of attributes allowed per span link */\n attributePerLinkCountLimit?: number;\n}\n\n/** Interface configuration for a buffer. */\nexport interface BufferConfig {\n /** The maximum batch size of every export. It must be smaller or equal to\n * maxQueueSize. The default value is 512. */\n maxExportBatchSize?: number;\n\n /** The delay interval in milliseconds between two consecutive exports.\n * The default value is 5000ms. */\n scheduledDelayMillis?: number;\n\n /** How long the export can run before it is cancelled.\n * The default value is 30000ms */\n exportTimeoutMillis?: number;\n\n /** The maximum queue size. After the size is reached spans are dropped.\n * The default value is 2048. */\n maxQueueSize?: number;\n}\n\n/** Interface configuration for BatchSpanProcessor on browser */\nexport interface BatchSpanProcessorBrowserConfig extends BufferConfig {\n /** Disable flush when a user navigates to a new page, closes the tab or the browser, or,\n * on mobile, switches to a different app. Auto flush is enabled by default. */\n disableAutoFlushOnDocumentHide?: boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** IdGenerator provides an interface for generating Trace Id and Span Id */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './Tracer';\nexport * from './BasicTracerProvider';\nexport * from './platform';\nexport * from './export/ConsoleSpanExporter';\nexport * from './export/InMemorySpanExporter';\nexport * from './export/ReadableSpan';\nexport * from './export/SimpleSpanProcessor';\nexport * from './export/SpanExporter';\nexport * from './export/NoopSpanProcessor';\nexport * from './sampler/AlwaysOffSampler';\nexport * from './sampler/AlwaysOnSampler';\nexport * from './sampler/ParentBasedSampler';\nexport * from './sampler/TraceIdRatioBasedSampler';\nexport * from './Sampler';\nexport * from './Span';\nexport * from './SpanProcessor';\nexport * from './TimedEvent';\nexport * from './types';\nexport * from './IdGenerator';\n","// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0'\n\nconst MAX_LENGTH = 256\nconst MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16\n\n// Max safe length for a build identifier. The max length minus 6 characters for\n// the shortest version with a build 0.0.0+BUILD.\nconst MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6\n\nconst RELEASE_TYPES = [\n 'major',\n 'premajor',\n 'minor',\n 'preminor',\n 'patch',\n 'prepatch',\n 'prerelease',\n]\n\nmodule.exports = {\n MAX_LENGTH,\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_SAFE_INTEGER,\n RELEASE_TYPES,\n SEMVER_SPEC_VERSION,\n FLAG_INCLUDE_PRERELEASE: 0b001,\n FLAG_LOOSE: 0b010,\n}\n","const debug = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {}\n\nmodule.exports = debug\n","const {\n MAX_SAFE_COMPONENT_LENGTH,\n MAX_SAFE_BUILD_LENGTH,\n MAX_LENGTH,\n} = require('./constants')\nconst debug = require('./debug')\nexports = module.exports = {}\n\n// The actual regexps go on exports.re\nconst re = exports.re = []\nconst safeRe = exports.safeRe = []\nconst src = exports.src = []\nconst safeSrc = exports.safeSrc = []\nconst t = exports.t = {}\nlet R = 0\n\nconst LETTERDASHNUMBER = '[a-zA-Z0-9-]'\n\n// Replace some greedy regex tokens to prevent regex dos issues. These regex are\n// used internally via the safeRe object since all inputs in this library get\n// normalized first to trim and collapse all extra whitespace. The original\n// regexes are exported for userland consumption and lower level usage. A\n// future breaking change could export the safer regex only with a note that\n// all input should have extra whitespace removed.\nconst safeRegexReplacements = [\n ['\\\\s', 1],\n ['\\\\d', MAX_LENGTH],\n [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],\n]\n\nconst makeSafeRegex = (value) => {\n for (const [token, max] of safeRegexReplacements) {\n value = value\n .split(`${token}*`).join(`${token}{0,${max}}`)\n .split(`${token}+`).join(`${token}{1,${max}}`)\n }\n return value\n}\n\nconst createToken = (name, value, isGlobal) => {\n const safe = makeSafeRegex(value)\n const index = R++\n debug(name, index, value)\n t[name] = index\n src[index] = value\n safeSrc[index] = safe\n re[index] = new RegExp(value, isGlobal ? 'g' : undefined)\n safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)\n}\n\n// The following Regular Expressions can be used for tokenizing,\n// validating, and parsing SemVer version strings.\n\n// ## Numeric Identifier\n// A single `0`, or a non-zero digit followed by zero or more digits.\n\ncreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*')\ncreateToken('NUMERICIDENTIFIERLOOSE', '\\\\d+')\n\n// ## Non-numeric Identifier\n// Zero or more digits, followed by a letter or hyphen, and then zero or\n// more letters, digits, or hyphens.\n\ncreateToken('NONNUMERICIDENTIFIER', `\\\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)\n\n// ## Main Version\n// Three dot-separated numeric identifiers.\n\ncreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIER]})`)\n\ncreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n `(${src[t.NUMERICIDENTIFIERLOOSE]})`)\n\n// ## Pre-release Version Identifier\n// A numeric identifier, or a non-numeric identifier.\n\ncreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\ncreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n}|${src[t.NONNUMERICIDENTIFIER]})`)\n\n// ## Pre-release Version\n// Hyphen, followed by one or more dot-separated pre-release version\n// identifiers.\n\ncreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`)\n\ncreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)\n\n// ## Build Metadata Identifier\n// Any combination of digits, letters, or hyphens.\n\ncreateToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)\n\n// ## Build Metadata\n// Plus sign, followed by one or more period-separated build metadata\n// identifiers.\n\ncreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`)\n\n// ## Full Version String\n// A main version, followed optionally by a pre-release version and\n// build metadata.\n\n// Note that the only major, minor, patch, and pre-release sections of\n// the version string are capturing groups. The build metadata is not a\n// capturing group, because it should not ever be used in version\n// comparison.\n\ncreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n}${src[t.PRERELEASE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('FULL', `^${src[t.FULLPLAIN]}$`)\n\n// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n// common in the npm registry.\ncreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n}${src[t.PRERELEASELOOSE]}?${\n src[t.BUILD]}?`)\n\ncreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)\n\ncreateToken('GTLT', '((?:<|>)?=?)')\n\n// Something like \"2.*\" or \"1.2.x\".\n// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n// Only the first item is strictly required.\ncreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`)\ncreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`)\n\ncreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n `(?:${src[t.PRERELEASE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n `(?:${src[t.PRERELEASELOOSE]})?${\n src[t.BUILD]}?` +\n `)?)?`)\n\ncreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`)\ncreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Coercion.\n// Extract anything that could conceivably be a part of a valid semver\ncreateToken('COERCEPLAIN', `${'(^|[^\\\\d])' +\n '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)\ncreateToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\\\d])`)\ncreateToken('COERCEFULL', src[t.COERCEPLAIN] +\n `(?:${src[t.PRERELEASE]})?` +\n `(?:${src[t.BUILD]})?` +\n `(?:$|[^\\\\d])`)\ncreateToken('COERCERTL', src[t.COERCE], true)\ncreateToken('COERCERTLFULL', src[t.COERCEFULL], true)\n\n// Tilde ranges.\n// Meaning is \"reasonably at or greater than\"\ncreateToken('LONETILDE', '(?:~>?)')\n\ncreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true)\nexports.tildeTrimReplace = '$1~'\n\ncreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// Caret ranges.\n// Meaning is \"at least and backwards compatible with\"\ncreateToken('LONECARET', '(?:\\\\^)')\n\ncreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true)\nexports.caretTrimReplace = '$1^'\n\ncreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)\ncreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)\n\n// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\ncreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`)\ncreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`)\n\n// An expression to strip any whitespace between the gtlt and the thing\n// it modifies, so that `> 1.2.3` ==> `>1.2.3`\ncreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)\nexports.comparatorTrimReplace = '$1$2$3'\n\n// Something like `1.2.3 - 1.2.4`\n// Note that these all use the loose form, because they'll be\n// checked against either the strict or loose comparator form\n// later.\ncreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAIN]})` +\n `\\\\s*$`)\n\ncreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s+-\\\\s+` +\n `(${src[t.XRANGEPLAINLOOSE]})` +\n `\\\\s*$`)\n\n// Star ranges basically just allow anything at all.\ncreateToken('STAR', '(<|>)?=?\\\\s*\\\\*')\n// >=0.0.0 is like a star\ncreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$')\ncreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$')\n","// parse out just the options we care about\nconst looseOption = Object.freeze({ loose: true })\nconst emptyOpts = Object.freeze({ })\nconst parseOptions = options => {\n if (!options) {\n return emptyOpts\n }\n\n if (typeof options !== 'object') {\n return looseOption\n }\n\n return options\n}\nmodule.exports = parseOptions\n","const numeric = /^[0-9]+$/\nconst compareIdentifiers = (a, b) => {\n const anum = numeric.test(a)\n const bnum = numeric.test(b)\n\n if (anum && bnum) {\n a = +a\n b = +b\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n}\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)\n\nmodule.exports = {\n compareIdentifiers,\n rcompareIdentifiers,\n}\n","const debug = require('../internal/debug')\nconst { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')\nconst { safeRe: re, safeSrc: src, t } = require('../internal/re')\n\nconst parseOptions = require('../internal/parse-options')\nconst { compareIdentifiers } = require('../internal/identifiers')\nclass SemVer {\n constructor (version, options) {\n options = parseOptions(options)\n\n if (version instanceof SemVer) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof version}\".`)\n }\n\n if (version.length > MAX_LENGTH) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH} characters`\n )\n }\n\n debug('SemVer', version, options)\n this.options = options\n this.loose = !!options.loose\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease\n\n const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version\n\n // these are actually numbers\n this.major = +m[1]\n this.minor = +m[2]\n this.patch = +m[3]\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = []\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n })\n }\n\n this.build = m[5] ? m[5].split('.') : []\n this.format()\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other)\n if (!(other instanceof SemVer)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer(other, this.options)\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0\n do {\n const a = this.prerelease[i]\n const b = other.prerelease[i]\n debug('prerelease compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer)) {\n other = new SemVer(other, this.options)\n }\n\n let i = 0\n do {\n const a = this.build[i]\n const b = other.build[i]\n debug('build compare', i, a, b)\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier, identifierBase) {\n if (release.startsWith('pre')) {\n if (!identifier && identifierBase === false) {\n throw new Error('invalid increment argument: identifier is empty')\n }\n // Avoid an invalid semver results\n if (identifier) {\n const r = new RegExp(`^${this.options.loose ? src[t.PRERELEASELOOSE] : src[t.PRERELEASE]}$`)\n const match = `-${identifier}`.match(r)\n if (!match || match[1] !== identifier) {\n throw new Error(`invalid identifier: ${identifier}`)\n }\n }\n }\n\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor = 0\n this.major++\n this.inc('pre', identifier, identifierBase)\n break\n case 'preminor':\n this.prerelease.length = 0\n this.patch = 0\n this.minor++\n this.inc('pre', identifier, identifierBase)\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0\n this.inc('patch', identifier, identifierBase)\n this.inc('pre', identifier, identifierBase)\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier, identifierBase)\n }\n this.inc('pre', identifier, identifierBase)\n break\n case 'release':\n if (this.prerelease.length === 0) {\n throw new Error(`version ${this.raw} is not a prerelease`)\n }\n this.prerelease.length = 0\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++\n }\n this.minor = 0\n this.patch = 0\n this.prerelease = []\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++\n }\n this.patch = 0\n this.prerelease = []\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++\n }\n this.prerelease = []\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre': {\n const base = Number(identifierBase) ? 1 : 0\n\n if (this.prerelease.length === 0) {\n this.prerelease = [base]\n } else {\n let i = this.prerelease.length\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++\n i = -2\n }\n }\n if (i === -1) {\n // didn't increment anything\n if (identifier === this.prerelease.join('.') && identifierBase === false) {\n throw new Error('invalid increment argument: identifier already exists')\n }\n this.prerelease.push(base)\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n let prerelease = [identifier, base]\n if (identifierBase === false) {\n prerelease = [identifier]\n }\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = prerelease\n }\n } else {\n this.prerelease = prerelease\n }\n }\n break\n }\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.raw = this.format()\n if (this.build.length) {\n this.raw += `+${this.build.join('.')}`\n }\n return this\n }\n}\n\nmodule.exports = SemVer\n","const SemVer = require('../classes/semver')\nconst parse = (version, options, throwErrors = false) => {\n if (version instanceof SemVer) {\n return version\n }\n try {\n return new SemVer(version, options)\n } catch (er) {\n if (!throwErrors) {\n return null\n }\n throw er\n }\n}\n\nmodule.exports = parse\n","const parse = require('./parse')\nconst valid = (version, options) => {\n const v = parse(version, options)\n return v ? v.version : null\n}\nmodule.exports = valid\n","const parse = require('./parse')\nconst clean = (version, options) => {\n const s = parse(version.trim().replace(/^[=v]+/, ''), options)\n return s ? s.version : null\n}\nmodule.exports = clean\n","const SemVer = require('../classes/semver')\n\nconst inc = (version, release, options, identifier, identifierBase) => {\n if (typeof (options) === 'string') {\n identifierBase = identifier\n identifier = options\n options = undefined\n }\n\n try {\n return new SemVer(\n version instanceof SemVer ? version.version : version,\n options\n ).inc(release, identifier, identifierBase).version\n } catch (er) {\n return null\n }\n}\nmodule.exports = inc\n","const parse = require('./parse.js')\n\nconst diff = (version1, version2) => {\n const v1 = parse(version1, null, true)\n const v2 = parse(version2, null, true)\n const comparison = v1.compare(v2)\n\n if (comparison === 0) {\n return null\n }\n\n const v1Higher = comparison > 0\n const highVersion = v1Higher ? v1 : v2\n const lowVersion = v1Higher ? v2 : v1\n const highHasPre = !!highVersion.prerelease.length\n const lowHasPre = !!lowVersion.prerelease.length\n\n if (lowHasPre && !highHasPre) {\n // Going from prerelease -> no prerelease requires some special casing\n\n // If the low version has only a major, then it will always be a major\n // Some examples:\n // 1.0.0-1 -> 1.0.0\n // 1.0.0-1 -> 1.1.1\n // 1.0.0-1 -> 2.0.0\n if (!lowVersion.patch && !lowVersion.minor) {\n return 'major'\n }\n\n // If the main part has no difference\n if (lowVersion.compareMain(highVersion) === 0) {\n if (lowVersion.minor && !lowVersion.patch) {\n return 'minor'\n }\n return 'patch'\n }\n }\n\n // add the `pre` prefix if we are going to a prerelease version\n const prefix = highHasPre ? 'pre' : ''\n\n if (v1.major !== v2.major) {\n return prefix + 'major'\n }\n\n if (v1.minor !== v2.minor) {\n return prefix + 'minor'\n }\n\n if (v1.patch !== v2.patch) {\n return prefix + 'patch'\n }\n\n // high and low are preleases\n return 'prerelease'\n}\n\nmodule.exports = diff\n","const SemVer = require('../classes/semver')\nconst major = (a, loose) => new SemVer(a, loose).major\nmodule.exports = major\n","const SemVer = require('../classes/semver')\nconst minor = (a, loose) => new SemVer(a, loose).minor\nmodule.exports = minor\n","const SemVer = require('../classes/semver')\nconst patch = (a, loose) => new SemVer(a, loose).patch\nmodule.exports = patch\n","const parse = require('./parse')\nconst prerelease = (version, options) => {\n const parsed = parse(version, options)\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n}\nmodule.exports = prerelease\n","const SemVer = require('../classes/semver')\nconst compare = (a, b, loose) =>\n new SemVer(a, loose).compare(new SemVer(b, loose))\n\nmodule.exports = compare\n","const compare = require('./compare')\nconst rcompare = (a, b, loose) => compare(b, a, loose)\nmodule.exports = rcompare\n","const compare = require('./compare')\nconst compareLoose = (a, b) => compare(a, b, true)\nmodule.exports = compareLoose\n","const SemVer = require('../classes/semver')\nconst compareBuild = (a, b, loose) => {\n const versionA = new SemVer(a, loose)\n const versionB = new SemVer(b, loose)\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n}\nmodule.exports = compareBuild\n","const compareBuild = require('./compare-build')\nconst sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))\nmodule.exports = sort\n","const compareBuild = require('./compare-build')\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))\nmodule.exports = rsort\n","const compare = require('./compare')\nconst gt = (a, b, loose) => compare(a, b, loose) > 0\nmodule.exports = gt\n","const compare = require('./compare')\nconst lt = (a, b, loose) => compare(a, b, loose) < 0\nmodule.exports = lt\n","const compare = require('./compare')\nconst eq = (a, b, loose) => compare(a, b, loose) === 0\nmodule.exports = eq\n","const compare = require('./compare')\nconst neq = (a, b, loose) => compare(a, b, loose) !== 0\nmodule.exports = neq\n","const compare = require('./compare')\nconst gte = (a, b, loose) => compare(a, b, loose) >= 0\nmodule.exports = gte\n","const compare = require('./compare')\nconst lte = (a, b, loose) => compare(a, b, loose) <= 0\nmodule.exports = lte\n","const eq = require('./eq')\nconst neq = require('./neq')\nconst gt = require('./gt')\nconst gte = require('./gte')\nconst lt = require('./lt')\nconst lte = require('./lte')\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version\n }\n if (typeof b === 'object') {\n b = b.version\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt(a, b, loose)\n\n case '>=':\n return gte(a, b, loose)\n\n case '<':\n return lt(a, b, loose)\n\n case '<=':\n return lte(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n}\nmodule.exports = cmp\n","const SemVer = require('../classes/semver')\nconst parse = require('./parse')\nconst { safeRe: re, t } = require('../internal/re')\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version)\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {}\n\n let match = null\n if (!options.rtl) {\n match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]\n let next\n while ((next = coerceRtlRegex.exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next\n }\n coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length\n }\n // leave it in a clean state\n coerceRtlRegex.lastIndex = -1\n }\n\n if (match === null) {\n return null\n }\n\n const major = match[2]\n const minor = match[3] || '0'\n const patch = match[4] || '0'\n const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''\n const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''\n\n return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)\n}\nmodule.exports = coerce\n","class LRUCache {\n constructor () {\n this.max = 1000\n this.map = new Map()\n }\n\n get (key) {\n const value = this.map.get(key)\n if (value === undefined) {\n return undefined\n } else {\n // Remove the key from the map and add it to the end\n this.map.delete(key)\n this.map.set(key, value)\n return value\n }\n }\n\n delete (key) {\n return this.map.delete(key)\n }\n\n set (key, value) {\n const deleted = this.delete(key)\n\n if (!deleted && value !== undefined) {\n // If cache is full, delete the least recently used item\n if (this.map.size >= this.max) {\n const firstKey = this.map.keys().next().value\n this.delete(firstKey)\n }\n\n this.map.set(key, value)\n }\n\n return this\n }\n}\n\nmodule.exports = LRUCache\n","const SPACE_CHARACTERS = /\\s+/g\n\n// hoisted class for cyclic dependency\nclass Range {\n constructor (range, options) {\n options = parseOptions(options)\n\n if (range instanceof Range) {\n if (\n range.loose === !!options.loose &&\n range.includePrerelease === !!options.includePrerelease\n ) {\n return range\n } else {\n return new Range(range.raw, options)\n }\n }\n\n if (range instanceof Comparator) {\n // just put it in the set and return\n this.raw = range.value\n this.set = [[range]]\n this.formatted = undefined\n return this\n }\n\n this.options = options\n this.loose = !!options.loose\n this.includePrerelease = !!options.includePrerelease\n\n // First reduce all whitespace as much as possible so we do not have to rely\n // on potentially slow regexes like \\s*. This is then stored and used for\n // future error messages as well.\n this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')\n\n // First, split on ||\n this.set = this.raw\n .split('||')\n // map the range to a 2d array of comparators\n .map(r => this.parseRange(r.trim()))\n // throw out any comparator lists that are empty\n // this generally means that it was not a valid range, which is allowed\n // in loose mode, but will still throw if the WHOLE range is invalid.\n .filter(c => c.length)\n\n if (!this.set.length) {\n throw new TypeError(`Invalid SemVer Range: ${this.raw}`)\n }\n\n // if we have any that are not the null set, throw out null sets.\n if (this.set.length > 1) {\n // keep the first one, in case they're all null sets\n const first = this.set[0]\n this.set = this.set.filter(c => !isNullSet(c[0]))\n if (this.set.length === 0) {\n this.set = [first]\n } else if (this.set.length > 1) {\n // if we have any that are *, then the range is just *\n for (const c of this.set) {\n if (c.length === 1 && isAny(c[0])) {\n this.set = [c]\n break\n }\n }\n }\n }\n\n this.formatted = undefined\n }\n\n get range () {\n if (this.formatted === undefined) {\n this.formatted = ''\n for (let i = 0; i < this.set.length; i++) {\n if (i > 0) {\n this.formatted += '||'\n }\n const comps = this.set[i]\n for (let k = 0; k < comps.length; k++) {\n if (k > 0) {\n this.formatted += ' '\n }\n this.formatted += comps[k].toString().trim()\n }\n }\n }\n return this.formatted\n }\n\n format () {\n return this.range\n }\n\n toString () {\n return this.range\n }\n\n parseRange (range) {\n // memoize range parsing for performance.\n // this is a very hot path, and fully deterministic.\n const memoOpts =\n (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |\n (this.options.loose && FLAG_LOOSE)\n const memoKey = memoOpts + ':' + range\n const cached = cache.get(memoKey)\n if (cached) {\n return cached\n }\n\n const loose = this.options.loose\n // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]\n range = range.replace(hr, hyphenReplace(this.options.includePrerelease))\n debug('hyphen replace', range)\n\n // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)\n debug('comparator trim', range)\n\n // `~ 1.2.3` => `~1.2.3`\n range = range.replace(re[t.TILDETRIM], tildeTrimReplace)\n debug('tilde trim', range)\n\n // `^ 1.2.3` => `^1.2.3`\n range = range.replace(re[t.CARETTRIM], caretTrimReplace)\n debug('caret trim', range)\n\n // At this point, the range is completely trimmed and\n // ready to be split into comparators.\n\n let rangeList = range\n .split(' ')\n .map(comp => parseComparator(comp, this.options))\n .join(' ')\n .split(/\\s+/)\n // >=0.0.0 is equivalent to *\n .map(comp => replaceGTE0(comp, this.options))\n\n if (loose) {\n // in loose mode, throw out any that are not valid comparators\n rangeList = rangeList.filter(comp => {\n debug('loose invalid filter', comp, this.options)\n return !!comp.match(re[t.COMPARATORLOOSE])\n })\n }\n debug('range list', rangeList)\n\n // if any comparators are the null set, then replace with JUST null set\n // if more than one comparator, remove any * comparators\n // also, don't include the same comparator more than once\n const rangeMap = new Map()\n const comparators = rangeList.map(comp => new Comparator(comp, this.options))\n for (const comp of comparators) {\n if (isNullSet(comp)) {\n return [comp]\n }\n rangeMap.set(comp.value, comp)\n }\n if (rangeMap.size > 1 && rangeMap.has('')) {\n rangeMap.delete('')\n }\n\n const result = [...rangeMap.values()]\n cache.set(memoKey, result)\n return result\n }\n\n intersects (range, options) {\n if (!(range instanceof Range)) {\n throw new TypeError('a Range is required')\n }\n\n return this.set.some((thisComparators) => {\n return (\n isSatisfiable(thisComparators, options) &&\n range.set.some((rangeComparators) => {\n return (\n isSatisfiable(rangeComparators, options) &&\n thisComparators.every((thisComparator) => {\n return rangeComparators.every((rangeComparator) => {\n return thisComparator.intersects(rangeComparator, options)\n })\n })\n )\n })\n )\n })\n }\n\n // if ANY of the sets match ALL of its comparators, then pass\n test (version) {\n if (!version) {\n return false\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n for (let i = 0; i < this.set.length; i++) {\n if (testSet(this.set[i], version, this.options)) {\n return true\n }\n }\n return false\n }\n}\n\nmodule.exports = Range\n\nconst LRU = require('../internal/lrucache')\nconst cache = new LRU()\n\nconst parseOptions = require('../internal/parse-options')\nconst Comparator = require('./comparator')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst {\n safeRe: re,\n t,\n comparatorTrimReplace,\n tildeTrimReplace,\n caretTrimReplace,\n} = require('../internal/re')\nconst { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')\n\nconst isNullSet = c => c.value === '<0.0.0-0'\nconst isAny = c => c.value === ''\n\n// take a set of comparators and determine whether there\n// exists a version which can satisfy it\nconst isSatisfiable = (comparators, options) => {\n let result = true\n const remainingComparators = comparators.slice()\n let testComparator = remainingComparators.pop()\n\n while (result && remainingComparators.length) {\n result = remainingComparators.every((otherComparator) => {\n return testComparator.intersects(otherComparator, options)\n })\n\n testComparator = remainingComparators.pop()\n }\n\n return result\n}\n\n// comprised of xranges, tildes, stars, and gtlt's at this point.\n// already replaced the hyphen ranges\n// turn into a set of JUST comparators.\nconst parseComparator = (comp, options) => {\n debug('comp', comp, options)\n comp = replaceCarets(comp, options)\n debug('caret', comp)\n comp = replaceTildes(comp, options)\n debug('tildes', comp)\n comp = replaceXRanges(comp, options)\n debug('xrange', comp)\n comp = replaceStars(comp, options)\n debug('stars', comp)\n return comp\n}\n\nconst isX = id => !id || id.toLowerCase() === 'x' || id === '*'\n\n// ~, ~> --> * (any, kinda silly)\n// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n// ~0.0.1 --> >=0.0.1 <0.1.0-0\nconst replaceTildes = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceTilde(c, options))\n .join(' ')\n}\n\nconst replaceTilde = (comp, options) => {\n const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('tilde', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0 <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n // ~1.2 == >=1.2.0 <1.3.0-0\n ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`\n } else if (pr) {\n debug('replaceTilde pr', pr)\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n } else {\n // ~1.2.3 == >=1.2.3 <1.3.0-0\n ret = `>=${M}.${m}.${p\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('tilde return', ret)\n return ret\n })\n}\n\n// ^ --> * (any, kinda silly)\n// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n// ^1.2.3 --> >=1.2.3 <2.0.0-0\n// ^1.2.0 --> >=1.2.0 <2.0.0-0\n// ^0.0.1 --> >=0.0.1 <0.0.2-0\n// ^0.1.0 --> >=0.1.0 <0.2.0-0\nconst replaceCarets = (comp, options) => {\n return comp\n .trim()\n .split(/\\s+/)\n .map((c) => replaceCaret(c, options))\n .join(' ')\n}\n\nconst replaceCaret = (comp, options) => {\n debug('caret', comp, options)\n const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]\n const z = options.includePrerelease ? '-0' : ''\n return comp.replace(r, (_, M, m, p, pr) => {\n debug('caret', comp, _, M, m, p, pr)\n let ret\n\n if (isX(M)) {\n ret = ''\n } else if (isX(m)) {\n ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`\n } else if (isX(p)) {\n if (M === '0') {\n ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`\n } else {\n ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`\n }\n } else if (pr) {\n debug('replaceCaret pr', pr)\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p}-${pr\n } <${+M + 1}.0.0-0`\n }\n } else {\n debug('no pr')\n if (M === '0') {\n if (m === '0') {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${m}.${+p + 1}-0`\n } else {\n ret = `>=${M}.${m}.${p\n }${z} <${M}.${+m + 1}.0-0`\n }\n } else {\n ret = `>=${M}.${m}.${p\n } <${+M + 1}.0.0-0`\n }\n }\n\n debug('caret return', ret)\n return ret\n })\n}\n\nconst replaceXRanges = (comp, options) => {\n debug('replaceXRanges', comp, options)\n return comp\n .split(/\\s+/)\n .map((c) => replaceXRange(c, options))\n .join(' ')\n}\n\nconst replaceXRange = (comp, options) => {\n comp = comp.trim()\n const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]\n return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n debug('xRange', comp, ret, gtlt, M, m, p, pr)\n const xM = isX(M)\n const xm = xM || isX(m)\n const xp = xm || isX(p)\n const anyX = xp\n\n if (gtlt === '=' && anyX) {\n gtlt = ''\n }\n\n // if we're including prereleases in the match, then we need\n // to fix this to -0, the lowest possible prerelease value\n pr = options.includePrerelease ? '-0' : ''\n\n if (xM) {\n if (gtlt === '>' || gtlt === '<') {\n // nothing is allowed\n ret = '<0.0.0-0'\n } else {\n // nothing is forbidden\n ret = '*'\n }\n } else if (gtlt && anyX) {\n // we know patch is an x, because we have any x at all.\n // replace X with 0\n if (xm) {\n m = 0\n }\n p = 0\n\n if (gtlt === '>') {\n // >1 => >=2.0.0\n // >1.2 => >=1.3.0\n gtlt = '>='\n if (xm) {\n M = +M + 1\n m = 0\n p = 0\n } else {\n m = +m + 1\n p = 0\n }\n } else if (gtlt === '<=') {\n // <=0.7.x is actually <0.8.0, since any 0.7.x should\n // pass. Similarly, <=7.x is actually <8.0.0, etc.\n gtlt = '<'\n if (xm) {\n M = +M + 1\n } else {\n m = +m + 1\n }\n }\n\n if (gtlt === '<') {\n pr = '-0'\n }\n\n ret = `${gtlt + M}.${m}.${p}${pr}`\n } else if (xm) {\n ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`\n } else if (xp) {\n ret = `>=${M}.${m}.0${pr\n } <${M}.${+m + 1}.0-0`\n }\n\n debug('xRange return', ret)\n\n return ret\n })\n}\n\n// Because * is AND-ed with everything else in the comparator,\n// and '' means \"any version\", just remove the *s entirely.\nconst replaceStars = (comp, options) => {\n debug('replaceStars', comp, options)\n // Looseness is ignored here. star is always as loose as it gets!\n return comp\n .trim()\n .replace(re[t.STAR], '')\n}\n\nconst replaceGTE0 = (comp, options) => {\n debug('replaceGTE0', comp, options)\n return comp\n .trim()\n .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n}\n\n// This function is passed to string.replace(re[t.HYPHENRANGE])\n// M, m, patch, prerelease, build\n// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n// TODO build?\nconst hyphenReplace = incPr => ($0,\n from, fM, fm, fp, fpr, fb,\n to, tM, tm, tp, tpr) => {\n if (isX(fM)) {\n from = ''\n } else if (isX(fm)) {\n from = `>=${fM}.0.0${incPr ? '-0' : ''}`\n } else if (isX(fp)) {\n from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`\n } else if (fpr) {\n from = `>=${from}`\n } else {\n from = `>=${from}${incPr ? '-0' : ''}`\n }\n\n if (isX(tM)) {\n to = ''\n } else if (isX(tm)) {\n to = `<${+tM + 1}.0.0-0`\n } else if (isX(tp)) {\n to = `<${tM}.${+tm + 1}.0-0`\n } else if (tpr) {\n to = `<=${tM}.${tm}.${tp}-${tpr}`\n } else if (incPr) {\n to = `<${tM}.${tm}.${+tp + 1}-0`\n } else {\n to = `<=${to}`\n }\n\n return `${from} ${to}`.trim()\n}\n\nconst testSet = (set, version, options) => {\n for (let i = 0; i < set.length; i++) {\n if (!set[i].test(version)) {\n return false\n }\n }\n\n if (version.prerelease.length && !options.includePrerelease) {\n // Find the set of versions that are allowed to have prereleases\n // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n // That should allow `1.2.3-pr.2` to pass.\n // However, `1.2.4-alpha.notready` should NOT be allowed,\n // even though it's within the range set by the comparators.\n for (let i = 0; i < set.length; i++) {\n debug(set[i].semver)\n if (set[i].semver === Comparator.ANY) {\n continue\n }\n\n if (set[i].semver.prerelease.length > 0) {\n const allowed = set[i].semver\n if (allowed.major === version.major &&\n allowed.minor === version.minor &&\n allowed.patch === version.patch) {\n return true\n }\n }\n }\n\n // Version has a -pre, but it's not one of the ones we like.\n return false\n }\n\n return true\n}\n","const ANY = Symbol('SemVer ANY')\n// hoisted class for cyclic dependency\nclass Comparator {\n static get ANY () {\n return ANY\n }\n\n constructor (comp, options) {\n options = parseOptions(options)\n\n if (comp instanceof Comparator) {\n if (comp.loose === !!options.loose) {\n return comp\n } else {\n comp = comp.value\n }\n }\n\n comp = comp.trim().split(/\\s+/).join(' ')\n debug('comparator', comp, options)\n this.options = options\n this.loose = !!options.loose\n this.parse(comp)\n\n if (this.semver === ANY) {\n this.value = ''\n } else {\n this.value = this.operator + this.semver.version\n }\n\n debug('comp', this)\n }\n\n parse (comp) {\n const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]\n const m = comp.match(r)\n\n if (!m) {\n throw new TypeError(`Invalid comparator: ${comp}`)\n }\n\n this.operator = m[1] !== undefined ? m[1] : ''\n if (this.operator === '=') {\n this.operator = ''\n }\n\n // if it literally is just '>' or '' then allow anything.\n if (!m[2]) {\n this.semver = ANY\n } else {\n this.semver = new SemVer(m[2], this.options.loose)\n }\n }\n\n toString () {\n return this.value\n }\n\n test (version) {\n debug('Comparator.test', version, this.options.loose)\n\n if (this.semver === ANY || version === ANY) {\n return true\n }\n\n if (typeof version === 'string') {\n try {\n version = new SemVer(version, this.options)\n } catch (er) {\n return false\n }\n }\n\n return cmp(version, this.operator, this.semver, this.options)\n }\n\n intersects (comp, options) {\n if (!(comp instanceof Comparator)) {\n throw new TypeError('a Comparator is required')\n }\n\n if (this.operator === '') {\n if (this.value === '') {\n return true\n }\n return new Range(comp.value, options).test(this.value)\n } else if (comp.operator === '') {\n if (comp.value === '') {\n return true\n }\n return new Range(this.value, options).test(comp.semver)\n }\n\n options = parseOptions(options)\n\n // Special cases where nothing can possibly be lower\n if (options.includePrerelease &&\n (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {\n return false\n }\n if (!options.includePrerelease &&\n (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {\n return false\n }\n\n // Same direction increasing (> or >=)\n if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {\n return true\n }\n // Same direction decreasing (< or <=)\n if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {\n return true\n }\n // same SemVer and both sides are inclusive (<= or >=)\n if (\n (this.semver.version === comp.semver.version) &&\n this.operator.includes('=') && comp.operator.includes('=')) {\n return true\n }\n // opposite directions less than\n if (cmp(this.semver, '<', comp.semver, options) &&\n this.operator.startsWith('>') && comp.operator.startsWith('<')) {\n return true\n }\n // opposite directions greater than\n if (cmp(this.semver, '>', comp.semver, options) &&\n this.operator.startsWith('<') && comp.operator.startsWith('>')) {\n return true\n }\n return false\n }\n}\n\nmodule.exports = Comparator\n\nconst parseOptions = require('../internal/parse-options')\nconst { safeRe: re, t } = require('../internal/re')\nconst cmp = require('../functions/cmp')\nconst debug = require('../internal/debug')\nconst SemVer = require('./semver')\nconst Range = require('./range')\n","const Range = require('../classes/range')\nconst satisfies = (version, range, options) => {\n try {\n range = new Range(range, options)\n } catch (er) {\n return false\n }\n return range.test(version)\n}\nmodule.exports = satisfies\n","const Range = require('../classes/range')\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '))\n\nmodule.exports = toComparators\n","const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null\n let maxSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v\n maxSV = new SemVer(max, options)\n }\n }\n })\n return max\n}\nmodule.exports = maxSatisfying\n","const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst minSatisfying = (versions, range, options) => {\n let min = null\n let minSV = null\n let rangeObj = null\n try {\n rangeObj = new Range(range, options)\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v\n minSV = new SemVer(min, options)\n }\n }\n })\n return min\n}\nmodule.exports = minSatisfying\n","const SemVer = require('../classes/semver')\nconst Range = require('../classes/range')\nconst gt = require('../functions/gt')\n\nconst minVersion = (range, loose) => {\n range = new Range(range, loose)\n\n let minver = new SemVer('0.0.0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer('0.0.0-0')\n if (range.test(minver)) {\n return minver\n }\n\n minver = null\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let setMin = null\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer(comparator.semver.version)\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++\n } else {\n compver.prerelease.push(0)\n }\n compver.raw = compver.format()\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt(compver, setMin)) {\n setMin = compver\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n })\n if (setMin && (!minver || gt(minver, setMin))) {\n minver = setMin\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n}\nmodule.exports = minVersion\n","const Range = require('../classes/range')\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range(range, options).range || '*'\n } catch (er) {\n return null\n }\n}\nmodule.exports = validRange\n","const SemVer = require('../classes/semver')\nconst Comparator = require('../classes/comparator')\nconst { ANY } = Comparator\nconst Range = require('../classes/range')\nconst satisfies = require('../functions/satisfies')\nconst gt = require('../functions/gt')\nconst lt = require('../functions/lt')\nconst lte = require('../functions/lte')\nconst gte = require('../functions/gte')\n\nconst outside = (version, range, hilo, options) => {\n version = new SemVer(version, options)\n range = new Range(range, options)\n\n let gtfn, ltefn, ltfn, comp, ecomp\n switch (hilo) {\n case '>':\n gtfn = gt\n ltefn = lte\n ltfn = lt\n comp = '>'\n ecomp = '>='\n break\n case '<':\n gtfn = lt\n ltefn = gte\n ltfn = gt\n comp = '<'\n ecomp = '<='\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i]\n\n let high = null\n let low = null\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY) {\n comparator = new Comparator('>=0.0.0')\n }\n high = high || comparator\n low = low || comparator\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator\n }\n })\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n}\n\nmodule.exports = outside\n","// Determine if version is greater than all the versions possible in the range.\nconst outside = require('./outside')\nconst gtr = (version, range, options) => outside(version, range, '>', options)\nmodule.exports = gtr\n","const outside = require('./outside')\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options)\nmodule.exports = ltr\n","const Range = require('../classes/range')\nconst intersects = (r1, r2, options) => {\n r1 = new Range(r1, options)\n r2 = new Range(r2, options)\n return r1.intersects(r2, options)\n}\nmodule.exports = intersects\n","// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\nmodule.exports = (versions, range, options) => {\n const set = []\n let first = null\n let prev = null\n const v = versions.sort((a, b) => compare(a, b, options))\n for (const version of v) {\n const included = satisfies(version, range, options)\n if (included) {\n prev = version\n if (!first) {\n first = version\n }\n } else {\n if (prev) {\n set.push([first, prev])\n }\n prev = null\n first = null\n }\n }\n if (first) {\n set.push([first, null])\n }\n\n const ranges = []\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min)\n } else if (!max && min === v[0]) {\n ranges.push('*')\n } else if (!max) {\n ranges.push(`>=${min}`)\n } else if (min === v[0]) {\n ranges.push(`<=${max}`)\n } else {\n ranges.push(`${min} - ${max}`)\n }\n }\n const simplified = ranges.join(' || ')\n const original = typeof range.raw === 'string' ? range.raw : String(range)\n return simplified.length < original.length ? simplified : range\n}\n","const Range = require('../classes/range.js')\nconst Comparator = require('../classes/comparator.js')\nconst { ANY } = Comparator\nconst satisfies = require('../functions/satisfies.js')\nconst compare = require('../functions/compare.js')\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options)\n dom = new Range(dom, options)\n let sawNonNull = false\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options)\n sawNonNull = sawNonNull || isSub !== null\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n}\n\nconst minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]\nconst minimumVersion = [new Comparator('>=0.0.0')]\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = minimumVersionWithPreRelease\n } else {\n sub = minimumVersion\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = minimumVersion\n }\n }\n\n const eqSet = new Set()\n let gt, lt\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options)\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options)\n } else {\n eqSet.add(c.semver)\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options)\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower\n let hasDomLT, hasDomGT\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options)\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options)\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n}\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n}\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options)\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n}\n\nmodule.exports = subset\n","// just pre-load all the stuff that index.js lazily exports\nconst internalRe = require('./internal/re')\nconst constants = require('./internal/constants')\nconst SemVer = require('./classes/semver')\nconst identifiers = require('./internal/identifiers')\nconst parse = require('./functions/parse')\nconst valid = require('./functions/valid')\nconst clean = require('./functions/clean')\nconst inc = require('./functions/inc')\nconst diff = require('./functions/diff')\nconst major = require('./functions/major')\nconst minor = require('./functions/minor')\nconst patch = require('./functions/patch')\nconst prerelease = require('./functions/prerelease')\nconst compare = require('./functions/compare')\nconst rcompare = require('./functions/rcompare')\nconst compareLoose = require('./functions/compare-loose')\nconst compareBuild = require('./functions/compare-build')\nconst sort = require('./functions/sort')\nconst rsort = require('./functions/rsort')\nconst gt = require('./functions/gt')\nconst lt = require('./functions/lt')\nconst eq = require('./functions/eq')\nconst neq = require('./functions/neq')\nconst gte = require('./functions/gte')\nconst lte = require('./functions/lte')\nconst cmp = require('./functions/cmp')\nconst coerce = require('./functions/coerce')\nconst Comparator = require('./classes/comparator')\nconst Range = require('./classes/range')\nconst satisfies = require('./functions/satisfies')\nconst toComparators = require('./ranges/to-comparators')\nconst maxSatisfying = require('./ranges/max-satisfying')\nconst minSatisfying = require('./ranges/min-satisfying')\nconst minVersion = require('./ranges/min-version')\nconst validRange = require('./ranges/valid')\nconst outside = require('./ranges/outside')\nconst gtr = require('./ranges/gtr')\nconst ltr = require('./ranges/ltr')\nconst intersects = require('./ranges/intersects')\nconst simplifyRange = require('./ranges/simplify')\nconst subset = require('./ranges/subset')\nmodule.exports = {\n parse,\n valid,\n clean,\n inc,\n diff,\n major,\n minor,\n patch,\n prerelease,\n compare,\n rcompare,\n compareLoose,\n compareBuild,\n sort,\n rsort,\n gt,\n lt,\n eq,\n neq,\n gte,\n lte,\n cmp,\n coerce,\n Comparator,\n Range,\n satisfies,\n toComparators,\n maxSatisfying,\n minSatisfying,\n minVersion,\n validRange,\n outside,\n gtr,\n ltr,\n intersects,\n simplifyRange,\n subset,\n SemVer,\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n RELEASE_TYPES: constants.RELEASE_TYPES,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const BAGGAGE_KEY_PAIR_SEPARATOR = '=';\nexport const BAGGAGE_PROPERTIES_SEPARATOR = ';';\nexport const BAGGAGE_ITEMS_SEPARATOR = ',';\n\n// Name of the http header used to propagate the baggage\nexport const BAGGAGE_HEADER = 'baggage';\n// Maximum number of name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_NAME_VALUE_PAIRS = 180;\n// Maximum number of bytes per a single name-value pair allowed by w3c spec\nexport const BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096;\n// Maximum total length of all name-value pairs allowed by w3c spec\nexport const BAGGAGE_MAX_TOTAL_LENGTH = 8192;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n Baggage,\n BaggageEntryMetadata,\n baggageEntryMetadataFromString,\n} from '@opentelemetry/api';\nimport {\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_PROPERTIES_SEPARATOR,\n BAGGAGE_KEY_PAIR_SEPARATOR,\n BAGGAGE_MAX_TOTAL_LENGTH,\n} from './constants';\n\ntype ParsedBaggageKeyValue = {\n key: string;\n value: string;\n metadata: BaggageEntryMetadata | undefined;\n};\n\nexport function serializeKeyPairs(keyPairs: string[]): string {\n return keyPairs.reduce((hValue: string, current: string) => {\n const value = `${hValue}${\n hValue !== '' ? BAGGAGE_ITEMS_SEPARATOR : ''\n }${current}`;\n return value.length > BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value;\n }, '');\n}\n\nexport function getKeyPairs(baggage: Baggage): string[] {\n return baggage.getAllEntries().map(([key, value]) => {\n let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`;\n\n // include opaque metadata if provided\n // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation\n if (value.metadata !== undefined) {\n entry += BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString();\n }\n\n return entry;\n });\n}\n\nexport function parsePairKeyValue(\n entry: string\n): ParsedBaggageKeyValue | undefined {\n const valueProps = entry.split(BAGGAGE_PROPERTIES_SEPARATOR);\n if (valueProps.length <= 0) return;\n const keyPairPart = valueProps.shift();\n if (!keyPairPart) return;\n const separatorIndex = keyPairPart.indexOf(BAGGAGE_KEY_PAIR_SEPARATOR);\n if (separatorIndex <= 0) return;\n const key = decodeURIComponent(\n keyPairPart.substring(0, separatorIndex).trim()\n );\n const value = decodeURIComponent(\n keyPairPart.substring(separatorIndex + 1).trim()\n );\n let metadata;\n if (valueProps.length > 0) {\n metadata = baggageEntryMetadataFromString(\n valueProps.join(BAGGAGE_PROPERTIES_SEPARATOR)\n );\n }\n return { key, value, metadata };\n}\n\n/**\n * Parse a string serialized in the baggage HTTP Format (without metadata):\n * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md\n */\nexport function parseKeyPairsIntoRecord(\n value?: string\n): Record<string, string> {\n if (typeof value !== 'string' || value.length === 0) return {};\n return value\n .split(BAGGAGE_ITEMS_SEPARATOR)\n .map(entry => {\n return parsePairKeyValue(entry);\n })\n .filter(keyPair => keyPair !== undefined && keyPair.value.length > 0)\n .reduce<Record<string, string>>((headers, keyPair) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n headers[keyPair!.key] = keyPair!.value;\n return headers;\n }, {});\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BaggageEntry,\n Context,\n propagation,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n} from '@opentelemetry/api';\n\nimport { isTracingSuppressed } from '../../trace/suppress-tracing';\nimport {\n BAGGAGE_HEADER,\n BAGGAGE_ITEMS_SEPARATOR,\n BAGGAGE_MAX_NAME_VALUE_PAIRS,\n BAGGAGE_MAX_PER_NAME_VALUE_PAIRS,\n} from '../constants';\nimport { getKeyPairs, parsePairKeyValue, serializeKeyPairs } from '../utils';\n\n/**\n * Propagates {@link Baggage} through Context format propagation.\n *\n * Based on the Baggage specification:\n * https://w3c.github.io/baggage/\n */\nexport class W3CBaggagePropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const baggage = propagation.getBaggage(context);\n if (!baggage || isTracingSuppressed(context)) return;\n const keyPairs = getKeyPairs(baggage)\n .filter((pair: string) => {\n return pair.length <= BAGGAGE_MAX_PER_NAME_VALUE_PAIRS;\n })\n .slice(0, BAGGAGE_MAX_NAME_VALUE_PAIRS);\n const headerValue = serializeKeyPairs(keyPairs);\n if (headerValue.length > 0) {\n setter.set(carrier, BAGGAGE_HEADER, headerValue);\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const headerValue = getter.get(carrier, BAGGAGE_HEADER);\n const baggageString = Array.isArray(headerValue)\n ? headerValue.join(BAGGAGE_ITEMS_SEPARATOR)\n : headerValue;\n if (!baggageString) return context;\n const baggage: Record<string, BaggageEntry> = {};\n if (baggageString.length === 0) {\n return context;\n }\n const pairs = baggageString.split(BAGGAGE_ITEMS_SEPARATOR);\n pairs.forEach(entry => {\n const keyPair = parsePairKeyValue(entry);\n if (keyPair) {\n const baggageEntry: BaggageEntry = { value: keyPair.value };\n if (keyPair.metadata) {\n baggageEntry.metadata = keyPair.metadata;\n }\n baggage[keyPair.key] = baggageEntry;\n }\n });\n if (Object.entries(baggage).length === 0) {\n return context;\n }\n return propagation.setBaggage(context, propagation.createBaggage(baggage));\n }\n\n fields(): string[] {\n return [BAGGAGE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Clock {\n /**\n * Return the current time in milliseconds from some epoch such as the Unix epoch or process start\n */\n now(): number;\n}\n\n/**\n * A utility for returning wall times anchored to a given point in time. Wall time measurements will\n * not be taken from the system, but instead are computed by adding a monotonic clock time\n * to the anchor point.\n *\n * This is needed because the system time can change and result in unexpected situations like\n * spans ending before they are started. Creating an anchored clock for each local root span\n * ensures that span timings and durations are accurate while preventing span times from drifting\n * too far from the system clock.\n *\n * Only creating an anchored clock once per local trace ensures span times are correct relative\n * to each other. For example, a child span will never have a start time before its parent even\n * if the system clock is corrected during the local trace.\n *\n * Heavily inspired by the OTel Java anchored clock\n * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java\n */\nexport class AnchoredClock implements Clock {\n private _monotonicClock: Clock;\n private _epochMillis: number;\n private _performanceMillis: number;\n\n /**\n * Create a new AnchoredClock anchored to the current time returned by systemClock.\n *\n * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date\n * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance\n */\n public constructor(systemClock: Clock, monotonicClock: Clock) {\n this._monotonicClock = monotonicClock;\n this._epochMillis = systemClock.now();\n this._performanceMillis = monotonicClock.now();\n }\n\n /**\n * Returns the current time by adding the number of milliseconds since the\n * AnchoredClock was created to the creation epoch time\n */\n public now(): number {\n const delta = this._monotonicClock.now() - this._performanceMillis;\n return this._epochMillis + delta;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, SpanAttributeValue, SpanAttributes } from '@opentelemetry/api';\n\nexport function sanitizeAttributes(attributes: unknown): SpanAttributes {\n const out: SpanAttributes = {};\n\n if (typeof attributes !== 'object' || attributes == null) {\n return out;\n }\n\n for (const [key, val] of Object.entries(attributes)) {\n if (!isAttributeKey(key)) {\n diag.warn(`Invalid attribute key: ${key}`);\n continue;\n }\n if (!isAttributeValue(val)) {\n diag.warn(`Invalid attribute value set for key: ${key}`);\n continue;\n }\n if (Array.isArray(val)) {\n out[key] = val.slice();\n } else {\n out[key] = val;\n }\n }\n\n return out;\n}\n\nexport function isAttributeKey(key: unknown): key is string {\n return typeof key === 'string' && key.length > 0;\n}\n\nexport function isAttributeValue(val: unknown): val is SpanAttributeValue {\n if (val == null) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return isHomogeneousAttributeValueArray(val);\n }\n\n return isValidPrimitiveAttributeValue(val);\n}\n\nfunction isHomogeneousAttributeValueArray(arr: unknown[]): boolean {\n let type: string | undefined;\n\n for (const element of arr) {\n // null/undefined elements are allowed\n if (element == null) continue;\n\n if (!type) {\n if (isValidPrimitiveAttributeValue(element)) {\n type = typeof element;\n continue;\n }\n // encountered an invalid primitive\n return false;\n }\n\n if (typeof element === type) {\n continue;\n }\n\n return false;\n }\n\n return true;\n}\n\nfunction isValidPrimitiveAttributeValue(val: unknown): boolean {\n switch (typeof val) {\n case 'number':\n case 'boolean':\n case 'string':\n return true;\n }\n\n return false;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag, Exception } from '@opentelemetry/api';\nimport { ErrorHandler } from './types';\n\n/**\n * Returns a function that logs an error using the provided logger, or a\n * console logger if one was not provided.\n */\nexport function loggingErrorHandler(): ErrorHandler {\n return (ex: Exception) => {\n diag.error(stringifyException(ex));\n };\n}\n\n/**\n * Converts an exception into a string representation\n * @param {Exception} ex\n */\nfunction stringifyException(ex: Exception | string): string {\n if (typeof ex === 'string') {\n return ex;\n } else {\n return JSON.stringify(flattenException(ex));\n }\n}\n\n/**\n * Flattens an exception into key-value pairs by traversing the prototype chain\n * and coercing values to strings. Duplicate properties will not be overwritten;\n * the first insert wins.\n */\nfunction flattenException(ex: Exception): Record<string, string> {\n const result = {} as Record<string, string>;\n let current = ex;\n\n while (current !== null) {\n Object.getOwnPropertyNames(current).forEach(propertyName => {\n if (result[propertyName]) return;\n const value = current[propertyName as keyof typeof current];\n if (value) {\n result[propertyName] = String(value);\n }\n });\n current = Object.getPrototypeOf(current);\n }\n\n return result;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\nimport { loggingErrorHandler } from './logging-error-handler';\nimport { ErrorHandler } from './types';\n\n/** The global error handler delegate */\nlet delegateHandler = loggingErrorHandler();\n\n/**\n * Set the global error handler\n * @param {ErrorHandler} handler\n */\nexport function setGlobalErrorHandler(handler: ErrorHandler): void {\n delegateHandler = handler;\n}\n\n/**\n * Return the global error handler\n * @param {Exception} ex\n */\nexport function globalErrorHandler(ex: Exception): void {\n try {\n delegateHandler(ex);\n } catch {} // eslint-disable-line no-empty\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport enum TracesSamplerValues {\n AlwaysOff = 'always_off',\n AlwaysOn = 'always_on',\n ParentBasedAlwaysOff = 'parentbased_always_off',\n ParentBasedAlwaysOn = 'parentbased_always_on',\n ParentBasedTraceIdRatio = 'parentbased_traceidratio',\n TraceIdRatio = 'traceidratio',\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogLevel } from '@opentelemetry/api';\nimport { TracesSamplerValues } from './sampling';\n\nconst DEFAULT_LIST_SEPARATOR = ',';\n\n/**\n * Environment interface to define all names\n */\n\nconst ENVIRONMENT_BOOLEAN_KEYS = ['OTEL_SDK_DISABLED'] as const;\n\ntype ENVIRONMENT_BOOLEANS = {\n [K in (typeof ENVIRONMENT_BOOLEAN_KEYS)[number]]?: boolean;\n};\n\nfunction isEnvVarABoolean(key: unknown): key is keyof ENVIRONMENT_BOOLEANS {\n return (\n ENVIRONMENT_BOOLEAN_KEYS.indexOf(key as keyof ENVIRONMENT_BOOLEANS) > -1\n );\n}\n\nconst ENVIRONMENT_NUMBERS_KEYS = [\n 'OTEL_BSP_EXPORT_TIMEOUT',\n 'OTEL_BSP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BSP_MAX_QUEUE_SIZE',\n 'OTEL_BSP_SCHEDULE_DELAY',\n 'OTEL_BLRP_EXPORT_TIMEOUT',\n 'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE',\n 'OTEL_BLRP_MAX_QUEUE_SIZE',\n 'OTEL_BLRP_SCHEDULE_DELAY',\n 'OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT',\n 'OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT',\n 'OTEL_SPAN_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_LINK_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT',\n 'OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT',\n 'OTEL_EXPORTER_OTLP_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_TRACES_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_METRICS_TIMEOUT',\n 'OTEL_EXPORTER_OTLP_LOGS_TIMEOUT',\n 'OTEL_EXPORTER_JAEGER_AGENT_PORT',\n] as const;\n\ntype ENVIRONMENT_NUMBERS = {\n [K in (typeof ENVIRONMENT_NUMBERS_KEYS)[number]]?: number;\n};\n\nfunction isEnvVarANumber(key: unknown): key is keyof ENVIRONMENT_NUMBERS {\n return (\n ENVIRONMENT_NUMBERS_KEYS.indexOf(key as keyof ENVIRONMENT_NUMBERS) > -1\n );\n}\n\nconst ENVIRONMENT_LISTS_KEYS = [\n 'OTEL_NO_PATCH_MODULES',\n 'OTEL_PROPAGATORS',\n] as const;\n\ntype ENVIRONMENT_LISTS = {\n [K in (typeof ENVIRONMENT_LISTS_KEYS)[number]]?: string[];\n};\n\nfunction isEnvVarAList(key: unknown): key is keyof ENVIRONMENT_LISTS {\n return ENVIRONMENT_LISTS_KEYS.indexOf(key as keyof ENVIRONMENT_LISTS) > -1;\n}\n\nexport type ENVIRONMENT = {\n CONTAINER_NAME?: string;\n ECS_CONTAINER_METADATA_URI_V4?: string;\n ECS_CONTAINER_METADATA_URI?: string;\n HOSTNAME?: string;\n KUBERNETES_SERVICE_HOST?: string;\n NAMESPACE?: string;\n OTEL_EXPORTER_JAEGER_AGENT_HOST?: string;\n OTEL_EXPORTER_JAEGER_ENDPOINT?: string;\n OTEL_EXPORTER_JAEGER_PASSWORD?: string;\n OTEL_EXPORTER_JAEGER_USER?: string;\n OTEL_EXPORTER_OTLP_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT?: string;\n OTEL_EXPORTER_OTLP_HEADERS?: string;\n OTEL_EXPORTER_OTLP_TRACES_HEADERS?: string;\n OTEL_EXPORTER_OTLP_METRICS_HEADERS?: string;\n OTEL_EXPORTER_OTLP_LOGS_HEADERS?: string;\n OTEL_EXPORTER_ZIPKIN_ENDPOINT?: string;\n OTEL_LOG_LEVEL?: DiagLogLevel;\n OTEL_RESOURCE_ATTRIBUTES?: string;\n OTEL_SERVICE_NAME?: string;\n OTEL_TRACES_EXPORTER?: string;\n OTEL_TRACES_SAMPLER_ARG?: string;\n OTEL_TRACES_SAMPLER?: string;\n OTEL_LOGS_EXPORTER?: string;\n OTEL_EXPORTER_OTLP_INSECURE?: string;\n OTEL_EXPORTER_OTLP_TRACES_INSECURE?: string;\n OTEL_EXPORTER_OTLP_METRICS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_LOGS_INSECURE?: string;\n OTEL_EXPORTER_OTLP_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION?: string;\n OTEL_EXPORTER_OTLP_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY?: string;\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE?: string;\n OTEL_EXPORTER_OTLP_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL?: string;\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE?: string;\n} & ENVIRONMENT_BOOLEANS &\n ENVIRONMENT_NUMBERS &\n ENVIRONMENT_LISTS;\n\nexport type RAW_ENVIRONMENT = {\n [key: string]: string | number | undefined | string[];\n};\n\nexport const DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity;\n\nexport const DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128;\n\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT = 128;\nexport const DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT = 128;\n\n/**\n * Default environment variables\n */\nexport const DEFAULT_ENVIRONMENT: Required<ENVIRONMENT> = {\n OTEL_SDK_DISABLED: false,\n CONTAINER_NAME: '',\n ECS_CONTAINER_METADATA_URI_V4: '',\n ECS_CONTAINER_METADATA_URI: '',\n HOSTNAME: '',\n KUBERNETES_SERVICE_HOST: '',\n NAMESPACE: '',\n OTEL_BSP_EXPORT_TIMEOUT: 30000,\n OTEL_BSP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BSP_MAX_QUEUE_SIZE: 2048,\n OTEL_BSP_SCHEDULE_DELAY: 5000,\n OTEL_BLRP_EXPORT_TIMEOUT: 30000,\n OTEL_BLRP_MAX_EXPORT_BATCH_SIZE: 512,\n OTEL_BLRP_MAX_QUEUE_SIZE: 2048,\n OTEL_BLRP_SCHEDULE_DELAY: 5000,\n OTEL_EXPORTER_JAEGER_AGENT_HOST: '',\n OTEL_EXPORTER_JAEGER_AGENT_PORT: 6832,\n OTEL_EXPORTER_JAEGER_ENDPOINT: '',\n OTEL_EXPORTER_JAEGER_PASSWORD: '',\n OTEL_EXPORTER_JAEGER_USER: '',\n OTEL_EXPORTER_OTLP_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: '',\n OTEL_EXPORTER_OTLP_HEADERS: '',\n OTEL_EXPORTER_OTLP_TRACES_HEADERS: '',\n OTEL_EXPORTER_OTLP_METRICS_HEADERS: '',\n OTEL_EXPORTER_OTLP_LOGS_HEADERS: '',\n OTEL_EXPORTER_OTLP_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_TRACES_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_METRICS_TIMEOUT: 10000,\n OTEL_EXPORTER_OTLP_LOGS_TIMEOUT: 10000,\n OTEL_EXPORTER_ZIPKIN_ENDPOINT: 'http://localhost:9411/api/v2/spans',\n OTEL_LOG_LEVEL: DiagLogLevel.INFO,\n OTEL_NO_PATCH_MODULES: [],\n OTEL_PROPAGATORS: ['tracecontext', 'baggage'],\n OTEL_RESOURCE_ATTRIBUTES: '',\n OTEL_SERVICE_NAME: '',\n OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT: DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT:\n DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT,\n OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT: DEFAULT_ATTRIBUTE_COUNT_LIMIT,\n OTEL_SPAN_EVENT_COUNT_LIMIT: 128,\n OTEL_SPAN_LINK_COUNT_LIMIT: 128,\n OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT,\n OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT:\n DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT,\n OTEL_TRACES_EXPORTER: '',\n OTEL_TRACES_SAMPLER: TracesSamplerValues.ParentBasedAlwaysOn,\n OTEL_TRACES_SAMPLER_ARG: '',\n OTEL_LOGS_EXPORTER: '',\n OTEL_EXPORTER_OTLP_INSECURE: '',\n OTEL_EXPORTER_OTLP_TRACES_INSECURE: '',\n OTEL_EXPORTER_OTLP_METRICS_INSECURE: '',\n OTEL_EXPORTER_OTLP_LOGS_INSECURE: '',\n OTEL_EXPORTER_OTLP_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_TRACES_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_METRICS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_LOGS_COMPRESSION: '',\n OTEL_EXPORTER_OTLP_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY: '',\n OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE: '',\n OTEL_EXPORTER_OTLP_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: 'http/protobuf',\n OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: 'cumulative',\n};\n\n/**\n * @param key\n * @param environment\n * @param values\n */\nfunction parseBoolean(\n key: keyof ENVIRONMENT_BOOLEANS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n if (typeof values[key] === 'undefined') {\n return;\n }\n\n const value = String(values[key]);\n // support case-insensitive \"true\"\n environment[key] = value.toLowerCase() === 'true';\n}\n\n/**\n * Parses a variable as number with number validation\n * @param name\n * @param environment\n * @param values\n * @param min\n * @param max\n */\nfunction parseNumber(\n name: keyof ENVIRONMENT_NUMBERS,\n environment: ENVIRONMENT,\n values: RAW_ENVIRONMENT,\n min = -Infinity,\n max = Infinity\n) {\n if (typeof values[name] !== 'undefined') {\n const value = Number(values[name] as string);\n if (!isNaN(value)) {\n if (value < min) {\n environment[name] = min;\n } else if (value > max) {\n environment[name] = max;\n } else {\n environment[name] = value;\n }\n }\n }\n}\n\n/**\n * Parses list-like strings from input into output.\n * @param name\n * @param environment\n * @param values\n * @param separator\n */\nfunction parseStringList(\n name: keyof ENVIRONMENT_LISTS,\n output: ENVIRONMENT,\n input: RAW_ENVIRONMENT,\n separator = DEFAULT_LIST_SEPARATOR\n) {\n const givenValue = input[name];\n if (typeof givenValue === 'string') {\n output[name] = givenValue.split(separator).map(v => v.trim());\n }\n}\n\n// The support string -> DiagLogLevel mappings\nconst logLevelMap: { [key: string]: DiagLogLevel } = {\n ALL: DiagLogLevel.ALL,\n VERBOSE: DiagLogLevel.VERBOSE,\n DEBUG: DiagLogLevel.DEBUG,\n INFO: DiagLogLevel.INFO,\n WARN: DiagLogLevel.WARN,\n ERROR: DiagLogLevel.ERROR,\n NONE: DiagLogLevel.NONE,\n};\n\n/**\n * Environmentally sets log level if valid log level string is provided\n * @param key\n * @param environment\n * @param values\n */\nfunction setLogLevelFromEnv(\n key: keyof ENVIRONMENT,\n environment: RAW_ENVIRONMENT | ENVIRONMENT,\n values: RAW_ENVIRONMENT\n) {\n const value = values[key];\n if (typeof value === 'string') {\n const theLevel = logLevelMap[value.toUpperCase()];\n if (theLevel != null) {\n environment[key] = theLevel;\n }\n }\n}\n\n/**\n * Parses environment values\n * @param values\n */\nexport function parseEnvironment(values: RAW_ENVIRONMENT): ENVIRONMENT {\n const environment: ENVIRONMENT = {};\n\n for (const env in DEFAULT_ENVIRONMENT) {\n const key = env as keyof ENVIRONMENT;\n\n switch (key) {\n case 'OTEL_LOG_LEVEL':\n setLogLevelFromEnv(key, environment, values);\n break;\n\n default:\n if (isEnvVarABoolean(key)) {\n parseBoolean(key, environment, values);\n } else if (isEnvVarANumber(key)) {\n parseNumber(key, environment, values);\n } else if (isEnvVarAList(key)) {\n parseStringList(key, environment, values);\n } else {\n const value = values[key];\n if (typeof value !== 'undefined' && value !== null) {\n environment[key] = String(value);\n }\n }\n }\n }\n\n return environment;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nfunction intValue(charCode: number): number {\n // 0-9\n if (charCode >= 48 && charCode <= 57) {\n return charCode - 48;\n }\n\n // a-f\n if (charCode >= 97 && charCode <= 102) {\n return charCode - 87;\n }\n\n // A-F\n return charCode - 55;\n}\n\nexport function hexToBinary(hexStr: string): Uint8Array {\n const buf = new Uint8Array(hexStr.length / 2);\n let offset = 0;\n\n for (let i = 0; i < hexStr.length; i += 2) {\n const hi = intValue(hexStr.charCodeAt(i));\n const lo = intValue(hexStr.charCodeAt(i + 1));\n buf[offset++] = (hi << 4) | lo;\n }\n\n return buf;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { hexToBinary } from '../../common/hex-to-binary';\n\nexport function hexToBase64(hexStr: string): string {\n return Buffer.from(hexToBinary(hexStr)).toString('base64');\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IdGenerator } from '../../trace/IdGenerator';\nconst SPAN_ID_BYTES = 8;\nconst TRACE_ID_BYTES = 16;\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n */\nexport class RandomIdGenerator implements IdGenerator {\n /**\n * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex\n * characters corresponding to 128 bits.\n */\n generateTraceId = getIdGenerator(TRACE_ID_BYTES);\n\n /**\n * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex\n * characters corresponding to 64 bits.\n */\n generateSpanId = getIdGenerator(SPAN_ID_BYTES);\n}\n\nconst SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES);\nfunction getIdGenerator(bytes: number): () => string {\n return function generateId() {\n for (let i = 0; i < bytes / 4; i++) {\n // unsigned right shift drops decimal part of the number\n // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE\n SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4);\n }\n\n // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated\n for (let i = 0; i < bytes; i++) {\n if (SHARED_BUFFER[i] > 0) {\n break;\n } else if (i === bytes - 1) {\n SHARED_BUFFER[bytes - 1] = 1;\n }\n }\n\n return SHARED_BUFFER.toString('hex', 0, bytes);\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { performance } from 'perf_hooks';\n\nexport const otperformance = performance;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.24.1';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../../version';\nimport {\n TelemetrySdkLanguageValues,\n SemanticResourceAttributes,\n} from '@opentelemetry/semantic-conventions';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [SemanticResourceAttributes.TELEMETRY_SDK_NAME]: 'opentelemetry',\n [SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'node',\n [SemanticResourceAttributes.TELEMETRY_SDK_LANGUAGE]:\n TelemetrySdkLanguageValues.NODEJS,\n [SemanticResourceAttributes.TELEMETRY_SDK_VERSION]: VERSION,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport function unrefTimer(timer: NodeJS.Timer): void {\n timer.unref();\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { getEnvWithoutDefaults, getEnv } from './environment';\nexport * from './globalThis';\nexport * from './hex-to-base64';\nexport * from './RandomIdGenerator';\nexport * from './performance';\nexport * from './sdk-info';\nexport * from './timer-util';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport * from './node';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\nimport { TimeOriginLegacy } from './types';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\nexport function getTimeOrigin(): number {\n let timeOrigin = performance.timeOrigin;\n if (typeof timeOrigin !== 'number') {\n const perf: TimeOriginLegacy = performance as unknown as TimeOriginLegacy;\n timeOrigin = perf.timing && perf.timing.fetchStart;\n }\n return timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(getTimeOrigin());\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Must be a performance.now() if it's smaller than process start time.\n if (time < getTimeOrigin()) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substr(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Exception } from '@opentelemetry/api';\n\n/**\n * This interface defines a fallback to read a timeOrigin when it is not available on performance.timeOrigin,\n * this happens for example on Safari Mac\n * then the timeOrigin is taken from fetchStart - which is the closest to timeOrigin\n */\nexport interface TimeOriginLegacy {\n timing: {\n fetchStart: number;\n };\n}\n\n/**\n * This interface defines the params that are be added to the wrapped function\n * using the \"shimmer.wrap\"\n */\nexport interface ShimWrapped extends Function {\n __wrapped: boolean;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __unwrap: Function;\n // eslint-disable-next-line @typescript-eslint/ban-types\n __original: Function;\n}\n\n/**\n * An instrumentation library consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n * @deprecated Use {@link InstrumentationScope} instead.\n */\nexport interface InstrumentationLibrary {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/**\n * An instrumentation scope consists of the name and optional version\n * used to obtain a tracer or meter from a provider. This metadata is made\n * available on ReadableSpan and MetricRecord for use by the export pipeline.\n */\nexport interface InstrumentationScope {\n readonly name: string;\n readonly version?: string;\n readonly schemaUrl?: string;\n}\n\n/** Defines an error handler function */\nexport type ErrorHandler = (ex: Exception) => void;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\n )\n );\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * IdGenerator provides an interface for generating Trace Id and Span Id.\n */\nexport interface IdGenerator {\n /** Returns a trace ID composed of 32 lowercase hex characters. */\n generateTraceId(): string;\n /** Returns a span ID composed of 16 lowercase hex characters. */\n generateSpanId(): string;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey, Span } from '@opentelemetry/api';\n\nconst RPC_METADATA_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key RPC_METADATA'\n);\n\nexport enum RPCType {\n HTTP = 'http',\n}\n\ntype HTTPMetadata = {\n type: RPCType.HTTP;\n route?: string;\n span: Span;\n};\n\n/**\n * Allows for future rpc metadata to be used with this mechanism\n */\nexport type RPCMetadata = HTTPMetadata;\n\nexport function setRPCMetadata(context: Context, meta: RPCMetadata): Context {\n return context.setValue(RPC_METADATA_KEY, meta);\n}\n\nexport function deleteRPCMetadata(context: Context): Context {\n return context.deleteValue(RPC_METADATA_KEY);\n}\n\nexport function getRPCMetadata(context: Context): RPCMetadata | undefined {\n return context.getValue(RPC_METADATA_KEY) as RPCMetadata | undefined;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples no traces.\n */\nexport class AlwaysOffSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return 'AlwaysOffSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Sampler, SamplingDecision, SamplingResult } from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples all traces.\n */\nexport class AlwaysOnSampler implements Sampler {\n shouldSample(): SamplingResult {\n return {\n decision: SamplingDecision.RECORD_AND_SAMPLED,\n };\n }\n\n toString(): string {\n return 'AlwaysOnSampler';\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n Link,\n Sampler,\n SamplingResult,\n SpanAttributes,\n SpanKind,\n TraceFlags,\n trace,\n} from '@opentelemetry/api';\nimport { globalErrorHandler } from '../../common/global-error-handler';\nimport { AlwaysOffSampler } from './AlwaysOffSampler';\nimport { AlwaysOnSampler } from './AlwaysOnSampler';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * A composite sampler that either respects the parent span's sampling decision\n * or delegates to `delegateSampler` for root spans.\n */\nexport class ParentBasedSampler implements Sampler {\n private _root: Sampler;\n private _remoteParentSampled: Sampler;\n private _remoteParentNotSampled: Sampler;\n private _localParentSampled: Sampler;\n private _localParentNotSampled: Sampler;\n\n constructor(config: ParentBasedSamplerConfig) {\n this._root = config.root;\n\n if (!this._root) {\n globalErrorHandler(\n new Error('ParentBasedSampler must have a root sampler configured')\n );\n this._root = new AlwaysOnSampler();\n }\n\n this._remoteParentSampled =\n config.remoteParentSampled ?? new AlwaysOnSampler();\n this._remoteParentNotSampled =\n config.remoteParentNotSampled ?? new AlwaysOffSampler();\n this._localParentSampled =\n config.localParentSampled ?? new AlwaysOnSampler();\n this._localParentNotSampled =\n config.localParentNotSampled ?? new AlwaysOffSampler();\n }\n\n shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n attributes: SpanAttributes,\n links: Link[]\n ): SamplingResult {\n const parentContext = trace.getSpanContext(context);\n\n if (!parentContext || !isSpanContextValid(parentContext)) {\n return this._root.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.isRemote) {\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._remoteParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n return this._remoteParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n if (parentContext.traceFlags & TraceFlags.SAMPLED) {\n return this._localParentSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n return this._localParentNotSampled.shouldSample(\n context,\n traceId,\n spanName,\n spanKind,\n attributes,\n links\n );\n }\n\n toString(): string {\n return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`;\n }\n}\n\ninterface ParentBasedSamplerConfig {\n /** Sampler called for spans with no parent */\n root: Sampler;\n /** Sampler called for spans with a remote parent which was sampled. Default AlwaysOn */\n remoteParentSampled?: Sampler;\n /** Sampler called for spans with a remote parent which was not sampled. Default AlwaysOff */\n remoteParentNotSampled?: Sampler;\n /** Sampler called for spans with a local parent which was sampled. Default AlwaysOn */\n localParentSampled?: Sampler;\n /** Sampler called for spans with a local parent which was not sampled. Default AlwaysOff */\n localParentNotSampled?: Sampler;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Sampler,\n SamplingDecision,\n SamplingResult,\n isValidTraceId,\n} from '@opentelemetry/api';\n\n/**\n * @deprecated Use the one defined in @opentelemetry/sdk-trace-base instead.\n * Sampler that samples a given fraction of traces based of trace id deterministically.\n */\nexport class TraceIdRatioBasedSampler implements Sampler {\n private _upperBound: number;\n\n constructor(private readonly _ratio: number = 0) {\n this._ratio = this._normalize(_ratio);\n this._upperBound = Math.floor(this._ratio * 0xffffffff);\n }\n\n shouldSample(context: unknown, traceId: string): SamplingResult {\n return {\n decision:\n isValidTraceId(traceId) && this._accumulate(traceId) < this._upperBound\n ? SamplingDecision.RECORD_AND_SAMPLED\n : SamplingDecision.NOT_RECORD,\n };\n }\n\n toString(): string {\n return `TraceIdRatioBased{${this._ratio}}`;\n }\n\n private _normalize(ratio: number): number {\n if (typeof ratio !== 'number' || isNaN(ratio)) return 0;\n return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio;\n }\n\n private _accumulate(traceId: string): number {\n let accumulation = 0;\n for (let i = 0; i < traceId.length / 8; i++) {\n const pos = i * 8;\n const part = parseInt(traceId.slice(pos, pos + 8), 16);\n accumulation = (accumulation ^ part) >>> 0;\n }\n return accumulation;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { isPlainObject } from './lodash.merge';\n\nconst MAX_LEVEL = 20;\n\ninterface ObjectInto {\n obj: any;\n key: string;\n}\n\n/**\n * Merges objects together\n * @param args - objects / values to be merged\n */\nexport function merge(...args: any[]): any {\n let result: any = args.shift();\n const objects: WeakMap<any, ObjectInto[]> | undefined = new WeakMap<\n any,\n ObjectInto[]\n >();\n while (args.length > 0) {\n result = mergeTwoObjects(result, args.shift(), 0, objects);\n }\n\n return result;\n}\n\nfunction takeValue(value: any): any {\n if (isArray(value)) {\n return value.slice();\n }\n return value;\n}\n\n/**\n * Merges two objects\n * @param one - first object\n * @param two - second object\n * @param level - current deep level\n * @param objects - objects holder that has been already referenced - to prevent\n * cyclic dependency\n */\nfunction mergeTwoObjects(\n one: any,\n two: any,\n level = 0,\n objects: WeakMap<any, ObjectInto[]>\n): any {\n let result: any;\n if (level > MAX_LEVEL) {\n return undefined;\n }\n level++;\n if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) {\n result = takeValue(two);\n } else if (isArray(one)) {\n result = one.slice();\n if (isArray(two)) {\n for (let i = 0, j = two.length; i < j; i++) {\n result.push(takeValue(two[i]));\n }\n } else if (isObject(two)) {\n const keys = Object.keys(two);\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n result[key] = takeValue(two[key]);\n }\n }\n } else if (isObject(one)) {\n if (isObject(two)) {\n if (!shouldMerge(one, two)) {\n return two;\n }\n result = Object.assign({}, one);\n const keys = Object.keys(two);\n\n for (let i = 0, j = keys.length; i < j; i++) {\n const key = keys[i];\n const twoValue = two[key];\n\n if (isPrimitive(twoValue)) {\n if (typeof twoValue === 'undefined') {\n delete result[key];\n } else {\n // result[key] = takeValue(twoValue);\n result[key] = twoValue;\n }\n } else {\n const obj1 = result[key];\n const obj2 = twoValue;\n\n if (\n wasObjectReferenced(one, key, objects) ||\n wasObjectReferenced(two, key, objects)\n ) {\n delete result[key];\n } else {\n if (isObject(obj1) && isObject(obj2)) {\n const arr1 = objects.get(obj1) || [];\n const arr2 = objects.get(obj2) || [];\n arr1.push({ obj: one, key });\n arr2.push({ obj: two, key });\n objects.set(obj1, arr1);\n objects.set(obj2, arr2);\n }\n\n result[key] = mergeTwoObjects(\n result[key],\n twoValue,\n level,\n objects\n );\n }\n }\n }\n } else {\n result = two;\n }\n }\n\n return result;\n}\n\n/**\n * Function to check if object has been already reference\n * @param obj\n * @param key\n * @param objects\n */\nfunction wasObjectReferenced(\n obj: any,\n key: string,\n objects: WeakMap<any, ObjectInto[]>\n): boolean {\n const arr = objects.get(obj[key]) || [];\n for (let i = 0, j = arr.length; i < j; i++) {\n const info = arr[i];\n if (info.key === key && info.obj === obj) {\n return true;\n }\n }\n return false;\n}\n\nfunction isArray(value: any): boolean {\n return Array.isArray(value);\n}\n\nfunction isFunction(value: any): boolean {\n return typeof value === 'function';\n}\n\nfunction isObject(value: any): boolean {\n return (\n !isPrimitive(value) &&\n !isArray(value) &&\n !isFunction(value) &&\n typeof value === 'object'\n );\n}\n\nfunction isPrimitive(value: any): boolean {\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'undefined' ||\n value instanceof Date ||\n value instanceof RegExp ||\n value === null\n );\n}\n\nfunction shouldMerge(one: any, two: any): boolean {\n if (!isPlainObject(one) || !isPlainObject(two)) {\n return false;\n }\n\n return true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Error that is thrown on timeouts.\n */\nexport class TimeoutError extends Error {\n constructor(message?: string) {\n super(message);\n\n // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see:\n // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise\n * rejects, and resolves if the specified promise resolves.\n *\n * <p> NOTE: this operation will continue even after it throws a {@link TimeoutError}.\n *\n * @param promise promise to use with timeout.\n * @param timeout the timeout in milliseconds until the returned promise is rejected.\n */\nexport function callWithTimeout<T>(\n promise: Promise<T>,\n timeout: number\n): Promise<T> {\n let timeoutHandle: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>(function timeoutFunction(\n _resolve,\n reject\n ) {\n timeoutHandle = setTimeout(function timeoutHandler() {\n reject(new TimeoutError('Operation timed out.'));\n }, timeout);\n });\n\n return Promise.race([promise, timeoutPromise]).then(\n result => {\n clearTimeout(timeoutHandle);\n return result;\n },\n reason => {\n clearTimeout(timeoutHandle);\n throw reason;\n }\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ShimWrapped } from '../common/types';\n\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nexport function isWrapped(func: unknown): func is ShimWrapped {\n return (\n typeof func === 'function' &&\n typeof (func as ShimWrapped).__original === 'function' &&\n typeof (func as ShimWrapped).__unwrap === 'function' &&\n (func as ShimWrapped).__wrapped === true\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport class Deferred<T> {\n private _promise: Promise<T>;\n private _resolve!: (val: T) => void;\n private _reject!: (error: unknown) => void;\n constructor() {\n this._promise = new Promise((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n get promise() {\n return this._promise;\n }\n\n resolve(val: T) {\n this._resolve(val);\n }\n\n reject(err: unknown) {\n this._reject(err);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Deferred } from './promise';\n\n/**\n * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked.\n */\nexport class BindOnceFuture<\n R,\n This = unknown,\n T extends (this: This, ...args: unknown[]) => R = () => R,\n> {\n private _isCalled = false;\n private _deferred = new Deferred<R>();\n constructor(\n private _callback: T,\n private _that: This\n ) {}\n\n get isCalled() {\n return this._isCalled;\n }\n\n get promise() {\n return this._deferred.promise;\n }\n\n call(...args: Parameters<T>): Promise<R> {\n if (!this._isCalled) {\n this._isCalled = true;\n try {\n Promise.resolve(this._callback.call(this._that, ...args)).then(\n val => this._deferred.resolve(val),\n err => this._deferred.reject(err)\n );\n } catch (err) {\n this._deferred.reject(err);\n }\n }\n return this._deferred.promise;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './baggage/propagation/W3CBaggagePropagator';\nexport * from './common/anchored-clock';\nexport * from './common/attributes';\nexport * from './common/global-error-handler';\nexport * from './common/logging-error-handler';\nexport * from './common/time';\nexport * from './common/types';\nexport * from './common/hex-to-binary';\nexport * from './ExportResult';\nexport * as baggageUtils from './baggage/utils';\nexport * from './platform';\nexport * from './propagation/composite';\nexport * from './trace/W3CTraceContextPropagator';\nexport * from './trace/IdGenerator';\nexport * from './trace/rpc-metadata';\nexport * from './trace/sampler/AlwaysOffSampler';\nexport * from './trace/sampler/AlwaysOnSampler';\nexport * from './trace/sampler/ParentBasedSampler';\nexport * from './trace/sampler/TraceIdRatioBasedSampler';\nexport * from './trace/suppress-tracing';\nexport * from './trace/TraceState';\nexport * from './utils/environment';\nexport * from './utils/merge';\nexport * from './utils/sampling';\nexport * from './utils/timeout';\nexport * from './utils/url';\nexport * from './utils/wrap';\nexport * from './utils/callback';\nexport * from './version';\nimport { _export } from './internal/exporter';\nexport const internal = {\n _export,\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n propagation,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from '@opentelemetry/core';\nimport { JaegerPropagatorConfig } from './types';\n\nexport const UBER_TRACE_ID_HEADER = 'uber-trace-id';\nexport const UBER_BAGGAGE_HEADER_PREFIX = 'uberctx';\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n * {trace-id}:{span-id}:{parent-span-id}:{flags}\n * {trace-id}\n * 64-bit or 128-bit random number in base16 format.\n * Can be variable length, shorter values are 0-padded on the left.\n * Value of 0 is invalid.\n * {span-id}\n * 64-bit random number in base16 format.\n * {parent-span-id}\n * Set to 0 because this field is deprecated.\n * {flags}\n * One byte bitmap, as two hex digits.\n * Inspired by jaeger-client-node project.\n */\nexport class JaegerPropagator implements TextMapPropagator {\n private readonly _jaegerTraceHeader: string;\n private readonly _jaegerBaggageHeaderPrefix: string;\n\n constructor(customTraceHeader?: string);\n constructor(config?: JaegerPropagatorConfig);\n constructor(config?: JaegerPropagatorConfig | string) {\n if (typeof config === 'string') {\n this._jaegerTraceHeader = config;\n this._jaegerBaggageHeaderPrefix = UBER_BAGGAGE_HEADER_PREFIX;\n } else {\n this._jaegerTraceHeader =\n config?.customTraceHeader || UBER_TRACE_ID_HEADER;\n this._jaegerBaggageHeaderPrefix =\n config?.customBaggageHeaderPrefix || UBER_BAGGAGE_HEADER_PREFIX;\n }\n }\n\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n const baggage = propagation.getBaggage(context);\n if (spanContext && isTracingSuppressed(context) === false) {\n const traceFlags = `0${(\n spanContext.traceFlags || TraceFlags.NONE\n ).toString(16)}`;\n\n setter.set(\n carrier,\n this._jaegerTraceHeader,\n `${spanContext.traceId}:${spanContext.spanId}:0:${traceFlags}`\n );\n }\n\n if (baggage) {\n for (const [key, entry] of baggage.getAllEntries()) {\n setter.set(\n carrier,\n `${this._jaegerBaggageHeaderPrefix}-${key}`,\n encodeURIComponent(entry.value)\n );\n }\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const uberTraceIdHeader = getter.get(carrier, this._jaegerTraceHeader);\n const uberTraceId = Array.isArray(uberTraceIdHeader)\n ? uberTraceIdHeader[0]\n : uberTraceIdHeader;\n const baggageValues = getter\n .keys(carrier)\n .filter(key => key.startsWith(`${this._jaegerBaggageHeaderPrefix}-`))\n .map(key => {\n const value = getter.get(carrier, key);\n return {\n key: key.substring(this._jaegerBaggageHeaderPrefix.length + 1),\n value: Array.isArray(value) ? value[0] : value,\n };\n });\n\n let newContext = context;\n // if the trace id header is present and valid, inject it into the context\n if (typeof uberTraceId === 'string') {\n const spanContext = deserializeSpanContext(uberTraceId);\n if (spanContext) {\n newContext = trace.setSpanContext(newContext, spanContext);\n }\n }\n if (baggageValues.length === 0) return newContext;\n\n // if baggage values are present, inject it into the current baggage\n let currentBaggage =\n propagation.getBaggage(context) ?? propagation.createBaggage();\n for (const baggageEntry of baggageValues) {\n if (baggageEntry.value === undefined) continue;\n currentBaggage = currentBaggage.setEntry(baggageEntry.key, {\n value: decodeURIComponent(baggageEntry.value),\n });\n }\n newContext = propagation.setBaggage(newContext, currentBaggage);\n\n return newContext;\n }\n\n fields(): string[] {\n return [this._jaegerTraceHeader];\n }\n}\n\nconst VALID_HEX_RE = /^[0-9a-f]{1,2}$/i;\n\n/**\n * @param {string} serializedString - a serialized span context.\n * @return {SpanContext} - returns a span context represented by the serializedString.\n **/\nfunction deserializeSpanContext(serializedString: string): SpanContext | null {\n const headers = decodeURIComponent(serializedString).split(':');\n if (headers.length !== 4) {\n return null;\n }\n\n const [_traceId, _spanId, , flags] = headers;\n\n const traceId = _traceId.padStart(32, '0');\n const spanId = _spanId.padStart(16, '0');\n const traceFlags = VALID_HEX_RE.test(flags) ? parseInt(flags, 16) & 1 : 1;\n\n return { traceId, spanId, isRemote: true, traceFlags };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './JaegerPropagator';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n AsyncHooksContextManager,\n AsyncLocalStorageContextManager,\n} from '@opentelemetry/context-async-hooks';\nimport { B3Propagator, B3InjectEncoding } from '@opentelemetry/propagator-b3';\nimport {\n BasicTracerProvider,\n PROPAGATOR_FACTORY,\n SDKRegistrationConfig,\n} from '@opentelemetry/sdk-trace-base';\nimport * as semver from 'semver';\nimport { NodeTracerConfig } from './config';\nimport { JaegerPropagator } from '@opentelemetry/propagator-jaeger';\n\n/**\n * Register this TracerProvider for use with the OpenTelemetry API.\n * Undefined values may be replaced with defaults, and\n * null values will be skipped.\n *\n * @param config Configuration object for SDK registration\n */\nexport class NodeTracerProvider extends BasicTracerProvider {\n protected static override readonly _registeredPropagators = new Map<\n string,\n PROPAGATOR_FACTORY\n >([\n ...BasicTracerProvider._registeredPropagators,\n [\n 'b3',\n () =>\n new B3Propagator({ injectEncoding: B3InjectEncoding.SINGLE_HEADER }),\n ],\n [\n 'b3multi',\n () => new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }),\n ],\n ['jaeger', () => new JaegerPropagator()],\n ]);\n\n constructor(config: NodeTracerConfig = {}) {\n super(config);\n }\n\n override register(config: SDKRegistrationConfig = {}): void {\n if (config.contextManager === undefined) {\n const ContextManager = semver.gte(process.version, '14.8.0')\n ? AsyncLocalStorageContextManager\n : AsyncHooksContextManager;\n config.contextManager = new ContextManager();\n config.contextManager.enable();\n }\n\n super.register(config);\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { NodeTracerConfig } from './config';\nexport * from './NodeTracerProvider';\nexport * from '@opentelemetry/sdk-trace-base';\n","{\n \"name\": \"dotenv\",\n \"version\": \"16.5.0\",\n \"description\": \"Loads environment variables from .env file\",\n \"main\": \"lib/main.js\",\n \"types\": \"lib/main.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/main.d.ts\",\n \"require\": \"./lib/main.js\",\n \"default\": \"./lib/main.js\"\n },\n \"./config\": \"./config.js\",\n \"./config.js\": \"./config.js\",\n \"./lib/env-options\": \"./lib/env-options.js\",\n \"./lib/env-options.js\": \"./lib/env-options.js\",\n \"./lib/cli-options\": \"./lib/cli-options.js\",\n \"./lib/cli-options.js\": \"./lib/cli-options.js\",\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"dts-check\": \"tsc --project tests/types/tsconfig.json\",\n \"lint\": \"standard\",\n \"pretest\": \"npm run lint && npm run dts-check\",\n \"test\": \"tap run --allow-empty-coverage --disable-coverage --timeout=60000\",\n \"test:coverage\": \"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov\",\n \"prerelease\": \"npm test\",\n \"release\": \"standard-version\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git://github.com/motdotla/dotenv.git\"\n },\n \"homepage\": \"https://github.com/motdotla/dotenv#readme\",\n \"funding\": \"https://dotenvx.com\",\n \"keywords\": [\n \"dotenv\",\n \"env\",\n \".env\",\n \"environment\",\n \"variables\",\n \"config\",\n \"settings\"\n ],\n \"readmeFilename\": \"README.md\",\n \"license\": \"BSD-2-Clause\",\n \"devDependencies\": {\n \"@types/node\": \"^18.11.3\",\n \"decache\": \"^4.6.2\",\n \"sinon\": \"^14.0.1\",\n \"standard\": \"^17.0.0\",\n \"standard-version\": \"^9.5.0\",\n \"tap\": \"^19.2.0\",\n \"typescript\": \"^4.8.4\"\n },\n \"engines\": {\n \"node\": \">=12\"\n },\n \"browser\": {\n \"fs\": false\n }\n}\n","const fs = require('fs')\nconst path = require('path')\nconst os = require('os')\nconst crypto = require('crypto')\nconst packageJson = require('../package.json')\n\nconst version = packageJson.version\n\nconst LINE = /(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg\n\n// Parse src into an Object\nfunction parse (src) {\n const obj = {}\n\n // Convert buffer to string\n let lines = src.toString()\n\n // Convert line breaks to same format\n lines = lines.replace(/\\r\\n?/mg, '\\n')\n\n let match\n while ((match = LINE.exec(lines)) != null) {\n const key = match[1]\n\n // Default undefined or null to empty string\n let value = (match[2] || '')\n\n // Remove whitespace\n value = value.trim()\n\n // Check if double quoted\n const maybeQuote = value[0]\n\n // Remove surrounding quotes\n value = value.replace(/^(['\"`])([\\s\\S]*)\\1$/mg, '$2')\n\n // Expand newlines if double quoted\n if (maybeQuote === '\"') {\n value = value.replace(/\\\\n/g, '\\n')\n value = value.replace(/\\\\r/g, '\\r')\n }\n\n // Add to object\n obj[key] = value\n }\n\n return obj\n}\n\nfunction _parseVault (options) {\n const vaultPath = _vaultPath(options)\n\n // Parse .env.vault\n const result = DotenvModule.configDotenv({ path: vaultPath })\n if (!result.parsed) {\n const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`)\n err.code = 'MISSING_DATA'\n throw err\n }\n\n // handle scenario for comma separated keys - for use with key rotation\n // example: DOTENV_KEY=\"dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod\"\n const keys = _dotenvKey(options).split(',')\n const length = keys.length\n\n let decrypted\n for (let i = 0; i < length; i++) {\n try {\n // Get full key\n const key = keys[i].trim()\n\n // Get instructions for decrypt\n const attrs = _instructions(result, key)\n\n // Decrypt\n decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key)\n\n break\n } catch (error) {\n // last key\n if (i + 1 >= length) {\n throw error\n }\n // try next key\n }\n }\n\n // Parse decrypted .env string\n return DotenvModule.parse(decrypted)\n}\n\nfunction _warn (message) {\n console.log(`[dotenv@${version}][WARN] ${message}`)\n}\n\nfunction _debug (message) {\n console.log(`[dotenv@${version}][DEBUG] ${message}`)\n}\n\nfunction _dotenvKey (options) {\n // prioritize developer directly setting options.DOTENV_KEY\n if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {\n return options.DOTENV_KEY\n }\n\n // secondary infra already contains a DOTENV_KEY environment variable\n if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {\n return process.env.DOTENV_KEY\n }\n\n // fallback to empty string\n return ''\n}\n\nfunction _instructions (result, dotenvKey) {\n // Parse DOTENV_KEY. Format is a URI\n let uri\n try {\n uri = new URL(dotenvKey)\n } catch (error) {\n if (error.code === 'ERR_INVALID_URL') {\n const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n throw error\n }\n\n // Get decrypt key\n const key = uri.password\n if (!key) {\n const err = new Error('INVALID_DOTENV_KEY: Missing key part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get environment\n const environment = uri.searchParams.get('environment')\n if (!environment) {\n const err = new Error('INVALID_DOTENV_KEY: Missing environment part')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n }\n\n // Get ciphertext payload\n const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`\n const ciphertext = result.parsed[environmentKey] // DOTENV_VAULT_PRODUCTION\n if (!ciphertext) {\n const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`)\n err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT'\n throw err\n }\n\n return { ciphertext, key }\n}\n\nfunction _vaultPath (options) {\n let possibleVaultPath = null\n\n if (options && options.path && options.path.length > 0) {\n if (Array.isArray(options.path)) {\n for (const filepath of options.path) {\n if (fs.existsSync(filepath)) {\n possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`\n }\n }\n } else {\n possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`\n }\n } else {\n possibleVaultPath = path.resolve(process.cwd(), '.env.vault')\n }\n\n if (fs.existsSync(possibleVaultPath)) {\n return possibleVaultPath\n }\n\n return null\n}\n\nfunction _resolveHome (envPath) {\n return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath\n}\n\nfunction _configVault (options) {\n const debug = Boolean(options && options.debug)\n if (debug) {\n _debug('Loading env from encrypted .env.vault')\n }\n\n const parsed = DotenvModule._parseVault(options)\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsed, options)\n\n return { parsed }\n}\n\nfunction configDotenv (options) {\n const dotenvPath = path.resolve(process.cwd(), '.env')\n let encoding = 'utf8'\n const debug = Boolean(options && options.debug)\n\n if (options && options.encoding) {\n encoding = options.encoding\n } else {\n if (debug) {\n _debug('No encoding is specified. UTF-8 is used by default')\n }\n }\n\n let optionPaths = [dotenvPath] // default, look for .env\n if (options && options.path) {\n if (!Array.isArray(options.path)) {\n optionPaths = [_resolveHome(options.path)]\n } else {\n optionPaths = [] // reset default\n for (const filepath of options.path) {\n optionPaths.push(_resolveHome(filepath))\n }\n }\n }\n\n // Build the parsed data in a temporary object (because we need to return it). Once we have the final\n // parsed data, we will combine it with process.env (or options.processEnv if provided).\n let lastError\n const parsedAll = {}\n for (const path of optionPaths) {\n try {\n // Specifying an encoding returns a string instead of a buffer\n const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }))\n\n DotenvModule.populate(parsedAll, parsed, options)\n } catch (e) {\n if (debug) {\n _debug(`Failed to load ${path} ${e.message}`)\n }\n lastError = e\n }\n }\n\n let processEnv = process.env\n if (options && options.processEnv != null) {\n processEnv = options.processEnv\n }\n\n DotenvModule.populate(processEnv, parsedAll, options)\n\n if (lastError) {\n return { parsed: parsedAll, error: lastError }\n } else {\n return { parsed: parsedAll }\n }\n}\n\n// Populates process.env from .env file\nfunction config (options) {\n // fallback to original dotenv if DOTENV_KEY is not set\n if (_dotenvKey(options).length === 0) {\n return DotenvModule.configDotenv(options)\n }\n\n const vaultPath = _vaultPath(options)\n\n // dotenvKey exists but .env.vault file does not exist\n if (!vaultPath) {\n _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`)\n\n return DotenvModule.configDotenv(options)\n }\n\n return DotenvModule._configVault(options)\n}\n\nfunction decrypt (encrypted, keyStr) {\n const key = Buffer.from(keyStr.slice(-64), 'hex')\n let ciphertext = Buffer.from(encrypted, 'base64')\n\n const nonce = ciphertext.subarray(0, 12)\n const authTag = ciphertext.subarray(-16)\n ciphertext = ciphertext.subarray(12, -16)\n\n try {\n const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce)\n aesgcm.setAuthTag(authTag)\n return `${aesgcm.update(ciphertext)}${aesgcm.final()}`\n } catch (error) {\n const isRange = error instanceof RangeError\n const invalidKeyLength = error.message === 'Invalid key length'\n const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data'\n\n if (isRange || invalidKeyLength) {\n const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)')\n err.code = 'INVALID_DOTENV_KEY'\n throw err\n } else if (decryptionFailed) {\n const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY')\n err.code = 'DECRYPTION_FAILED'\n throw err\n } else {\n throw error\n }\n }\n}\n\n// Populate process.env with parsed values\nfunction populate (processEnv, parsed, options = {}) {\n const debug = Boolean(options && options.debug)\n const override = Boolean(options && options.override)\n\n if (typeof parsed !== 'object') {\n const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate')\n err.code = 'OBJECT_REQUIRED'\n throw err\n }\n\n // Set process.env\n for (const key of Object.keys(parsed)) {\n if (Object.prototype.hasOwnProperty.call(processEnv, key)) {\n if (override === true) {\n processEnv[key] = parsed[key]\n }\n\n if (debug) {\n if (override === true) {\n _debug(`\"${key}\" is already defined and WAS overwritten`)\n } else {\n _debug(`\"${key}\" is already defined and was NOT overwritten`)\n }\n }\n } else {\n processEnv[key] = parsed[key]\n }\n }\n}\n\nconst DotenvModule = {\n configDotenv,\n _configVault,\n _parseVault,\n config,\n decrypt,\n parse,\n populate\n}\n\nmodule.exports.configDotenv = DotenvModule.configDotenv\nmodule.exports._configVault = DotenvModule._configVault\nmodule.exports._parseVault = DotenvModule._parseVault\nmodule.exports.config = DotenvModule.config\nmodule.exports.decrypt = DotenvModule.decrypt\nmodule.exports.parse = DotenvModule.parse\nmodule.exports.populate = DotenvModule.populate\n\nmodule.exports = DotenvModule\n","// ../config.js accepts options via environment variables\nconst options = {}\n\nif (process.env.DOTENV_CONFIG_ENCODING != null) {\n options.encoding = process.env.DOTENV_CONFIG_ENCODING\n}\n\nif (process.env.DOTENV_CONFIG_PATH != null) {\n options.path = process.env.DOTENV_CONFIG_PATH\n}\n\nif (process.env.DOTENV_CONFIG_DEBUG != null) {\n options.debug = process.env.DOTENV_CONFIG_DEBUG\n}\n\nif (process.env.DOTENV_CONFIG_OVERRIDE != null) {\n options.override = process.env.DOTENV_CONFIG_OVERRIDE\n}\n\nif (process.env.DOTENV_CONFIG_DOTENV_KEY != null) {\n options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY\n}\n\nmodule.exports = options\n","const re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/\n\nmodule.exports = function optionMatcher (args) {\n return args.reduce(function (acc, cur) {\n const matches = cur.match(re)\n if (matches) {\n acc[matches[1]] = matches[2]\n }\n return acc\n }, {})\n}\n","// core configs\nexport * from './core/configs/global-error-handler'\n\n// core decorators\nexport * from './core/decorators/controller-http-decorator'\nexport * from './core/decorators/dependency-container'\n\n// core entities\nexport * from './core/entities/aggregate-object-root'\nexport * from './core/entities/aggregate-root'\nexport * from './core/entities/common-dto'\nexport * from './core/entities/domain-event'\nexport * from './core/entities/entity'\nexport * from './core/entities/entity-object'\nexport * from './core/entities/optional'\nexport * from './core/entities/replace'\nexport * from './core/entities/unique-entity-id'\nexport * from './core/entities/unique-object-id'\nexport * from './core/entities/value-object'\nexport * from './core/entities/watched-list'\n\n// core errors\nexport * from './core/errors/application-error'\nexport * from './core/errors/conflict-error'\nexport * from './core/errors/domain-error'\nexport * from './core/errors/http-client-error'\nexport * from './core/errors/infra-error'\n\n// core http\nexport * from './core/http/base-controller'\nexport * from './core/http/dto-response'\nexport * from './core/http/error-notifier'\nexport * from './core/http/get-take-and-skip'\nexport * from './core/http/health-connections'\nexport * from './core/http/http'\nexport * from './core/http/pagination'\nexport * from './core/http/validator'\n\n// infra adapters http\nexport * from './infra/adapters/http/express-adapter'\nexport * from './infra/adapters/http/fastify-adapter'\n\n// infra adapters notifications\nexport * from './infra/adapters/notifications/discord'\nexport * from './infra/adapters/notifications/in-memory'\nexport * from './infra/adapters/notifications/notification-factory'\nexport * from './infra/adapters/notifications/sentry'\n\n// infra adapters validations\nexport * from './infra/adapters/validators/zod/zod-validator'\n\n// infra adapters observability]\nexport * from './infra/adapters/logger/logger'\nexport * from './infra/adapters/logger/winston-otel-fastify'\nexport * from './infra/adapters/observability/otel/opentelemetry'\nexport * from './infra/adapters/observability/otel/span-decorator'\nexport * from './infra/adapters/observability/otel/tracer-gateway-opentelemetry'\nexport * from './infra/adapters/observability/tracer-gateway'\n\n// infra common\nexport * from './infra/env'\n","import 'reflect-metadata'\n\ntype Class<T = any> = new (...args: any[]) => T\n\ntype Registration =\n | { type: 'class'; myClass: Class; singleton: boolean }\n | { type: 'value'; value: any }\n\nexport class DependencyContainer {\n static registry = new Map<string, Registration>()\n static singletons = new Map<string, any>()\n\n static register<T>(\n token: string,\n myClass: Class<T>,\n options: { singleton: boolean }\n ) {\n this.registry.set(token, {\n type: 'class',\n myClass,\n singleton: options.singleton,\n })\n }\n\n static registerValue<T>(token: string, value: T) {\n this.registry.set(token, { type: 'value', value })\n }\n\n static resolve<T>(target: Class<T>): T {\n const injectMetadata: Record<number, string> =\n Reflect.getOwnMetadata('inject:params', target) || {}\n\n const paramCount = Object.keys(injectMetadata).length\n\n const params = Array.from({ length: paramCount }, (_, index) => {\n const token = injectMetadata[index]\n if (!token) {\n throw new Error(\n `Missing @Inject token for parameter index ${index} in ${target.name}`\n )\n }\n return this.resolveToken(token)\n })\n\n return new target(...params)\n }\n\n static resolveToken(token: string): any {\n const registration = this.registry.get(token)\n\n if (!registration) {\n throw new Error(\n `\"${token}\" not registered. Please register it in the container.`\n )\n }\n\n if (registration.type === 'value') {\n return registration.value\n }\n\n const { myClass, singleton } = registration\n\n if (singleton) {\n if (!this.singletons.has(token)) {\n const instance = this.resolve(myClass)\n this.singletons.set(token, instance)\n }\n return this.singletons.get(token)\n }\n\n return this.resolve(myClass)\n }\n}\n\nexport function Inject(token: string): ParameterDecorator {\n return (\n target: object,\n _propertyKey: string | symbol | undefined,\n parameterIndex: number\n ): void => {\n const constructor =\n typeof target === 'function' ? target : target.constructor\n\n const existingInjectedParams: Record<number, string> =\n Reflect.getOwnMetadata('inject:params', constructor) || {}\n\n existingInjectedParams[parameterIndex] = token\n\n Reflect.defineMetadata('inject:params', existingInjectedParams, constructor)\n }\n}\n","import { DependencyContainer } from '../../core/decorators/dependency-container'\nimport type { IErrorNotifier } from '../../core/http/error-notifier'\n\nexport class GlobalErrorHandler {\n protected readonly errorNotifier: IErrorNotifier\n\n constructor(readonly env: Record<string, any>) {\n this.errorNotifier = DependencyContainer.resolveToken('IErrorNotifier')\n }\n\n register() {\n process.on('uncaughtException', (err) => {\n this.errorNotifier.notify(err, { env: this.env.ENVIRONMENT })\n process.exit(1)\n })\n\n process.on('unhandledRejection', (reason) => {\n if (reason instanceof Error) {\n this.errorNotifier.notify(reason, { env: this.env.ENVIRONMENT })\n } else {\n this.errorNotifier.notify(new Error(String(reason)), {\n env: this.env.ENVIRONMENT,\n })\n }\n\n process.exit(1)\n })\n }\n}\n","export type PropertiesError = {\n receivedValue?: any\n type: string\n message: string\n property: string | number | undefined\n propertyType?: string\n path?: string\n}\n\nexport type CommonError = {\n location: string\n propertyErrors?: PropertiesError[]\n}\n\nexport type ApiCommonError = {\n code: number\n occurredAt: Date\n message: string\n errorCode: string\n errors?: CommonError[]\n}\n\nexport enum ApiErrorEnum {\n DOMAIN = 'ERR001',\n APPLICATION = 'ERR002',\n INFRA = 'ERR003',\n HTTP_CLIENT = 'ERR004',\n VALIDATOR = 'ERR005',\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class ApplicationError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.APPLICATION,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\ntype ConflictProps = { id: string; [key: string]: unknown }\n\nexport default class ConflictError<T extends ConflictProps> extends Error {\n props: ApiCommonError\n conflictProps: T | T[]\n\n constructor(conflictProps: T | T[]) {\n super('Resource already exists.')\n this.conflictProps = conflictProps\n this.props = {\n code: 409,\n errorCode: ApiErrorEnum.APPLICATION,\n message: this.message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class DomainError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.DOMAIN,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import { type ApiCommonError, ApiErrorEnum } from './api-common-error'\n\nexport default class InfraError extends Error {\n props: ApiCommonError\n\n constructor(message: string) {\n super(message)\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.INFRA,\n message,\n occurredAt: new Date(),\n }\n }\n}\n","import {\n type ApiCommonError,\n ApiErrorEnum,\n type CommonError,\n} from './api-common-error'\n\nexport default class ValidationError extends Error {\n props: ApiCommonError\n\n constructor(errors: CommonError[]) {\n super('Validation Error')\n this.props = {\n code: 400,\n errorCode: ApiErrorEnum.VALIDATOR,\n message: 'Validation Error',\n occurredAt: new Date(),\n errors,\n }\n }\n}\n","import { DependencyContainer } from '../../core/decorators/dependency-container'\nimport ApplicationError from '../../core/errors/application-error'\nimport ConflictError from '../../core/errors/conflict-error'\nimport DomainError from '../../core/errors/domain-error'\nimport InfraError from '../../core/errors/infra-error'\nimport ValidationError from '../../core/errors/validation-error'\nimport { MiddlewareFunction } from '../../infra/adapters/validators/zod/zod-validator'\n\nimport { IErrorNotifier } from './error-notifier'\n\nimport 'reflect-metadata'\n\ntype AnyObject = Record<string, any>\n\nexport type Request = {\n body: AnyObject\n params: AnyObject\n headers: AnyObject\n query: AnyObject\n}\n\nexport type Response = {\n code: number\n data: any\n}\n\nexport type ContextError = {\n env: string\n user?: {\n id?: string\n name?: string\n email?: string\n }\n request?: {\n method?: string\n requestId?: string\n url?: string\n headers?: any\n query?: any\n body?: any\n params?: any\n }\n}\n\nexport abstract class BaseController {\n protected readonly errorNotifier: IErrorNotifier\n\n abstract handle<T>(request: T | Request): Promise<Response>\n\n constructor() {\n this.errorNotifier = DependencyContainer.resolveToken('IErrorNotifier')\n }\n\n protected success<T>(dto?: T): Response {\n return {\n code: 200,\n data: { data: dto },\n }\n }\n\n protected noContent(): Response {\n return {\n code: 204,\n data: undefined,\n }\n }\n\n protected created<T>(dto?: T): Response {\n return {\n code: 201,\n data: dto ? { data: dto } : undefined,\n }\n }\n\n protected paginated<T>(dto?: T): Response {\n return {\n code: 200,\n data: dto,\n }\n }\n\n protected buildContextError(request: Request): ContextError {\n return {\n env: process.env.ENVIRONMENT as string,\n request: {\n body: request.body,\n headers: request.headers,\n params: request.params,\n query: request.query,\n },\n }\n }\n\n public async failure(error: Error, context: ContextError): Promise<Response> {\n if (error instanceof ConflictError) {\n return {\n code: error.props.code,\n data: {\n message: error.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n items: Array.isArray(error.conflictProps)\n ? error.conflictProps\n : [error.conflictProps],\n },\n }\n }\n\n if (\n error instanceof DomainError ||\n error instanceof ApplicationError ||\n error instanceof InfraError\n ) {\n return {\n code: error.props.code,\n data: {\n message: error.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n },\n }\n }\n\n if (error instanceof ValidationError) {\n return {\n code: error.props.code,\n data: {\n message: error.props.message,\n errorCode: error.props.errorCode,\n occurredAt: error.props.occurredAt,\n errors: error.props.errors,\n },\n }\n }\n\n if (process.env.SHOULD_NOTIFY_ERROR) {\n await this.errorNotifier.notify(error, context)\n }\n\n return {\n code: 500,\n data: {\n code: 500,\n message: 'Server failed. Contact the administrator!',\n },\n }\n }\n\n public async execute(request: Request): Promise<Response> {\n const routeMetadata = Reflect.getMetadata('route', this.constructor)\n\n if (!routeMetadata) {\n throw new InfraError('Route metadata not found.')\n }\n\n const middlewares: MiddlewareFunction[] = routeMetadata.middlewares || []\n\n let processedRequest = request\n\n if (middlewares.length) {\n for (const middleware of middlewares) {\n processedRequest = await middleware(processedRequest)\n }\n }\n\n return await this.handle(processedRequest)\n }\n}\n","import { BaseController } from '../../core/http/base-controller'\nimport { MiddlewareFunction } from '../../infra/adapters/validators/zod/zod-validator'\nimport type { MethodType } from '../http/http'\n\ntype Props = {\n method: MethodType\n path: string\n middlewares?: MiddlewareFunction[]\n}\n\nexport function Controller({\n method,\n path,\n middlewares = [],\n}: Props): ClassDecorator {\n return (target: any) => {\n if (!(target.prototype instanceof BaseController)) {\n throw new Error(\n `The class ${target.name} should extends abstract class BaseController`\n )\n }\n\n Reflect.defineMetadata(\n 'route',\n { method, path: `/api/${path}`, middlewares },\n target\n )\n }\n}\n","import { ObjectId } from 'bson'\n\nexport class UniqueObjectId {\n private value: ObjectId\n\n constructor(value?: string) {\n this.value = new ObjectId(value)\n }\n\n toString() {\n return this.value.toString()\n }\n\n toValue() {\n return this.value.toString()\n }\n\n public equals(id: UniqueObjectId) {\n return id.toValue() === this.toValue()\n }\n}\n","import type { CommonDTO } from './common-dto'\nimport { UniqueObjectId } from './unique-object-id'\n\ntype PropsWithCommonDTO<Props> = Props & CommonDTO\n\nexport abstract class EntityObject<Props> {\n private _id: UniqueObjectId\n protected props: PropsWithCommonDTO<Props>\n\n get id() {\n return this._id\n }\n\n set id(id: UniqueObjectId) {\n this._id = id\n }\n\n get createdAt() {\n return this.props.createdAt\n }\n\n set createdAt(date: Date) {\n this.props.createdAt = date\n }\n\n get updatedAt(): Date | undefined | null {\n return this.props.updatedAt\n }\n\n public touch() {\n this.props.updatedAt = new Date()\n }\n\n protected constructor(props: PropsWithCommonDTO<Props>, id?: UniqueObjectId) {\n this._id = id ?? new UniqueObjectId(id)\n this.props = props\n }\n\n public equals(entity: EntityObject<Props>) {\n if (entity === this) {\n return true\n }\n\n if (entity.id === this._id) {\n return true\n }\n\n return false\n }\n}\n","import { EntityObject } from './entity-object'\n\nexport abstract class AggregateObjectRoot<Props> extends EntityObject<Props> {}\n","import { randomUUID } from 'node:crypto'\n\nexport class UniqueEntityId {\n private value: string\n\n constructor(value?: string) {\n this.value = value ?? randomUUID()\n }\n\n toString() {\n return this.value\n }\n\n toValue() {\n return this.value\n }\n\n public equals(id: UniqueEntityId) {\n return id.toValue() === this.toValue()\n }\n}\n","import { CommonDTO } from './common-dto'\nimport { UniqueEntityId } from './unique-entity-id'\n\ntype PropsWithCommonDTO<Props> = Props & CommonDTO\n\nexport abstract class Entity<Props> {\n private _id: UniqueEntityId\n protected props: PropsWithCommonDTO<Props>\n\n get id() {\n return this._id\n }\n\n set id(id: UniqueEntityId) {\n this._id = id\n }\n\n get createdAt() {\n return this.props.createdAt\n }\n\n set createdAt(date: Date) {\n this.props.createdAt = date\n }\n\n get updatedAt(): Date | undefined | null {\n return this.props.updatedAt\n }\n\n public touch() {\n this.props.updatedAt = new Date()\n }\n\n protected constructor(props: PropsWithCommonDTO<Props>, id?: UniqueEntityId) {\n this._id = id ?? new UniqueEntityId(id)\n this.props = props\n }\n\n public equals(entity: Entity<any>) {\n if (entity === this) {\n return true\n }\n\n if (entity.id === this._id) {\n return true\n }\n\n return false\n }\n}\n","import { Entity } from './entity'\n\nexport abstract class AggregateRoot<Props> extends Entity<Props> {}\n","export abstract class ValueObject<Props> {\n protected props: Props\n\n protected constructor(props: Props) {\n this.props = props\n }\n}\n","export abstract class WatchedList<T> {\n public currentItems: T[]\n private initial: T[]\n private new: T[]\n private removed: T[]\n private updated: T[]\n\n constructor(initialItems?: T[]) {\n this.currentItems = initialItems || []\n this.initial = initialItems || []\n this.new = []\n this.removed = []\n this.updated = []\n }\n\n abstract compareItems(a: T, b: T): boolean\n\n public getItems(): T[] {\n return this.currentItems\n }\n\n public getNewItems(): T[] {\n return this.new\n }\n\n public getRemovedItems(): T[] {\n return this.removed\n }\n\n public getUpdatedItems(): T[] {\n return this.updated\n }\n\n public addUpdatedItem(item: T) {\n return this.updated.push(item)\n }\n\n private isCurrentItem(item: T): boolean {\n return (\n this.currentItems.filter((v: T) => this.compareItems(item, v)).length !==\n 0\n )\n }\n\n private isNewItem(item: T): boolean {\n return this.new.filter((v: T) => this.compareItems(item, v)).length !== 0\n }\n\n private isRemovedItem(item: T): boolean {\n return (\n this.removed.filter((v: T) => this.compareItems(item, v)).length !== 0\n )\n }\n\n private removeFromNew(item: T): void {\n this.new = this.new.filter((v) => !this.compareItems(v, item))\n }\n\n private removeFromCurrent(item: T): void {\n this.currentItems = this.currentItems.filter(\n (v) => !this.compareItems(item, v)\n )\n }\n\n private removeFromRemoved(item: T): void {\n this.removed = this.removed.filter((v) => !this.compareItems(item, v))\n }\n\n private wasAddedInitially(item: T): boolean {\n return (\n this.initial.filter((v: T) => this.compareItems(item, v)).length !== 0\n )\n }\n\n public exists(item: T): boolean {\n return this.isCurrentItem(item)\n }\n\n public add(item: T): void {\n if (this.isRemovedItem(item)) {\n this.removeFromRemoved(item)\n }\n\n if (!this.isNewItem(item) && !this.wasAddedInitially(item)) {\n this.new.push(item)\n }\n\n if (!this.isCurrentItem(item)) {\n this.currentItems.push(item)\n }\n }\n\n public remove(item: T): void {\n this.removeFromCurrent(item)\n\n if (this.isNewItem(item)) {\n this.removeFromNew(item)\n\n return\n }\n\n if (!this.isRemovedItem(item)) {\n this.removed.push(item)\n }\n }\n\n public update(items: T[]): void {\n const newItems = items.filter((a) => {\n return !this.getItems().some((b) => this.compareItems(a, b))\n })\n\n const removedItems = this.getItems().filter((a) => {\n return !items.some((b) => this.compareItems(a, b))\n })\n\n const updatedItems = items.filter(\n (item) =>\n !newItems.some(\n (a) =>\n this.compareItems(item, a) &&\n !removedItems.some((b) => this.compareItems(item, b))\n )\n )\n\n this.currentItems = items\n this.new = newItems\n this.removed = removedItems\n this.updated = updatedItems\n }\n}\n","export function getTakeAndSkip(size: string, page: string) {\n const take = size ? Number(size) : 20\n const skip = page ? Number(page) : 1\n\n return { take, skip }\n}\n","import cors from 'cors'\nimport express, { Express, Request, Response } from 'express'\n\nimport type { BaseController } from '../../../core/http/base-controller'\nimport { IHttp } from '../../../core/http/http'\n\nimport { ErrorResponseCode } from './response-error-code'\nimport { validateControllerMetadata } from './validate-controller-metadata'\n\nexport class ExpressAdapter implements IHttp {\n readonly instance: Express\n private server: any\n\n constructor(\n readonly env: Record<string, any>,\n readonly logger: any\n ) {\n this.instance = express()\n this.instance.use(cors())\n this.instance.use(express.json({ limit: '10mb' }))\n this.instance.use(express.urlencoded({ limit: '10mb', extended: false }))\n this.instance.disable('x-powered-by')\n }\n\n registerRoute(controllerClass: BaseController): void {\n const { metadata } = validateControllerMetadata(controllerClass)\n\n this.instance[metadata.method](\n metadata.path,\n async (request: Request, response: Response) => {\n const requestData = {\n body: request.body,\n params: request.params,\n headers: request.headers,\n query: request.query,\n }\n\n try {\n const output = await controllerClass.execute(requestData)\n response\n .status(output.code || 204)\n .json(output.data || { code: ErrorResponseCode.NO_CONTENT_BODY })\n } catch (err: any) {\n const error = await controllerClass.failure(err, {\n env: this.env.ENVIRONMENT,\n request: {\n body: requestData.body,\n headers: requestData.headers,\n params: request.params,\n query: requestData.query,\n url: metadata.path,\n method: metadata.method,\n },\n })\n response.status(error.code).json(\n error.data || {\n error: ErrorResponseCode.NO_CONTENT_ERROR,\n }\n )\n }\n }\n )\n }\n\n async startServer(port: number): Promise<void> {\n return new Promise((resolve) => {\n this.server = this.instance.listen(port, () => {\n this.logger.info(`Server is running on PORT ${port}`)\n resolve()\n })\n })\n }\n\n async closeServer(): Promise<void> {\n return new Promise((resolve, reject) => {\n if (this.server) {\n this.server.close((err: any) => {\n if (err) return reject(err)\n resolve()\n })\n } else {\n resolve()\n }\n })\n }\n}\n","export enum ErrorResponseCode {\n NO_CONTENT_BODY = 'B001',\n NO_CONTENT_ERROR = 'B002',\n}\n","import { BaseController } from '../../../core/http/base-controller'\nimport type { MethodType } from '../../../core/http/http'\n\nimport 'reflect-metadata'\n\nexport function validateControllerMetadata(controller: BaseController) {\n const metadata = Reflect.getMetadata('route', controller.constructor) as {\n method: MethodType\n path: string\n }\n\n if (!metadata) {\n throw new Error(\n `Controller ${controller.constructor.name} not have metadata. Need to add decorator.`\n )\n }\n\n return {\n metadata,\n }\n}\n","import cors from '@fastify/cors'\nimport { IHttp } from 'core/http/http'\nimport fastify, { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\nimport qs from 'qs'\n\nimport { BaseController, Request } from '../../../core/http/base-controller'\n\nimport { ErrorResponseCode } from './response-error-code'\nimport { validateControllerMetadata } from './validate-controller-metadata'\n\nexport class FastifyAdapter implements IHttp {\n readonly instance: FastifyInstance\n\n constructor(\n readonly env: Record<string, any>,\n readonly logger: any\n ) {\n this.instance = fastify({\n bodyLimit: 10 * 1024 * 1024,\n querystringParser: (str) => qs.parse(str),\n loggerInstance: env.ENVIRONMENT !== 'test' ? logger : false,\n })\n\n this.instance.register(cors)\n }\n\n registerRoute(controllerClass: BaseController): void {\n const { metadata } = validateControllerMetadata(controllerClass)\n\n this.instance[metadata.method](\n metadata.path,\n async (request: FastifyRequest, reply: FastifyReply) => {\n const requestData = {\n body: request.body,\n params: request.params,\n headers: request.headers,\n query: request.query,\n } as Request\n\n try {\n const output = await controllerClass.execute(requestData)\n return reply.status(output.code || 200).send(\n output.data || {\n code: ErrorResponseCode.NO_CONTENT_BODY,\n }\n )\n } catch (err: any) {\n const error = await controllerClass.failure(err, {\n env: this.env.ENVIRONMENT,\n request: {\n body: requestData.body,\n headers: requestData.headers,\n params: request.params,\n query: requestData.query,\n url: metadata.path,\n method: metadata.method,\n },\n })\n return reply.status(error.code || 200).send(\n error.data || {\n code: ErrorResponseCode.NO_CONTENT_ERROR,\n }\n )\n }\n }\n )\n }\n\n async startServer(port: number): Promise<void> {\n await this.instance.listen({ port })\n\n if (this.env.NODE_ENV !== 'test') {\n this.logger.info(`Server is running on PORT ${port}`)\n }\n }\n\n async closeServer() {\n await this.instance.close()\n }\n}\n","import { Inject } from 'core/decorators/dependency-container'\nimport { MessageBuilder, Webhook } from 'discord-webhook-node'\n\nimport type { ContextError } from '../../../core/http/base-controller'\nimport type { IErrorNotifier } from '../../../core/http/error-notifier'\n\ntype DiscordOptions = {\n url: string\n env: string\n}\n\nexport class DiscordNotifier implements IErrorNotifier {\n private webhook: Webhook\n\n constructor(\n @Inject('DiscordConfig') private readonly options: DiscordOptions\n ) {\n this.webhook = new Webhook(this.options.url)\n }\n\n async notify(error: Error, context: ContextError): Promise<void> {\n const embed = new MessageBuilder()\n .setTitle('🚨 Error')\n .addField('Message', `\\`\\`\\`${error.message.slice(0, 300)}\\`\\`\\``)\n .addField(\n 'Route:',\n `\\`[${context?.request?.method}] ${context?.request?.url}\\``,\n true\n )\n .addField(\n 'Params:',\n '```json\\n' +\n JSON.stringify(context?.request?.params, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Query:',\n '```json\\n' +\n JSON.stringify(context?.request?.query, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Headers:',\n '```json\\n' +\n JSON.stringify(context?.request?.headers, null, 2) +\n '\\n```',\n true\n )\n .addField(\n 'Body:',\n '```json\\n' + JSON.stringify(context?.request?.body, null, 2) + '\\n```'\n )\n .addField(\n 'Stack Trace:',\n '```' + (error.stack || 'No stack provided').slice(0, 900) + '```'\n )\n .setFooter(`Env: ${this.options.env || 'development'}`)\n .setTimestamp()\n\n await this.webhook.send(embed)\n }\n}\n","import type { ContextError } from '../../../core/http/base-controller'\nimport type { IErrorNotifier } from '../../../core/http/error-notifier'\n\nexport class NotificationErrorInMemory implements IErrorNotifier {\n public errors: any[] = []\n\n async notify(error: Error, context?: ContextError): Promise<void> {\n console.error(error)\n\n this.errors.push({\n error: error.message,\n context,\n })\n }\n}\n","import * as Sentry from '@sentry/node'\nimport type { ContextError } from 'core/http/base-controller'\n\nimport { Inject } from '../../../core/decorators/dependency-container'\nimport { IErrorNotifier } from '../../../core/http/error-notifier'\n\ntype SentryOptions = {\n dsn: string\n environment: string\n}\n\nexport class SentryNotifier implements IErrorNotifier {\n constructor(@Inject('SentryConfig') private readonly options: SentryOptions) {\n Sentry.init({\n dsn: this.options.dsn,\n environment: this.options.environment,\n attachStacktrace: true,\n tracesSampleRate: this.options.environment === 'production' ? 0.1 : 1.0,\n maxBreadcrumbs: 100,\n debug: this.options.environment !== 'production',\n })\n }\n\n async notify(error: Error, context: ContextError): Promise<void> {\n Sentry.withScope((scope) => {\n scope.setLevel('error')\n\n if (context?.env) scope.setTag('env', context.env)\n\n if (context?.user) {\n scope.setUser({\n id: context.user.id,\n username: context.user.name,\n email: context.user.email,\n })\n }\n\n if (context?.request) {\n const { body, query, params, headers, method, url, requestId } =\n context.request\n\n scope.setContext('http', {\n method,\n requestId,\n url,\n headers,\n query,\n body,\n params,\n })\n }\n\n Sentry.captureException(error)\n })\n }\n}\n","import type { z } from 'zod'\n\nimport type { baseEnvSchema } from '../../env'\n\nimport { DiscordNotifier } from './discord'\nimport { NotificationErrorInMemory } from './in-memory'\nimport { SentryNotifier } from './sentry'\n\ntype OptionsNotifications = 'console' | 'discord' | 'sentry'\ntype EnvironmentEnum = z.infer<typeof baseEnvSchema>['ENVIRONMENT']\n\ntype Props = {\n test?: OptionsNotifications\n development?: OptionsNotifications\n staging?: OptionsNotifications\n production?: OptionsNotifications\n}\n\nexport class NotificationFactory {\n static define(env: EnvironmentEnum, definitions?: Props): any {\n const defaultDefinition = {\n test: this.defineProvider(definitions?.test ?? 'console'),\n development: this.defineProvider(definitions?.development ?? 'console'),\n staging: this.defineProvider(definitions?.staging ?? 'discord'),\n production: this.defineProvider(definitions?.production ?? 'sentry'),\n }\n\n return defaultDefinition[env]\n }\n\n private static defineProvider(provider: OptionsNotifications) {\n switch (provider) {\n case 'console':\n return NotificationErrorInMemory\n case 'discord':\n return DiscordNotifier\n case 'sentry':\n return SentryNotifier\n default:\n return NotificationErrorInMemory\n }\n }\n}\n","import type { ZodIssue } from 'zod'\n\nimport type {\n CommonError,\n PropertiesError,\n} from '../../../../core/errors/api-common-error'\n\ntype ZodError = ZodIssue & {\n expected: string\n received: string\n}\n\ntype ZodInvalidUnion = ZodError & {\n code: 'invalid_union'\n}\n\nexport default class ZodMapError {\n private static mapCommon(error: ZodError): PropertiesError {\n return {\n type: error.code,\n path: error.path.join('.'),\n property: error.path.pop(),\n propertyType: error.expected,\n receivedValue: error.received,\n message: error.message,\n }\n }\n\n private static mapInvalidUnion(error: ZodInvalidUnion): PropertiesError[] {\n const [errors] = error.unionErrors\n .flat()\n .map((err) => err.issues.map((item: any) => this.mapCommon(item)))\n\n return errors\n }\n\n private static mapInvalidType(error: ZodError): PropertiesError[] {\n return [this.mapCommon(error)]\n }\n\n private static mapErrorsFactory(error: ZodError): PropertiesError[] {\n if (error.code === 'invalid_union') {\n return this.mapInvalidUnion(error)\n }\n\n return this.mapInvalidType(error)\n }\n\n static mapErrors(errors: ZodIssue[][]) {\n const standardizedErrors = new Map<string | number, CommonError>()\n\n errors.flat().forEach((error) => {\n const keyError = standardizedErrors.get(error.path[0])\n\n if (keyError) {\n if (!keyError.propertyErrors) {\n keyError.propertyErrors = []\n }\n\n keyError.propertyErrors.push(\n ...this.mapErrorsFactory(error as ZodError)\n )\n\n return\n }\n\n standardizedErrors.set(error.path[0], {\n location: error.path[0],\n propertyErrors: Array.from([\n ...this.mapErrorsFactory(error as ZodError),\n ]),\n } as CommonError)\n })\n\n return Array.from(standardizedErrors, ([, arr]) => ({\n ...arr,\n })).flat()\n }\n}\n","import { ZodEffects, type ZodError, ZodObject } from 'zod'\n\nimport ValidationError from '../../../../core/errors/validation-error'\nimport IValidationHTTP, { RequestHttp } from '../../../../core/http/validator'\n\nimport ZodMapError from './zod-map-error'\nimport { zodValidator } from './zod-validator'\n\ntype SchemaDefinition = {\n headers: ZodObject<Record<string, any>>\n params: ZodObject<Record<string, any>>\n query: ZodObject<Record<string, any>>\n body:\n | ZodObject<Record<string, any>>\n | ZodEffects<ZodObject<Record<string, any>>>\n}\n\ntype ZodSchemaObject = ZodObject<SchemaDefinition>\n\nexport default class ZodValidator implements IValidationHTTP {\n constructor(private zodSchema: ZodSchemaObject) {}\n\n async validate<T>(requestHttp: RequestHttp): Promise<T> {\n const errors = []\n\n const {\n data: headersData = {},\n error: headersErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.headers\n ? await this.zodSchema.shape.headers.safeParseAsync(requestHttp.headers, {\n path: ['headers'],\n })\n : {}\n\n if (headersErrors?.errors) {\n errors.push(headersErrors?.errors)\n }\n\n const {\n data: paramsData = {},\n error: paramsErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.params\n ? await this.zodSchema.shape.params.safeParseAsync(requestHttp.params, {\n path: ['params'],\n })\n : {}\n\n if (paramsErrors?.errors) {\n errors.push(paramsErrors?.errors)\n }\n\n const {\n data: queryData = {},\n error: queryErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.query\n ? await this.zodSchema.shape.query.safeParseAsync(requestHttp.query, {\n path: ['query'],\n })\n : {}\n\n if (queryErrors?.errors) {\n errors.push(queryErrors?.errors)\n }\n\n const {\n data: bodyData = {},\n error: bodyErrors = {} as ZodError<{ errors: ZodError[] }>,\n } = requestHttp.body\n ? await this.zodSchema.shape.body.safeParseAsync(requestHttp.body, {\n path: ['body'],\n })\n : {}\n\n if (bodyErrors?.errors) {\n errors.push(bodyErrors?.errors)\n }\n\n if (errors.length) {\n throw new ValidationError(ZodMapError.mapErrors(errors))\n }\n\n return {\n body: bodyData,\n headers: headersData,\n params: paramsData,\n query: queryData,\n } as T\n }\n}\n\nexport { zodValidator }\n","import { z } from 'zod'\n\nimport { Request } from '../../../../core/http/base-controller'\n\nimport ZodValidator from './index'\n\nexport type ZodSchema = z.ZodObject<{\n headers: z.ZodObject<Record<string, any>>\n params: z.ZodObject<Record<string, any>>\n query: z.ZodObject<Record<string, any>>\n body:\n | z.ZodObject<Record<string, any>>\n | z.ZodEffects<z.ZodObject<Record<string, any>>>\n}>\n\nexport type MiddlewareFunction = (request: Request) => Promise<Request>\n\nexport function zodValidator(schema: ZodSchema): MiddlewareFunction {\n return async (request: Request): Promise<Request> => {\n const validator = new ZodValidator(schema)\n const validatedRequest = await validator.validate<Request>(request)\n return validatedRequest\n }\n}\n","import opentelemetry from '@opentelemetry/api'\nimport { Logger, logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { FastifyReply, FastifyRequest } from 'fastify'\nimport winston from 'winston'\n\nimport type { ILogger } from './logger'\n\nclass WinstonOtelFastify implements ILogger {\n logger: Logger | null = null\n consoleLogger: winston.Logger\n level: 'info' | 'error' | 'debug' | 'fatal' | 'warn' = 'info'\n\n private otelEnabled: boolean\n\n constructor() {\n this.otelEnabled = process.env.OTEL_ENABLE === 'true'\n this.level = (process.env.LOG_LEVEL as any) || 'info'\n\n if (this.otelEnabled) {\n this.logger = logs.getLogger(\n process.env.OTEL_SERVICE_NAME || 'default-service',\n process.env.OTEL_SERVICE_VERSION || '1.0.0'\n )\n }\n\n const transports =\n process.env.NODE_ENV === 'test'\n ? [new winston.transports.Console({ silent: true })]\n : [new winston.transports.Console()]\n\n this.consoleLogger = winston.createLogger({\n level: this.level,\n format: winston.format.combine(\n winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),\n winston.format((info) => {\n if (this.otelEnabled && process.env.NODE_ENV !== 'test') {\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span) {\n info.spanId = span.spanContext().spanId\n info.traceId = span.spanContext().traceId\n }\n }\n\n return info\n })(),\n winston.format.json()\n ),\n transports,\n })\n }\n\n private bodyIsFastifyRequest(\n body: string | FastifyRequest | FastifyReply\n ): body is FastifyRequest {\n return (body as FastifyRequest).method !== undefined\n }\n\n private bodyIsFastifyReply(\n body: string | FastifyRequest | FastifyReply\n ): body is FastifyReply {\n return (body as FastifyReply).statusCode !== undefined\n }\n\n private buildMessage(\n body: string | { req?: FastifyRequest; res?: FastifyReply }\n ) {\n if (\n typeof body === 'object' &&\n body.req &&\n this.bodyIsFastifyRequest(body.req)\n ) {\n return `${body.req.method} ${body.req.url}`\n } else if (\n typeof body === 'object' &&\n body.res &&\n this.bodyIsFastifyReply(body.res)\n ) {\n return `${body.res.request.method} ${body.res.request.url} ${body.res.statusCode} - ${body.res.elapsedTime} ms`\n } else if (typeof body === 'string') {\n return body\n } else {\n return ''\n }\n }\n\n private logMessage(\n body: string | { req?: FastifyRequest; res?: FastifyReply },\n severityNumber: SeverityNumber,\n severityText: string\n ) {\n const message = this.buildMessage(body)\n\n this.consoleLogger[severityText.toLowerCase() as keyof Logger](message)\n\n if (this.otelEnabled && this.logger && process.env.NODE_ENV !== 'test') {\n this.logger.emit({\n body: message,\n severityNumber,\n severityText,\n })\n }\n }\n\n info(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.INFO, 'INFO')\n }\n\n error(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.ERROR, 'ERROR')\n }\n\n debug(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.DEBUG, 'DEBUG')\n }\n\n fatal(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.FATAL, 'FATAL')\n }\n\n warn(body: string | { req?: FastifyRequest; res?: FastifyReply }) {\n this.logMessage(body, SeverityNumber.WARN, 'WARN')\n }\n\n trace(message: string) {\n this.consoleLogger.debug(message)\n\n if (this.otelEnabled && this.logger && process.env.NODE_ENV !== 'test') {\n this.logger.emit({\n body: message,\n severityNumber: SeverityNumber.TRACE,\n severityText: 'TRACE',\n })\n }\n }\n\n child(): WinstonOtelFastify {\n return new WinstonOtelFastify()\n }\n}\n\nexport { WinstonOtelFastify }\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, createContextKey } from '@opentelemetry/api';\n\nconst SUPPRESS_TRACING_KEY = createContextKey(\n 'OpenTelemetry SDK Context Key SUPPRESS_TRACING'\n);\n\nexport function suppressTracing(context: Context): Context {\n return context.setValue(SUPPRESS_TRACING_KEY, true);\n}\n\nexport function unsuppressTracing(context: Context): Context {\n return context.deleteValue(SUPPRESS_TRACING_KEY);\n}\n\nexport function isTracingSuppressed(context: Context): boolean {\n return context.getValue(SUPPRESS_TRACING_KEY) === true;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n TextMapGetter,\n TextMapPropagator,\n diag,\n TextMapSetter,\n} from '@opentelemetry/api';\n\n/** Configuration object for composite propagator */\nexport interface CompositePropagatorConfig {\n /**\n * List of propagators to run. Propagators run in the\n * list order. If a propagator later in the list writes the same context\n * key as a propagator earlier in the list, the later on will \"win\".\n */\n propagators?: TextMapPropagator[];\n}\n\n/** Combines multiple propagators into a single propagator. */\nexport class CompositePropagator implements TextMapPropagator {\n private readonly _propagators: TextMapPropagator[];\n private readonly _fields: string[];\n\n /**\n * Construct a composite propagator from a list of propagators.\n *\n * @param [config] Configuration object for composite propagator\n */\n constructor(config: CompositePropagatorConfig = {}) {\n this._propagators = config.propagators ?? [];\n\n this._fields = Array.from(\n new Set(\n this._propagators\n // older propagators may not have fields function, null check to be sure\n .map(p => (typeof p.fields === 'function' ? p.fields() : []))\n .reduce((x, y) => x.concat(y), [])\n )\n );\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same carrier key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to inject\n * @param carrier Carrier into which context will be injected\n */\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n for (const propagator of this._propagators) {\n try {\n propagator.inject(context, carrier, setter);\n } catch (err) {\n diag.warn(\n `Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n }\n }\n\n /**\n * Run each of the configured propagators with the given context and carrier.\n * Propagators are run in the order they are configured, so if multiple\n * propagators write the same context key, the propagator later in the list\n * will \"win\".\n *\n * @param context Context to add values to\n * @param carrier Carrier from which to extract context\n */\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n return this._propagators.reduce((ctx, propagator) => {\n try {\n return propagator.extract(ctx, carrier, getter);\n } catch (err) {\n diag.warn(\n `Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`\n );\n }\n return ctx;\n }, context);\n }\n\n fields(): string[] {\n // return a new array so our fields cannot be modified\n return this._fields.slice();\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n isSpanContextValid,\n SpanContext,\n TextMapGetter,\n TextMapPropagator,\n TextMapSetter,\n trace,\n TraceFlags,\n} from '@opentelemetry/api';\nimport { isTracingSuppressed } from './suppress-tracing';\nimport { TraceState } from './TraceState';\n\nexport const TRACE_PARENT_HEADER = 'traceparent';\nexport const TRACE_STATE_HEADER = 'tracestate';\n\nconst VERSION = '00';\nconst VERSION_PART = '(?!ff)[\\\\da-f]{2}';\nconst TRACE_ID_PART = '(?![0]{32})[\\\\da-f]{32}';\nconst PARENT_ID_PART = '(?![0]{16})[\\\\da-f]{16}';\nconst FLAGS_PART = '[\\\\da-f]{2}';\nconst TRACE_PARENT_REGEX = new RegExp(\n `^\\\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\\\s?$`\n);\n\n/**\n * Parses information from the [traceparent] span tag and converts it into {@link SpanContext}\n * @param traceParent - A meta property that comes from server.\n * It should be dynamically generated server side to have the server's request trace Id,\n * a parent span Id that was set on the server's request span,\n * and the trace flags to indicate the server's sampling decision\n * (01 = sampled, 00 = not sampled).\n * for example: '{version}-{traceId}-{spanId}-{sampleDecision}'\n * For more information see {@link https://www.w3.org/TR/trace-context/}\n */\nexport function parseTraceParent(traceParent: string): SpanContext | null {\n const match = TRACE_PARENT_REGEX.exec(traceParent);\n if (!match) return null;\n\n // According to the specification the implementation should be compatible\n // with future versions. If there are more parts, we only reject it if it's using version 00\n // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent\n if (match[1] === '00' && match[5]) return null;\n\n return {\n traceId: match[2],\n spanId: match[3],\n traceFlags: parseInt(match[4], 16),\n };\n}\n\n/**\n * Propagates {@link SpanContext} through Trace Context format propagation.\n *\n * Based on the Trace Context specification:\n * https://www.w3.org/TR/trace-context/\n */\nexport class W3CTraceContextPropagator implements TextMapPropagator {\n inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n const spanContext = trace.getSpanContext(context);\n if (\n !spanContext ||\n isTracingSuppressed(context) ||\n !isSpanContextValid(spanContext)\n )\n return;\n\n const traceParent = `${VERSION}-${spanContext.traceId}-${\n spanContext.spanId\n }-0${Number(spanContext.traceFlags || TraceFlags.NONE).toString(16)}`;\n\n setter.set(carrier, TRACE_PARENT_HEADER, traceParent);\n if (spanContext.traceState) {\n setter.set(\n carrier,\n TRACE_STATE_HEADER,\n spanContext.traceState.serialize()\n );\n }\n }\n\n extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const traceParentHeader = getter.get(carrier, TRACE_PARENT_HEADER);\n if (!traceParentHeader) return context;\n const traceParent = Array.isArray(traceParentHeader)\n ? traceParentHeader[0]\n : traceParentHeader;\n if (typeof traceParent !== 'string') return context;\n const spanContext = parseTraceParent(traceParent);\n if (!spanContext) return context;\n\n spanContext.isRemote = true;\n\n const traceStateHeader = getter.get(carrier, TRACE_STATE_HEADER);\n if (traceStateHeader) {\n // If more than one `tracestate` header is found, we merge them into a\n // single header.\n const state = Array.isArray(traceStateHeader)\n ? traceStateHeader.join(',')\n : traceStateHeader;\n spanContext.traceState = new TraceState(\n typeof state === 'string' ? state : undefined\n );\n }\n return trace.setSpanContext(context, spanContext);\n }\n\n fields(): string[] {\n return [TRACE_PARENT_HEADER, TRACE_STATE_HEADER];\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]';\nconst VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;\nconst VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;\nconst VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);\nconst VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;\nconst INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;\n\n/**\n * Key is opaque string up to 256 characters printable. It MUST begin with a\n * lowercase letter, and can only contain lowercase letters a-z, digits 0-9,\n * underscores _, dashes -, asterisks *, and forward slashes /.\n * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the\n * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key.\n * see https://www.w3.org/TR/trace-context/#key\n */\nexport function validateKey(key: string): boolean {\n return VALID_KEY_REGEX.test(key);\n}\n\n/**\n * Value is opaque string up to 256 characters printable ASCII RFC0020\n * characters (i.e., the range 0x20 to 0x7E) except comma , and =.\n */\nexport function validateValue(value: string): boolean {\n return (\n VALID_VALUE_BASE_REGEX.test(value) &&\n !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)\n );\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as api from '@opentelemetry/api';\nimport { validateKey, validateValue } from '../internal/validators';\n\nconst MAX_TRACE_STATE_ITEMS = 32;\nconst MAX_TRACE_STATE_LEN = 512;\nconst LIST_MEMBERS_SEPARATOR = ',';\nconst LIST_MEMBER_KEY_VALUE_SPLITTER = '=';\n\n/**\n * TraceState must be a class and not a simple object type because of the spec\n * requirement (https://www.w3.org/TR/trace-context/#tracestate-field).\n *\n * Here is the list of allowed mutations:\n * - New key-value pair should be added into the beginning of the list\n * - The value of any key can be updated. Modified keys MUST be moved to the\n * beginning of the list.\n */\nexport class TraceState implements api.TraceState {\n private _internalState: Map<string, string> = new Map();\n\n constructor(rawTraceState?: string) {\n if (rawTraceState) this._parse(rawTraceState);\n }\n\n set(key: string, value: string): TraceState {\n // TODO: Benchmark the different approaches(map vs list) and\n // use the faster one.\n const traceState = this._clone();\n if (traceState._internalState.has(key)) {\n traceState._internalState.delete(key);\n }\n traceState._internalState.set(key, value);\n return traceState;\n }\n\n unset(key: string): TraceState {\n const traceState = this._clone();\n traceState._internalState.delete(key);\n return traceState;\n }\n\n get(key: string): string | undefined {\n return this._internalState.get(key);\n }\n\n serialize(): string {\n return this._keys()\n .reduce((agg: string[], key) => {\n agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));\n return agg;\n }, [])\n .join(LIST_MEMBERS_SEPARATOR);\n }\n\n private _parse(rawTraceState: string) {\n if (rawTraceState.length > MAX_TRACE_STATE_LEN) return;\n this._internalState = rawTraceState\n .split(LIST_MEMBERS_SEPARATOR)\n .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning\n .reduce((agg: Map<string, string>, part: string) => {\n const listMember = part.trim(); // Optional Whitespace (OWS) handling\n const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);\n if (i !== -1) {\n const key = listMember.slice(0, i);\n const value = listMember.slice(i + 1, part.length);\n if (validateKey(key) && validateValue(value)) {\n agg.set(key, value);\n } else {\n // TODO: Consider to add warning log\n }\n }\n return agg;\n }, new Map());\n\n // Because of the reverse() requirement, trunc must be done after map is created\n if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {\n this._internalState = new Map(\n Array.from(this._internalState.entries())\n .reverse() // Use reverse same as original tracestate parse chain\n .slice(0, MAX_TRACE_STATE_ITEMS)\n );\n }\n }\n\n private _keys(): string[] {\n return Array.from(this._internalState.keys()).reverse();\n }\n\n private _clone(): TraceState {\n const traceState = new TraceState();\n traceState._internalState = new Map(this._internalState);\n return traceState;\n }\n}\n","import { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { CompositePropagator } from '@opentelemetry/core'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-proto'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'\nimport { Resource } from '@opentelemetry/resources'\nimport { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'\nimport {\n SEMRESATTRS_DEPLOYMENT_ENVIRONMENT,\n SEMRESATTRS_SERVICE_NAME,\n SEMRESATTRS_SERVICE_VERSION,\n} from '@opentelemetry/semantic-conventions'\n\nclass OpenTelemetry {\n sdk: NodeSDK\n\n constructor(private readonly env: Record<string, any>) {\n // Configuração do Resource com atributos semânticos\n const resource = new Resource({\n [SEMRESATTRS_SERVICE_NAME]: this.env.OTEL_SERVICE_NAME,\n [SEMRESATTRS_SERVICE_VERSION]: this.env.OTEL_SERVICE_VERSION || '1.0.0',\n [SEMRESATTRS_DEPLOYMENT_ENVIRONMENT]:\n this.env.ENVIRONMENT || 'development',\n })\n\n // Trace Exporter\n const traceExporter = new OTLPTraceExporter({\n url: this.env.OTEL_OTLP_TRACES_EXPORTER_URL,\n headers: {},\n })\n\n // Log Exporter\n const logExporter = new OTLPLogExporter({\n url: this.env.OTEL_OTLP_LOGS_EXPORTER_URL,\n headers: {},\n })\n\n // Metric Exporter\n const metricExporter = new OTLPMetricExporter({\n url: this.env.OTEL_OTLP_METRICS_EXPORTER_URL,\n headers: {},\n })\n\n this.sdk = new NodeSDK({\n resource,\n traceExporter,\n textMapPropagator: new CompositePropagator({\n propagators: [new W3CTraceContextPropagator()],\n }),\n spanProcessor: new BatchSpanProcessor(traceExporter, {\n maxQueueSize: 2048,\n maxExportBatchSize: 512,\n scheduledDelayMillis: 5000,\n exportTimeoutMillis: 30000,\n }),\n logRecordProcessor: new BatchLogRecordProcessor(logExporter, {\n maxQueueSize: 2048,\n maxExportBatchSize: 512,\n scheduledDelayMillis: 1000,\n exportTimeoutMillis: 30000,\n }),\n metricReader: new PeriodicExportingMetricReader({\n exporter: metricExporter,\n exportIntervalMillis: 10000,\n exportTimeoutMillis: 30000,\n }),\n })\n }\n\n startSdk() {\n try {\n this.sdk.start()\n console.log('OpenTelemetry SDK started successfully')\n } catch (error) {\n console.error('Error starting OpenTelemetry SDK:', error)\n throw error\n }\n }\n\n async shutdown() {\n try {\n await this.sdk.shutdown()\n console.log('OpenTelemetry SDK shut down successfully')\n } catch (error) {\n console.error('Error shutting down OpenTelemetry SDK:', error)\n throw error\n }\n }\n}\n\nexport { OpenTelemetry }\n","import opentelemetry, { SpanStatusCode, Tracer } from '@opentelemetry/api'\n\nimport 'reflect-metadata'\n\nexport function Span(): MethodDecorator {\n return function (\n target: any,\n propertyKey: string | symbol,\n descriptor: PropertyDescriptor\n ) {\n if (!process.env.OTEL_ENABLE) {\n return descriptor\n }\n\n const originalMethod = descriptor.value\n\n descriptor.value = function (...args: any[]) {\n const tracer: Tracer = opentelemetry.trace.getTracer(\n process.env.OTEL_SERVICE_NAME!,\n process.env.OTEL_SERVICE_VERSION!\n )\n\n const className = target.constructor?.name || 'UnknownClass'\n const methodName = String(propertyKey)\n const spanName = `${className}.${methodName}`\n\n return tracer.startActiveSpan(spanName, async (span) => {\n try {\n const result = originalMethod.apply(this, args)\n\n if (result instanceof Promise) {\n try {\n const awaitedResult = await result\n span.addEvent(`Method [${methodName}] executed successfully`)\n span.end()\n return awaitedResult\n } catch (error) {\n handleSpanError(span, error)\n throw error\n }\n } else {\n span.addEvent(`Method [${methodName}] executed successfully`)\n span.end()\n return result\n }\n } catch (error) {\n handleSpanError(span, error)\n throw error\n }\n })\n }\n\n return descriptor\n }\n}\n\nfunction handleSpanError(span: any, error: unknown): void {\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n if (error instanceof Error) {\n span.recordException(error)\n } else {\n span.recordException(new Error(String(error)))\n }\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n })\n\n span.end()\n}\n","import opentelemetry from '@opentelemetry/api'\n\nimport type { ITracerGateway } from '../tracer-gateway'\n\nexport class TracerGatewayOpentelemetry implements ITracerGateway {\n addEvent(name: string, attributes?: Record<string, any>): void {\n if (!process.env.OTEL_ENABLE) {\n return\n }\n\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span && attributes) {\n span.addEvent(name, attributes)\n } else if (span) {\n span.addEvent(name)\n }\n }\n\n setAttribute(key: string, value: string | number | boolean): void {\n if (!process.env.OTEL_ENABLE) {\n return\n }\n\n const span = opentelemetry.trace.getActiveSpan()\n\n if (span) {\n span.setAttribute(key, value)\n }\n }\n}\n","import { z } from 'zod'\n\nimport 'dotenv/config'\n\nexport const baseEnvSchema = z.object({\n NODE_ENV: z.enum(['test', 'development', 'production']).default('production'),\n ENVIRONMENT: z\n .enum(['test', 'development', 'staging', 'production'])\n .default('development'),\n PORT: z.coerce.number().default(3333),\n SHOULD_NOTIFY_ERROR: z.coerce.boolean().default(true),\n SENTRY_DSN: z.string().optional(),\n DISCORD_WEBHOOK_URL: z.string().optional(),\n LOG_LEVEL: z\n .enum(['info', 'error', 'debug', 'fatal', 'warn'])\n .default('info'),\n OTEL_ENABLE: z.coerce.boolean().default(false),\n OTEL_SERVICE_NAME: z.string().optional(),\n OTEL_SERVICE_VERSION: z.string().optional(),\n OTEL_OTLP_TRACES_EXPORTER_URL: z.string().url().optional(),\n OTEL_OTLP_LOGS_EXPORTER_URL: z.string().url().optional(),\n OTEL_OTLP_METRICS_EXPORTER_URL: z.string().url().optional(),\n})\n","(function () {\n require('./lib/main').config(\n Object.assign(\n {},\n require('./lib/env-options'),\n require('./lib/cli-options')(process.argv)\n )\n )\n})()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcG,WAAA,eAAA,SAAA,cAAA;;;;AAGH,QAAA,WAAA,QAAA,QAAA;AAaA,QAAM,uBAAuB;MAC3B;MACA;MACA;MACA;MACA;;QAGoB,mCAAgC,MAAA,iCAAA;aAAA;;;MAAtD,cAAA;AA4LmB,aAAA,gBAAgB,OAAO,aAAa;AAC7C,aAAA,WAAW;MACrB;;;;;;;MAxKE,KAAQA,UAAkB,QAAS;AACjC,YAAI,kBAAkB,SAAA,cAAc;AAClC,iBAAO,KAAK,kBAAkBA,UAAS,MAAM;;AAG/C,YAAI,OAAO,WAAW,YAAY;AAChC,iBAAO,KAAK,cAAcA,UAAS,MAAM;;AAE3C,eAAO;MACT;MAEQ,cAAkCA,UAAkB,QAAS;AACnE,cAAM,UAAU;AAChB,cAAM,iBAAiB,mCAA0B,MAAe;AAC9D,iBAAO,QAAQ,KAAKA,UAAS,MAAM,OAAO,MAAM,MAAM,IAAI,CAAC;QAC7D,GAFuB;AAGvB,eAAO,eAAe,gBAAgB,UAAU;UAC9C,YAAY;UACZ,cAAc;UACd,UAAU;UACV,OAAO,OAAO;SACf;AAMD,eAAO;MACT;;;;;;;;MASQ,kBACNA,UACA,IAAK;AAEL,cAAM,MAAM,KAAK,aAAa,EAAE;AAChC,YAAI,QAAQ;AAAW,iBAAO;AAC9B,aAAK,gBAAgB,EAAE;AAGvB,6BAAqB,QAAQ,CAAA,eAAa;AACxC,cAAI,GAAG,UAAU,MAAM;AAAW;AAClC,aAAG,UAAU,IAAI,KAAK,kBAAkB,IAAI,GAAG,UAAU,GAAGA,QAAO;QACrE,CAAC;AAED,YAAI,OAAO,GAAG,mBAAmB,YAAY;AAC3C,aAAG,iBAAiB,KA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AS,aAAaC,KAAaC,OAAwC;AAChE,QAAI,CAACT,QAAQC,IAAIC,aAAa;AAC5B;IACF;AAEA,UAAMC,OAAOC,aAAAA,QAAcC,MAAMC,cAAa;AAE9C,QAAIH,MAAM;AACRA,WAAKI,aAAaC,KAAKC,KAAAA;IACzB;EACF;AACF;;;AC9BA,iBAAkB;;;CCAjB,WAAA;AACCC,iBAAsBC,OACpBC,OAAOC,OACL,CAAC,GACDH,uBACAA,sBAA6BI,QAAQC,IAAI,CAAA,CAAA;AAG/C,GAAA;;;ADJO,IAAMC,gBAAgBC,aAAEC,OAAO;EACpCC,UAAUF,aAAEG,KAAK;IAAC;IAAQ;IAAe;GAAa,EAAEC,QAAQ,YAAA;EAChEC,aAAaL,aACVG,KAAK;IAAC;IAAQ;IAAe;IAAW;GAAa,EACrDC,QAAQ,aAAA;EACXE,MAAMN,aAAEO,OAAOC,OAAM,EAAGJ,QAAQ,IAAA;EAChCK,qBAAqBT,aAAEO,OAAOG,QAAO,EAAGN,QAAQ,IAAA;EAChDO,YAAYX,aAAEY,OAAM,EAAGC,SAAQ;EAC/BC,qBAAqBd,aAAEY,OAAM,EAAGC,SAAQ;EACxCE,WAAWf,aACRG,KAAK;IAAC;IAAQ;IAAS;IAAS;IAAS;GAAO,EAChDC,QAAQ,MAAA;EACXY,aAAahB,aAAEO,OAAOG,QAAO,EAAGN,QAAQ,KAAA;EACxCa,mBAAmBjB,aAAEY,OAAM,EAAGC,SAAQ;EACtCK,sBAAsBlB,aAAEY,OAAM,EAAGC,SAAQ;EACzCM,+BAA+BnB,aAAEY,OAAM,EAAGQ,IAAG,EAAGP,SAAQ;EACxDQ,6BAA6BrB,aAAEY,OAAM,EAAGQ,IAAG,EAAGP,SAAQ;EACtDS,gCAAgCtB,aAAEY,OAAM,EAAGQ,IAAG,EAAGP,SAAQ;AAC3D,CAAA;","names":["context","_a","_a","context","_a","context","isTracingSuppressed","context","SUPPRESS_TRACING_KEY","import_api","_a","import_api","import_api","W3CBaggagePropagator","context","isTracingSuppressed","AnchoredClock","import_api","import_api","_a","TracesSamplerValues","import_api","RandomIdGenerator","VERSION","VERSION","ExportResultCode","import_api","__values","CompositePropagator","_a","context","validateKey","VALID_KEY_REGEX","validateValue","VALID_VALUE_BASE_REGEX","INVALID_VALUE_COMMA_EQUAL_REGEX","VALID_KEY_CHAR_RANGE","VALID_KEY","VALID_VENDOR_KEY","MAX_TRACE_STATE_ITEMS","MAX_TRACE_STATE_LEN","LIST_MEMBERS_SEPARATOR","LIST_MEMBER_KEY_VALUE_SPLITTER","TraceState","validateKey","validateValue","parseTraceParent","TRACE_PARENT_REGEX","import_api","TRACE_PARENT_HEADER","TRACE_STATE_HEADER","VERSION","VERSION_PART","TRACE_ID_PART","PARENT_ID_PART","FLAGS_PART","W3CTraceContextPropagator","context","isTracingSuppressed","TraceState","import_api","RPCType","import_api","AlwaysOffSampler","import_api","AlwaysOnSampler","import_api","ParentBasedSampler","_a","context","import_api","TraceIdRatioBasedSampler","context","TimeoutError","Deferred","__read","BindOnceFuture","_a","import_api","init_constants","import_api","init_constants","B3MultiPropagator","context","isTracingSuppressed","import_api","__read","init_constants","B3SinglePropagator","context","isTracingSuppressed","_a","init_types","B3InjectEncoding","init_constants","init_types","B3Propagator","context","isTracingSuppressed","init_esm","init_constants","init_types","context","SUPPRESS_TRACING_KEY","isTracingSuppressed","import_api","init_suppress_tracing","BAGGAGE_KEY_PAIR_SEPARATOR","BAGGAGE_PROPERTIES_SEPARATOR","BAGGAGE_ITEMS_SEPARATOR","BAGGAGE_HEADER","BAGGAGE_MAX_NAME_VALUE_PAIRS","BAGGAGE_MAX_PER_NAME_VALUE_PAIRS","BAGGAGE_MAX_TOTAL_LENGTH","init_constants","serializeKeyPairs","BAGGAGE_ITEMS_SEPARATOR","BAGGAGE_MAX_TOTAL_LENGTH","getKeyPairs","_a","__read","BAGGAGE_PROPERTIES_SEPARATOR","parsePairKeyValue","BAGGAGE_KEY_PAIR_SEPARATOR","import_api","init_constants","import_api","W3CBaggagePropagator","init_W3CBaggagePropagator","init_suppress_tracing","init_constants","init_utils","context","isTracingSuppressed","getKeyPairs","BAGGAGE_MAX_PER_NAME_VALUE_PAIRS","BAGGAGE_MAX_NAME_VALUE_PAIRS","serializeKeyPairs","BAGGAGE_HEADER","BAGGAGE_ITEMS_SEPARATOR","parsePairKeyValue","AnchoredClock","init_anchored_clock","__values","__read","import_api","init_attributes","loggingErrorHandler","stringifyException","flattenException","import_api","init_logging_error_handler","globalErrorHandler","delegateHandler","_a","init_global_error_handler","init_logging_error_handler","loggingErrorHandler","TracesSamplerValues","init_sampling","logLevelMap","env","DEFAULT_ENVIRONMENT","import_api","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","init_environment","init_sampling","TracesSamplerValues","DEFAULT_ENVIRONMENT","init_environment","_globalThis","init_globalThis","init_hex_to_binary","init_hex_to_base64","getIdGenerator","SHARED_BUFFER","SPAN_ID_BYTES","TRACE_ID_BYTES","RandomIdGenerator","init_RandomIdGenerator","init_performance","VERSION","init_version","import_semantic_conventions","_a","SDK_INFO","init_sdk_info","init_version","VERSION","init_timer_util","init_node","init_environment","init_globalThis","init_hex_to_base64","init_RandomIdGenerator","init_performance","init_sdk_info","init_timer_util","init_platform","init_node","MILLISECONDS_TO_NANOSECONDS","SECOND_TO_NANOSECONDS","NANOSECOND_DIGITS","NANOSECOND_DIGITS_IN_MILLIS","init_time","init_platform","init_types","ExportResultCode","init_ExportResult","import_api","__values","CompositePropagator","init_composite","_a","context","validateKey","VALID_KEY_REGEX","validateValue","VALID_VALUE_BASE_REGEX","INVALID_VALUE_COMMA_EQUAL_REGEX","VALID_KEY_CHAR_RANGE","VALID_KEY","VALID_VENDOR_KEY","init_validators","MAX_TRACE_STATE_ITEMS","MAX_TRACE_STATE_LEN","LIST_MEMBERS_SEPARATOR","LIST_MEMBER_KEY_VALUE_SPLITTER","TraceState","init_TraceState","init_validators","validateKey","validateValue","parseTraceParent","TRACE_PARENT_REGEX","import_api","TRACE_PARENT_HEADER","TRACE_STATE_HEADER","VERSION","VERSION_PART","TRACE_ID_PART","PARENT_ID_PART","FLAGS_PART","W3CTraceContextPropagator","init_W3CTraceContextPropagator","init_suppress_tracing","init_TraceState","context","isTracingSuppressed","TraceState","init_IdGenerator","import_api","RPC_METADATA_KEY","RPCType","init_rpc_metadata","import_api","AlwaysOffSampler","init_AlwaysOffSampler","import_api","AlwaysOnSampler","init_AlwaysOnSampler","import_api","ParentBasedSampler","init_ParentBasedSampler","init_global_error_handler","init_AlwaysOffSampler","init_AlwaysOnSampler","globalErrorHandler","AlwaysOnSampler","_a","AlwaysOffSampler","context","import_api","TraceIdRatioBasedSampler","init_TraceIdRatioBasedSampler","context","init_merge","__extends","TimeoutError","init_timeout","init_wrap","Deferred","init_promise","__read","BindOnceFuture","init_callback","init_promise","Deferred","_a","__spreadArray","import_api","init_suppress_tracing","init_esm","init_W3CBaggagePropagator","init_anchored_clock","init_attributes","init_global_error_handler","init_logging_error_handler","init_time","init_types","init_hex_to_binary","init_ExportResult","init_platform","init_composite","init_W3CTraceContextPropagator","init_IdGenerator","init_rpc_metadata","init_AlwaysOffSampler","init_AlwaysOnSampler","init_ParentBasedSampler","init_TraceIdRatioBasedSampler","init_suppress_tracing","init_TraceState","init_environment","init_merge","init_sampling","init_timeout","init_url","init_wrap","init_callback","init_version","import_api","import_semantic_conventions","__values","init_esm","Span","context","__read","SamplingDecision","AlwaysOffSampler","init_AlwaysOffSampler","SamplingDecision","AlwaysOnSampler","init_AlwaysOnSampler","SamplingDecision","import_api","ParentBasedSampler","init_ParentBasedSampler","init_esm","init_AlwaysOffSampler","init_AlwaysOnSampler","globalErrorHandler","AlwaysOnSampler","_a","AlwaysOffSampler","context","import_api","TraceIdRatioBasedSampler","init_TraceIdRatioBasedSampler","context","SamplingDecision","TracesSamplerValues","AlwaysOnSampler","AlwaysOffSampler","ParentBasedSampler","TraceIdRatioBasedSampler","import_api","init_esm","init_AlwaysOffSampler","init_AlwaysOnSampler","init_ParentBasedSampler","init_TraceIdRatioBasedSampler","_a","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","init_esm","import_api","init_esm","BatchSpanProcessorBase","env","BindOnceFuture","ExportResultCode","_a","globalErrorHandler","__extends","BatchSpanProcessor","getIdGenerator","SHARED_BUFFER","SPAN_ID_BYTES","TRACE_ID_BYTES","RandomIdGenerator","init_RandomIdGenerator","init_node","init_RandomIdGenerator","init_platform","init_node","init_esm","init_platform","Tracer","RandomIdGenerator","context","isTracingSuppressed","_a","__values","init_esm","MultiSpanProcessor","globalErrorHandler","context","NoopSpanProcessor","import_api","init_esm","init_platform","ForceFlushState","BasicTracerProvider","_a","CompositePropagator","W3CTraceContextPropagator","W3CBaggagePropagator","__values","init_esm","ConsoleSpanExporter","_a","ExportResultCode","__read","init_esm","InMemorySpanExporter","ExportResultCode","_a","__spreadArray","import_api","init_esm","SimpleSpanProcessor","BindOnceFuture","_a","ExportResultCode","globalErrorHandler","init_types","init_IdGenerator","esm_exports","AlwaysOffSampler","AlwaysOnSampler","ParentBasedSampler","RandomIdGenerator","SamplingDecision","TraceIdRatioBasedSampler","init_esm","init_platform","init_AlwaysOffSampler","init_AlwaysOnSampler","init_ParentBasedSampler","init_TraceIdRatioBasedSampler","init_types","init_IdGenerator","module","SEMVER_SPEC_VERSION","MAX_LENGTH","MAX_SAFE_INTEGER","Number","MAX_SAFE_COMPONENT_LENGTH","MAX_SAFE_BUILD_LENGTH","RELEASE_TYPES","exports","FLAG_INCLUDE_PRERELEASE","FLAG_LOOSE","module","debug","process","env","NODE_DEBUG","test","args","console","error","exports","module","MAX_SAFE_COMPONENT_LENGTH","MAX_SAFE_BUILD_LENGTH","MAX_LENGTH","require","debug","exports","re","safeRe","src","safeSrc","t","R","LETTERDASHNUMBER","safeRegexReplacements","makeSafeRegex","value","token","max","split","join","createToken","name","isGlobal","safe","index","RegExp","undefined","NUMERICIDENTIFIER","NUMERICIDENTIFIERLOOSE","NONNUMERICIDENTIFIER","PRERELEASEIDENTIFIER","PRERELEASEIDENTIFIERLOOSE","BUILDIDENTIFIER","MAINVERSION","PRERELEASE","BUILD","FULLPLAIN","MAINVERSIONLOOSE","PRERELEASELOOSE","LOOSEPLAIN","XRANGEIDENTIFIER","XRANGEIDENTIFIERLOOSE","GTLT","XRANGEPLAIN","XRANGEPLAINLOOSE","COERCEPLAIN","COERCE","COERCEFULL","LONETILDE","tildeTrimReplace","LONECARET","caretTrimReplace","comparatorTrimReplace","module","looseOption","Object","freeze","loose","emptyOpts","parseOptions","options","exports","module","numeric","compareIdentifiers","a","b","anum","test","bnum","rcompareIdentifiers","exports","module","debug","require","MAX_LENGTH","MAX_SAFE_INTEGER","safeRe","re","safeSrc","src","t","parseOptions","compareIdentifiers","SemVer","constructor","version","options","loose","includePrerelease","TypeError","length","m","trim","match","LOOSE","FULL","raw","major","minor","patch","prerelease","split","map","id","test","num","build","format","join","toString","compare","other","compareMain","comparePre","i","a","b","undefined","compareBuild","inc","release","identifier","identifierBase","startsWith","Error","r","RegExp","PRERELEASELOOSE","PRERELEASE","base","Number","push","isNaN","exports","module","SemVer","require","parse","version","options","throwErrors","er","exports","module","parse","require","valid","version","options","v","exports","module","parse","require","clean","version","options","s","trim","replace","exports","module","SemVer","require","inc","version","release","options","identifier","identifierBase","undefined","er","exports","module","parse","require","diff","version1","version2","v1","v2","comparison","compare","v1Higher","highVersion","lowVersion","highHasPre","prerelease","length","lowHasPre","patch","minor","compareMain","prefix","major","exports","module","SemVer","require","major","a","loose","exports","module","SemVer","require","minor","a","loose","exports","module","SemVer","require","patch","a","loose","exports","module","parse","require","prerelease","version","options","parsed","length","exports","module","SemVer","require","compare","a","b","loose","exports","module","compare","require","rcompare","a","b","loose","exports","module","compare","require","compareLoose","a","b","exports","module","SemVer","require","compareBuild","a","b","loose","versionA","versionB","compare","exports","module","compareBuild","require","sort","list","loose","a","b","exports","module","compareBuild","require","rsort","list","loose","sort","a","b","exports","module","compare","require","gt","a","b","loose","exports","module","compare","require","lt","a","b","loose","exports","module","compare","require","eq","a","b","loose","exports","module","compare","require","neq","a","b","loose","exports","module","compare","require","gte","a","b","loose","exports","module","compare","require","lte","a","b","loose","exports","module","eq","require","neq","gt","gte","lt","lte","cmp","a","op","b","loose","version","TypeError","exports","module","SemVer","require","parse","safeRe","re","t","coerce","version","options","String","match","rtl","includePrerelease","COERCEFULL","COERCE","coerceRtlRegex","COERCERTLFULL","COERCERTL","next","exec","index","length","lastIndex","major","minor","patch","prerelease","build","exports","module","LRUCache","constructor","max","map","Map","get","key","value","undefined","delete","set","deleted","size","firstKey","keys","next","exports","module","SPACE_CHARACTERS","Range","constructor","range","options","parseOptions","loose","includePrerelease","raw","Comparator","value","set","formatted","undefined","trim","replace","split","map","r","parseRange","filter","c","length","TypeError","first","isNullSet","isAny","i","comps","k","toString","format","memoOpts","FLAG_INCLUDE_PRERELEASE","FLAG_LOOSE","memoKey","cached","cache","get","hr","re","t","HYPHENRANGELOOSE","HYPHENRANGE","hyphenReplace","debug","COMPARATORTRIM","comparatorTrimReplace","TILDETRIM","tildeTrimReplace","CARETTRIM","caretTrimReplace","rangeList","comp","parseComparator","join","replaceGTE0","match","COMPARATORLOOSE","rangeMap","Map","comparators","size","has","delete","result","values","intersects","some","thisComparators","isSatisfiable","rangeComparators","every","thisComparator","rangeComparator","test","version","SemVer","er","testSet","exports","LRU","require","safeRe","remainingComparators","slice","testComparator","pop","otherComparator","replaceCarets","replaceTildes","replaceXRanges","replaceStars","isX","id","toLowerCase","replaceTilde","TILDELOOSE","TILDE","_","M","m","p","pr","ret","replaceCaret","CARETLOOSE","CARET","z","replaceXRange","XRANGELOOSE","XRANGE","gtlt","xM","xm","xp","anyX","STAR","GTE0PRE","GTE0","incPr","$0","from","fM","fm","fp","fpr","fb","to","tM","tm","tp","tpr","prerelease","semver","ANY","allowed","major","minor","patch","module","ANY","Symbol","Comparator","constructor","comp","options","parseOptions","loose","value","trim","split","join","debug","parse","semver","operator","version","r","re","t","COMPARATORLOOSE","COMPARATOR","m","match","TypeError","undefined","SemVer","toString","test","er","cmp","intersects","Range","includePrerelease","startsWith","includes","exports","require","safeRe","module","Range","require","satisfies","version","range","options","er","test","exports","module","Range","require","toComparators","range","options","set","map","comp","c","value","join","trim","split","exports","module","SemVer","require","Range","maxSatisfying","versions","range","options","max","maxSV","rangeObj","er","forEach","v","test","compare","exports","module","SemVer","require","Range","minSatisfying","versions","range","options","min","minSV","rangeObj","er","forEach","v","test","compare","exports","module","SemVer","require","Range","gt","minVersion","range","loose","minver","test","i","set","length","comparators","setMin","forEach","comparator","compver","semver","version","operator","prerelease","patch","push","raw","format","Error","exports","require_valid","module","Range","require","validRange","range","options","er","exports","module","SemVer","require","Comparator","ANY","Range","satisfies","gt","lt","lte","gte","outside","version","range","hilo","options","gtfn","ltefn","ltfn","comp","ecomp","TypeError","i","set","length","comparators","high","low","forEach","comparator","semver","operator","exports","module","outside","require","gtr","version","range","options","exports","module","outside","require","ltr","version","range","options","exports","module","Range","require","intersects","r1","r2","options","exports","module","satisfies","require","compare","exports","versions","range","options","set","first","prev","v","sort","a","b","version","included","push","ranges","min","max","simplified","join","original","raw","String","length","module","Range","require","Comparator","ANY","satisfies","compare","subset","sub","dom","options","sawNonNull","OUTER","simpleSub","set","simpleDom","isSub","simpleSubset","minimumVersionWithPreRelease","minimumVersion","length","semver","includePrerelease","eqSet","Set","gt","lt","c","operator","higherGT","lowerLT","add","size","gtltComp","eq","String","higher","lower","hasDomLT","hasDomGT","needDomLTPre","prerelease","needDomGTPre","major","minor","patch","a","b","comp","exports","require_semver","module","internalRe","require","constants","SemVer","identifiers","parse","valid","clean","inc","diff","major","minor","patch","prerelease","compare","rcompare","compareLoose","compareBuild","sort","rsort","gt","lt","eq","neq","gte","lte","cmp","coerce","Comparator","Range","satisfies","toComparators","maxSatisfying","minSatisfying","minVersion","validRange","outside","gtr","ltr","intersects","simplifyRange","subset","exports","re","src","tokens","t","SEMVER_SPEC_VERSION","RELEASE_TYPES","compareIdentifiers","rcompareIdentifiers","isTracingSuppressed","context","SUPPRESS_TRACING_KEY","import_api","init_suppress_tracing","BAGGAGE_KEY_PAIR_SEPARATOR","BAGGAGE_PROPERTIES_SEPARATOR","BAGGAGE_ITEMS_SEPARATOR","BAGGAGE_HEADER","BAGGAGE_MAX_NAME_VALUE_PAIRS","BAGGAGE_MAX_PER_NAME_VALUE_PAIRS","BAGGAGE_MAX_TOTAL_LENGTH","init_constants","serializeKeyPairs","BAGGAGE_ITEMS_SEPARATOR","BAGGAGE_MAX_TOTAL_LENGTH","getKeyPairs","_a","__read","BAGGAGE_PROPERTIES_SEPARATOR","parsePairKeyValue","BAGGAGE_KEY_PAIR_SEPARATOR","import_api","init_constants","import_api","W3CBaggagePropagator","init_W3CBaggagePropagator","init_suppress_tracing","init_constants","init_utils","context","isTracingSuppressed","getKeyPairs","BAGGAGE_MAX_PER_NAME_VALUE_PAIRS","BAGGAGE_MAX_NAME_VALUE_PAIRS","serializeKeyPairs","BAGGAGE_HEADER","BAGGAGE_ITEMS_SEPARATOR","parsePairKeyValue","AnchoredClock","init_anchored_clock","import_api","init_attributes","loggingErrorHandler","stringifyException","flattenException","import_api","init_logging_error_handler","globalErrorHandler","delegateHandler","_a","init_global_error_handler","init_logging_error_handler","loggingErrorHandler","TracesSamplerValues","init_sampling","import_api","DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT","DEFAULT_ATTRIBUTE_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT","DEFAULT_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT","DEFAULT_ENVIRONMENT","logLevelMap","init_environment","init_sampling","TracesSamplerValues","_globalThis","init_globalThis","init_hex_to_binary","init_hex_to_base64","getIdGenerator","SHARED_BUFFER","SPAN_ID_BYTES","TRACE_ID_BYTES","RandomIdGenerator","init_RandomIdGenerator","init_performance","VERSION","init_version","import_semantic_conventions","_a","SDK_INFO","init_sdk_info","init_version","VERSION","init_timer_util","init_node","init_globalThis","init_hex_to_base64","init_RandomIdGenerator","init_performance","init_sdk_info","init_timer_util","init_platform","init_node","NANOSECOND_DIGITS","NANOSECOND_DIGITS_IN_MILLIS","MILLISECONDS_TO_NANOSECONDS","SECOND_TO_NANOSECONDS","init_time","init_types","ExportResultCode","init_ExportResult","import_api","__values","CompositePropagator","init_composite","_a","context","validateKey","VALID_KEY_REGEX","validateValue","VALID_VALUE_BASE_REGEX","INVALID_VALUE_COMMA_EQUAL_REGEX","VALID_KEY_CHAR_RANGE","VALID_KEY","VALID_VENDOR_KEY","init_validators","MAX_TRACE_STATE_ITEMS","MAX_TRACE_STATE_LEN","LIST_MEMBERS_SEPARATOR","LIST_MEMBER_KEY_VALUE_SPLITTER","TraceState","init_TraceState","init_validators","validateKey","validateValue","parseTraceParent","TRACE_PARENT_REGEX","import_api","TRACE_PARENT_HEADER","TRACE_STATE_HEADER","VERSION","VERSION_PART","TRACE_ID_PART","PARENT_ID_PART","FLAGS_PART","W3CTraceContextPropagator","init_W3CTraceContextPropagator","init_suppress_tracing","init_TraceState","context","isTracingSuppressed","TraceState","init_IdGenerator","import_api","RPC_METADATA_KEY","RPCType","init_rpc_metadata","import_api","AlwaysOffSampler","init_AlwaysOffSampler","import_api","AlwaysOnSampler","init_AlwaysOnSampler","import_api","ParentBasedSampler","init_ParentBasedSampler","init_global_error_handler","init_AlwaysOffSampler","init_AlwaysOnSampler","globalErrorHandler","AlwaysOnSampler","_a","AlwaysOffSampler","context","import_api","TraceIdRatioBasedSampler","init_TraceIdRatioBasedSampler","context","init_merge","__extends","TimeoutError","init_timeout","init_wrap","Deferred","init_promise","__read","BindOnceFuture","init_callback","init_promise","Deferred","_a","__spreadArray","init_esm","init_W3CBaggagePropagator","init_anchored_clock","init_attributes","init_global_error_handler","init_logging_error_handler","init_time","init_types","init_hex_to_binary","init_ExportResult","init_platform","init_composite","init_W3CTraceContextPropagator","init_IdGenerator","init_rpc_metadata","init_AlwaysOffSampler","init_AlwaysOnSampler","init_ParentBasedSampler","init_TraceIdRatioBasedSampler","init_suppress_tracing","init_TraceState","init_environment","init_merge","init_sampling","init_timeout","init_url","init_wrap","init_callback","init_version","_a","__read","import_api","__values","init_esm","JaegerPropagator","context","isTracingSuppressed","esm_exports","init_esm","module","module","fs","require","path","os","crypto","packageJson","version","LINE","parse","src","obj","lines","toString","replace","match","exec","key","value","trim","maybeQuote","_parseVault","options","vaultPath","_vaultPath","result","DotenvModule","configDotenv","parsed","err","Error","code","keys","_dotenvKey","split","length","decrypted","i","attrs","_instructions","decrypt","ciphertext","error","_warn","message","console","log","_debug","DOTENV_KEY","process","env","dotenvKey","uri","URL","password","environment","searchParams","get","environmentKey","toUpperCase","possibleVaultPath","Array","isArray","filepath","existsSync","endsWith","resolve","cwd","_resolveHome","envPath","join","homedir","slice","_configVault","debug","Boolean","processEnv","populate","dotenvPath","encoding","optionPaths","push","lastError","parsedAll","readFileSync","e","config","encrypted","keyStr","Buffer","from","nonce","subarray","authTag","aesgcm","createDecipheriv","setAuthTag","update","final","isRange","RangeError","invalidKeyLength","decryptionFailed","override","Object","prototype","hasOwnProperty","call","exports","module","options","process","env","DOTENV_CONFIG_ENCODING","encoding","DOTENV_CONFIG_PATH","path","DOTENV_CONFIG_DEBUG","debug","DOTENV_CONFIG_OVERRIDE","override","DOTENV_CONFIG_DOTENV_KEY","DOTENV_KEY","exports","module","re","exports","optionMatcher","args","reduce","acc","cur","matches","match","Span","DependencyContainer","registry","Map","singletons","register","token","myClass","options","set","type","singleton","registerValue","value","resolve","target","injectMetadata","Reflect","getOwnMetadata","paramCount","Object","keys","length","params","Array","from","_","index","Error","name","resolveToken","registration","get","has","instance","Inject","_propertyKey","parameterIndex","constructor","existingInjectedParams","defineMetadata","GlobalErrorHandler","errorNotifier","constructor","env","DependencyContainer","resolveToken","register","process","on","err","notify","ENVIRONMENT","exit","reason","Error","String","ApiErrorEnum","ApplicationError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","APPLICATION","occurredAt","Date","ConflictError","Error","props","conflictProps","constructor","code","errorCode","ApiErrorEnum","APPLICATION","message","occurredAt","Date","DomainError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","DOMAIN","occurredAt","Date","InfraError","Error","props","constructor","message","code","errorCode","ApiErrorEnum","INFRA","occurredAt","Date","ValidationError","Error","props","constructor","errors","code","errorCode","ApiErrorEnum","VALIDATOR","message","occurredAt","Date","import_reflect_metadata","BaseController","errorNotifier","constructor","DependencyContainer","resolveToken","success","dto","code","data","noContent","undefined","created","paginated","buildContextError","request","env","process","ENVIRONMENT","body","headers","params","query","failure","error","context","ConflictError","props","message","errorCode","occurredAt","items","Array","isArray","conflictProps","DomainError","ApplicationError","InfraError","ValidationError","errors","SHOULD_NOTIFY_ERROR","notify","execute","routeMetadata","Reflect","getMetadata","middlewares","processedRequest","length","middleware","handle","Controller","method","path","middlewares","target","prototype","BaseController","Error","name","Reflect","defineMetadata","UniqueObjectId","value","constructor","ObjectId","toString","toValue","equals","id","EntityObject","_id","props","id","createdAt","date","updatedAt","touch","Date","UniqueObjectId","equals","entity","AggregateObjectRoot","EntityObject","UniqueEntityId","value","constructor","randomUUID","toString","toValue","equals","id","Entity","_id","props","id","createdAt","date","updatedAt","touch","Date","UniqueEntityId","equals","entity","AggregateRoot","Entity","ValueObject","props","WatchedList","currentItems","initial","new","removed","updated","constructor","initialItems","getItems","getNewItems","getRemovedItems","getUpdatedItems","addUpdatedItem","item","push","isCurrentItem","filter","v","compareItems","length","isNewItem","isRemovedItem","removeFromNew","removeFromCurrent","removeFromRemoved","wasAddedInitially","exists","add","remove","update","items","newItems","a","some","b","removedItems","updatedItems","getTakeAndSkip","size","page","take","Number","skip","ErrorResponseCode","import_reflect_metadata","validateControllerMetadata","controller","metadata","Reflect","getMetadata","constructor","Error","name","ExpressAdapter","instance","server","constructor","env","logger","express","use","cors","json","limit","urlencoded","extended","disable","registerRoute","controllerClass","metadata","validateControllerMetadata","method","path","request","response","requestData","body","params","headers","query","output","execute","status","code","data","ErrorResponseCode","NO_CONTENT_BODY","err","error","failure","ENVIRONMENT","url","NO_CONTENT_ERROR","startServer","port","Promise","resolve","listen","info","closeServer","reject","close","import_cors","FastifyAdapter","instance","constructor","env","logger","fastify","bodyLimit","querystringParser","str","qs","parse","loggerInstance","ENVIRONMENT","register","cors","registerRoute","controllerClass","metadata","validateControllerMetadata","method","path","request","reply","requestData","body","params","headers","query","output","execute","status","code","send","data","ErrorResponseCode","NO_CONTENT_BODY","err","error","failure","url","NO_CONTENT_ERROR","startServer","port","listen","NODE_ENV","info","closeServer","close","DiscordNotifier","webhook","constructor","options","Webhook","url","notify","error","context","embed","MessageBuilder","setTitle","addField","message","slice","request","method","JSON","stringify","params","query","headers","body","stack","setFooter","env","setTimestamp","send","NotificationErrorInMemory","errors","notify","error","context","console","push","message","SentryNotifier","constructor","options","Sentry","init","dsn","environment","attachStacktrace","tracesSampleRate","maxBreadcrumbs","debug","notify","error","context","withScope","scope","setLevel","env","setTag","user","setUser","id","username","name","email","request","body","query","params","headers","method","url","requestId","setContext","captureException","NotificationFactory","define","env","definitions","defaultDefinition","test","defineProvider","development","staging","production","provider","NotificationErrorInMemory","DiscordNotifier","SentryNotifier","ZodMapError","mapCommon","error","type","code","path","join","property","pop","propertyType","expected","receivedValue","received","message","mapInvalidUnion","errors","unionErrors","flat","map","err","issues","item","mapInvalidType","mapErrorsFactory","mapErrors","standardizedErrors","Map","forEach","keyError","get","propertyErrors","push","set","location","Array","from","arr","ZodValidator","constructor","zodSchema","validate","requestHttp","errors","data","headersData","error","headersErrors","headers","shape","safeParseAsync","path","push","paramsData","paramsErrors","params","queryData","queryErrors","query","bodyData","bodyErrors","body","length","ValidationError","ZodMapError","mapErrors","zodValidator","schema","request","validator","ZodValidator","validatedRequest","validate","WinstonOtelFastify","logger","consoleLogger","level","otelEnabled","constructor","process","env","OTEL_ENABLE","LOG_LEVEL","logs","getLogger","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","transports","NODE_ENV","winston","Console","silent","createLogger","format","combine","timestamp","info","span","opentelemetry","trace","getActiveSpan","spanId","spanContext","traceId","json","bodyIsFastifyRequest","body","method","undefined","bodyIsFastifyReply","statusCode","buildMessage","req","url","res","request","elapsedTime","logMessage","severityNumber","severityText","message","toLowerCase","emit","SeverityNumber","INFO","error","ERROR","debug","DEBUG","fatal","FATAL","warn","WARN","TRACE","child","import_api","context","import_api","CompositePropagator","_a","context","import_api","TraceState","W3CTraceContextPropagator","context","import_resources","import_semantic_conventions","OpenTelemetry","sdk","constructor","env","resource","Resource","SEMRESATTRS_SERVICE_NAME","OTEL_SERVICE_NAME","SEMRESATTRS_SERVICE_VERSION","OTEL_SERVICE_VERSION","SEMRESATTRS_DEPLOYMENT_ENVIRONMENT","ENVIRONMENT","traceExporter","OTLPTraceExporter","url","OTEL_OTLP_TRACES_EXPORTER_URL","headers","logExporter","OTLPLogExporter","OTEL_OTLP_LOGS_EXPORTER_URL","metricExporter","OTLPMetricExporter","OTEL_OTLP_METRICS_EXPORTER_URL","NodeSDK","textMapPropagator","CompositePropagator","propagators","W3CTraceContextPropagator","spanProcessor","BatchSpanProcessor","maxQueueSize","maxExportBatchSize","scheduledDelayMillis","exportTimeoutMillis","logRecordProcessor","BatchLogRecordProcessor","metricReader","PeriodicExportingMetricReader","exporter","exportIntervalMillis","startSdk","start","console","log","error","shutdown","import_api","import_reflect_metadata","Span","target","propertyKey","descriptor","process","env","OTEL_ENABLE","originalMethod","value","args","tracer","opentelemetry","trace","getTracer","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","className","constructor","name","methodName","String","spanName","startActiveSpan","span","result","apply","Promise","awaitedResult","addEvent","end","error","handleSpanError","errorMessage","Error","message","recordException","setStatus","code","SpanStatusCode","ERROR","import_api","TracerGatewayOpentelemetry","addEvent","name","attributes","process","env","OTEL_ENABLE","span","opentelemetry","trace","getActiveSpan","setAttribute","key","value","require","config","Object","assign","process","argv","baseEnvSchema","z","object","NODE_ENV","enum","default","ENVIRONMENT","PORT","coerce","number","SHOULD_NOTIFY_ERROR","boolean","SENTRY_DSN","string","optional","DISCORD_WEBHOOK_URL","LOG_LEVEL","OTEL_ENABLE","OTEL_SERVICE_NAME","OTEL_SERVICE_VERSION","OTEL_OTLP_TRACES_EXPORTER_URL","url","OTEL_OTLP_LOGS_EXPORTER_URL","OTEL_OTLP_METRICS_EXPORTER_URL"]}