@wix/cli 1.1.162 → 1.1.163
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.
- package/build/{ConnectWixVibeCommand-GZM2BJVW.js → ConnectWixVibeCommand-UMLGR2FM.js} +8 -8
- package/build/{DevCommand-IHLJIGCS.js → DevCommand-NJ4GKDIK.js} +11 -11
- package/build/{DevCommand-MTZ46PZQ.js → DevCommand-X7Z7FL7S.js} +10 -10
- package/build/{DevCommand-POGXYBHH.js → DevCommand-YAX65RZ5.js} +8 -8
- package/build/{EnvPullCommand-OXO3VW3F.js → EnvPullCommand-76YK7R5I.js} +5 -5
- package/build/{EnvRemoveCommand-3QDI5QXP.js → EnvRemoveCommand-Q7QVOOKC.js} +4 -4
- package/build/{EnvSetCommand-Y4JMQX5W.js → EnvSetCommand-Z4PSCJRU.js} +4 -4
- package/build/{GenerateCommand-EFRVZD4J.js → GenerateCommand-ZCSTKD7K.js} +5 -5
- package/build/{InstallCommand-LJUPLKMR.js → InstallCommand-J5L2JJG5.js} +7 -7
- package/build/{LoginCommand-2EOCKUKN.js → LoginCommand-IUGNILLA.js} +3 -3
- package/build/{LogoutCommand-ZVIHWCRX.js → LogoutCommand-ZDVUWBYK.js} +2 -2
- package/build/{PreviewCommand-O4CKUQVC.js → PreviewCommand-6E5SC6VB.js} +12 -12
- package/build/{PreviewCommand-T5AARIDY.js → PreviewCommand-JIQVZ5TB.js} +11 -11
- package/build/{PreviewCommand-MGYVAWPC.js → PreviewCommand-XP2EY5IK.js} +10 -10
- package/build/{PromoteCommand-MCKKRXGO.js → PromoteCommand-LYK7MTM5.js} +11 -11
- package/build/{PublishCommand-7UDY3YX5.js → PublishCommand-6IFBEQTG.js} +10 -10
- package/build/{ReleaseCommand-OX2OUZ7W.js → ReleaseCommand-Q66266SD.js} +12 -12
- package/build/{TranslationPullCommand-OW5P7WQQ.js → TranslationPullCommand-2LOFGIL7.js} +5 -5
- package/build/{TranslationPushCommand-4GYA7S5J.js → TranslationPushCommand-LJI7GADK.js} +6 -6
- package/build/{UninstallCommand-BAQJ6HNB.js → UninstallCommand-56BO2ZXY.js} +7 -7
- package/build/{chunk-GSO2OENC.js → chunk-2CSZPHMM.js} +3 -3
- package/build/{chunk-GFZU5OPF.js → chunk-2NT5QHJ7.js} +4 -4
- package/build/{chunk-5KG46TLQ.js → chunk-3QMFB7WM.js} +3 -3
- package/build/{chunk-E4VJBLJV.js → chunk-5ITU5VHX.js} +2 -2
- package/build/{chunk-GPV26EWK.js → chunk-APNV4UYE.js} +4 -4
- package/build/{chunk-XMXQ64GU.js → chunk-BKTO7E3Z.js} +2 -2
- package/build/{chunk-DPJYSQSN.js → chunk-EJZMJKA5.js} +2 -2
- package/build/{chunk-P7DWJGFN.js → chunk-EQGEAZOM.js} +2 -2
- package/build/{chunk-QIB67OE6.js → chunk-ESDJRY2Z.js} +3 -3
- package/build/{chunk-ZYUKHN7N.js → chunk-FX2WV2OH.js} +3 -3
- package/build/{chunk-REKK2OPM.js → chunk-GY43SGEZ.js} +3 -3
- package/build/{chunk-CEMO64GF.js → chunk-HX4KSBXM.js} +2 -2
- package/build/{chunk-HRZWURZ7.js → chunk-JJHV3G5M.js} +2 -2
- package/build/{chunk-G6P33ZGR.js → chunk-LZ5P6HUX.js} +2 -2
- package/build/{chunk-SSQMNRLT.js → chunk-OCTQJWUR.js} +4 -4
- package/build/{chunk-JYJC52KV.js → chunk-PL7575CU.js} +4 -4
- package/build/{chunk-MQC2BZ7W.js → chunk-PV7STX76.js} +3 -3
- package/build/{chunk-LEKNX4UD.js → chunk-QQPMVHRI.js} +3 -3
- package/build/{chunk-5EDINUD6.js → chunk-RY4MIN44.js} +2 -2
- package/build/{chunk-ZJ2JSHSQ.js → chunk-SE5KG52F.js} +3 -3
- package/build/{chunk-HMYE5P5S.js → chunk-TADSDOPD.js} +2 -2
- package/build/{chunk-O7YLCWI5.js → chunk-TYB2YKMU.js} +4 -4
- package/build/{chunk-H5IYD2UO.js → chunk-UIXNGYK2.js} +2 -2
- package/build/{chunk-RSL55MAQ.js → chunk-UWD6RUSL.js} +2 -2
- package/build/{chunk-RSL55MAQ.js.map → chunk-UWD6RUSL.js.map} +1 -1
- package/build/{chunk-EICIL6XT.js → chunk-VBTVAZDV.js} +2 -2
- package/build/{chunk-AAC7Q5IA.js → chunk-XMIBOQUL.js} +3 -3
- package/build/{chunk-SOOXGPJM.js → chunk-Y3AXMJ7X.js} +4 -4
- package/build/{chunk-7PGFDSUE.js → chunk-YATWD63H.js} +2 -2
- package/build/{chunk-3YJXKQBT.js → chunk-YO4463YZ.js} +6 -6
- package/build/{chunk-JSGUJDS3.js → chunk-Z4MSM2PE.js} +47 -4
- package/build/chunk-Z4MSM2PE.js.map +1 -0
- package/build/{chunk-L44BZKAP.js → chunk-ZHKTECUQ.js} +6 -6
- package/build/{dev-ZDHKXB6F.js → dev-B47G4HDM.js} +12 -12
- package/build/{env-pull-QFBMIIRV.js → env-pull-PFCZNPI3.js} +6 -6
- package/build/index.js +14 -14
- package/build/{install-MPMCQDPG.js → install-ODJTCXDA.js} +6 -6
- package/build/{preview-YKV5EWM4.js → preview-JRDWP2F6.js} +12 -12
- package/build/{publish-QOTPZCMC.js → publish-WL7UYWAP.js} +8 -8
- package/build/{render-command-XHK2T2CY.js → render-command-5JKHVZXG.js} +4 -4
- package/build/{render-command-OY2PNJAU.js → render-command-AWTB2IKF.js} +3 -3
- package/build/{render-command-I756BW6A.js → render-command-JWTMINS6.js} +3 -3
- package/build/{render-command-B33ZAPE2.js → render-command-LYDJJCHV.js} +3 -3
- package/build/{render-command-AENKFQBD.js → render-command-YVHJYNBG.js} +4 -4
- package/build/{src-RSS2KIVG.js → src-4HB2ZEJM.js} +8 -8
- package/build/{src-PSLCPHEL.js → src-CCP2TRFT.js} +28 -28
- package/build/{src-COWESTMT.js → src-NF4CBGMT.js} +3 -3
- package/build/{src-NFPLXAQF.js → src-R5WPSRJQ.js} +2 -2
- package/build/{src-NZ5MTHG5.js → src-XBBZMRFI.js} +11 -11
- package/build/{sync-types-TG7SH3UH.js → sync-types-RDSLNXPT.js} +5 -5
- package/build/{translation-pull-SORARTJZ.js → translation-pull-DG23ZXR3.js} +6 -6
- package/build/{translation-push-ZAHQXD2A.js → translation-push-S63MASSP.js} +7 -7
- package/build/{uninstall-432A7W5U.js → uninstall-VFXPCCJ5.js} +6 -6
- package/package.json +2 -2
- package/build/chunk-JSGUJDS3.js.map +0 -1
- /package/build/{ConnectWixVibeCommand-GZM2BJVW.js.map → ConnectWixVibeCommand-UMLGR2FM.js.map} +0 -0
- /package/build/{DevCommand-IHLJIGCS.js.map → DevCommand-NJ4GKDIK.js.map} +0 -0
- /package/build/{DevCommand-MTZ46PZQ.js.map → DevCommand-X7Z7FL7S.js.map} +0 -0
- /package/build/{DevCommand-POGXYBHH.js.map → DevCommand-YAX65RZ5.js.map} +0 -0
- /package/build/{EnvPullCommand-OXO3VW3F.js.map → EnvPullCommand-76YK7R5I.js.map} +0 -0
- /package/build/{EnvRemoveCommand-3QDI5QXP.js.map → EnvRemoveCommand-Q7QVOOKC.js.map} +0 -0
- /package/build/{EnvSetCommand-Y4JMQX5W.js.map → EnvSetCommand-Z4PSCJRU.js.map} +0 -0
- /package/build/{GenerateCommand-EFRVZD4J.js.map → GenerateCommand-ZCSTKD7K.js.map} +0 -0
- /package/build/{InstallCommand-LJUPLKMR.js.map → InstallCommand-J5L2JJG5.js.map} +0 -0
- /package/build/{LoginCommand-2EOCKUKN.js.map → LoginCommand-IUGNILLA.js.map} +0 -0
- /package/build/{LogoutCommand-ZVIHWCRX.js.map → LogoutCommand-ZDVUWBYK.js.map} +0 -0
- /package/build/{PreviewCommand-O4CKUQVC.js.map → PreviewCommand-6E5SC6VB.js.map} +0 -0
- /package/build/{PreviewCommand-T5AARIDY.js.map → PreviewCommand-JIQVZ5TB.js.map} +0 -0
- /package/build/{PreviewCommand-MGYVAWPC.js.map → PreviewCommand-XP2EY5IK.js.map} +0 -0
- /package/build/{PromoteCommand-MCKKRXGO.js.map → PromoteCommand-LYK7MTM5.js.map} +0 -0
- /package/build/{PublishCommand-7UDY3YX5.js.map → PublishCommand-6IFBEQTG.js.map} +0 -0
- /package/build/{ReleaseCommand-OX2OUZ7W.js.map → ReleaseCommand-Q66266SD.js.map} +0 -0
- /package/build/{TranslationPullCommand-OW5P7WQQ.js.map → TranslationPullCommand-2LOFGIL7.js.map} +0 -0
- /package/build/{TranslationPushCommand-4GYA7S5J.js.map → TranslationPushCommand-LJI7GADK.js.map} +0 -0
- /package/build/{UninstallCommand-BAQJ6HNB.js.map → UninstallCommand-56BO2ZXY.js.map} +0 -0
- /package/build/{chunk-GSO2OENC.js.map → chunk-2CSZPHMM.js.map} +0 -0
- /package/build/{chunk-GFZU5OPF.js.map → chunk-2NT5QHJ7.js.map} +0 -0
- /package/build/{chunk-5KG46TLQ.js.map → chunk-3QMFB7WM.js.map} +0 -0
- /package/build/{chunk-E4VJBLJV.js.map → chunk-5ITU5VHX.js.map} +0 -0
- /package/build/{chunk-GPV26EWK.js.map → chunk-APNV4UYE.js.map} +0 -0
- /package/build/{chunk-XMXQ64GU.js.map → chunk-BKTO7E3Z.js.map} +0 -0
- /package/build/{chunk-DPJYSQSN.js.map → chunk-EJZMJKA5.js.map} +0 -0
- /package/build/{chunk-P7DWJGFN.js.map → chunk-EQGEAZOM.js.map} +0 -0
- /package/build/{chunk-QIB67OE6.js.map → chunk-ESDJRY2Z.js.map} +0 -0
- /package/build/{chunk-ZYUKHN7N.js.map → chunk-FX2WV2OH.js.map} +0 -0
- /package/build/{chunk-REKK2OPM.js.map → chunk-GY43SGEZ.js.map} +0 -0
- /package/build/{chunk-CEMO64GF.js.map → chunk-HX4KSBXM.js.map} +0 -0
- /package/build/{chunk-HRZWURZ7.js.map → chunk-JJHV3G5M.js.map} +0 -0
- /package/build/{chunk-G6P33ZGR.js.map → chunk-LZ5P6HUX.js.map} +0 -0
- /package/build/{chunk-SSQMNRLT.js.map → chunk-OCTQJWUR.js.map} +0 -0
- /package/build/{chunk-JYJC52KV.js.map → chunk-PL7575CU.js.map} +0 -0
- /package/build/{chunk-MQC2BZ7W.js.map → chunk-PV7STX76.js.map} +0 -0
- /package/build/{chunk-LEKNX4UD.js.map → chunk-QQPMVHRI.js.map} +0 -0
- /package/build/{chunk-5EDINUD6.js.map → chunk-RY4MIN44.js.map} +0 -0
- /package/build/{chunk-ZJ2JSHSQ.js.map → chunk-SE5KG52F.js.map} +0 -0
- /package/build/{chunk-HMYE5P5S.js.map → chunk-TADSDOPD.js.map} +0 -0
- /package/build/{chunk-O7YLCWI5.js.map → chunk-TYB2YKMU.js.map} +0 -0
- /package/build/{chunk-H5IYD2UO.js.map → chunk-UIXNGYK2.js.map} +0 -0
- /package/build/{chunk-EICIL6XT.js.map → chunk-VBTVAZDV.js.map} +0 -0
- /package/build/{chunk-AAC7Q5IA.js.map → chunk-XMIBOQUL.js.map} +0 -0
- /package/build/{chunk-SOOXGPJM.js.map → chunk-Y3AXMJ7X.js.map} +0 -0
- /package/build/{chunk-7PGFDSUE.js.map → chunk-YATWD63H.js.map} +0 -0
- /package/build/{chunk-3YJXKQBT.js.map → chunk-YO4463YZ.js.map} +0 -0
- /package/build/{chunk-L44BZKAP.js.map → chunk-ZHKTECUQ.js.map} +0 -0
- /package/build/{dev-ZDHKXB6F.js.map → dev-B47G4HDM.js.map} +0 -0
- /package/build/{env-pull-QFBMIIRV.js.map → env-pull-PFCZNPI3.js.map} +0 -0
- /package/build/{install-MPMCQDPG.js.map → install-ODJTCXDA.js.map} +0 -0
- /package/build/{preview-YKV5EWM4.js.map → preview-JRDWP2F6.js.map} +0 -0
- /package/build/{publish-QOTPZCMC.js.map → publish-WL7UYWAP.js.map} +0 -0
- /package/build/{render-command-XHK2T2CY.js.map → render-command-5JKHVZXG.js.map} +0 -0
- /package/build/{render-command-OY2PNJAU.js.map → render-command-AWTB2IKF.js.map} +0 -0
- /package/build/{render-command-I756BW6A.js.map → render-command-JWTMINS6.js.map} +0 -0
- /package/build/{render-command-B33ZAPE2.js.map → render-command-LYDJJCHV.js.map} +0 -0
- /package/build/{render-command-AENKFQBD.js.map → render-command-YVHJYNBG.js.map} +0 -0
- /package/build/{src-RSS2KIVG.js.map → src-4HB2ZEJM.js.map} +0 -0
- /package/build/{src-PSLCPHEL.js.map → src-CCP2TRFT.js.map} +0 -0
- /package/build/{src-COWESTMT.js.map → src-NF4CBGMT.js.map} +0 -0
- /package/build/{src-NFPLXAQF.js.map → src-R5WPSRJQ.js.map} +0 -0
- /package/build/{src-NZ5MTHG5.js.map → src-XBBZMRFI.js.map} +0 -0
- /package/build/{sync-types-TG7SH3UH.js.map → sync-types-RDSLNXPT.js.map} +0 -0
- /package/build/{translation-pull-SORARTJZ.js.map → translation-pull-DG23ZXR3.js.map} +0 -0
- /package/build/{translation-push-ZAHQXD2A.js.map → translation-push-S63MASSP.js.map} +0 -0
- /package/build/{uninstall-432A7W5U.js.map → uninstall-VFXPCCJ5.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/p-retry/node_modules/retry/lib/retry_operation.js","../../../node_modules/p-retry/node_modules/retry/lib/retry.js","../../../node_modules/p-retry/node_modules/retry/index.js","../../../node_modules/@opentelemetry/core/src/trace/suppress-tracing.ts","../../../node_modules/@opentelemetry/core/src/baggage/constants.ts","../../../node_modules/@opentelemetry/core/src/baggage/utils.ts","../../../node_modules/@opentelemetry/core/src/baggage/propagation/W3CBaggagePropagator.ts","../../../node_modules/@opentelemetry/core/src/common/anchored-clock.ts","../../../node_modules/@opentelemetry/core/src/common/attributes.ts","../../../node_modules/@opentelemetry/core/src/common/logging-error-handler.ts","../../../node_modules/@opentelemetry/core/src/common/global-error-handler.ts","../../../node_modules/@opentelemetry/core/src/utils/sampling.ts","../../../node_modules/@opentelemetry/core/src/utils/environment.ts","../../../node_modules/@opentelemetry/core/src/platform/node/environment.ts","../../../node_modules/@opentelemetry/core/src/platform/node/globalThis.ts","../../../node_modules/@opentelemetry/core/src/common/hex-to-binary.ts","../../../node_modules/@opentelemetry/core/src/platform/node/hex-to-base64.ts","../../../node_modules/@opentelemetry/core/src/platform/node/RandomIdGenerator.ts","../../../node_modules/@opentelemetry/core/src/platform/node/performance.ts","../../../node_modules/@opentelemetry/core/src/version.ts","../../../node_modules/@opentelemetry/core/src/platform/node/sdk-info.ts","../../../node_modules/@opentelemetry/core/src/platform/node/timer-util.ts","../../../node_modules/@opentelemetry/core/src/platform/node/index.ts","../../../node_modules/@opentelemetry/core/src/platform/index.ts","../../../node_modules/@opentelemetry/core/src/common/time.ts","../../../node_modules/@opentelemetry/core/src/common/types.ts","../../../node_modules/@opentelemetry/core/src/ExportResult.ts","../../../node_modules/@opentelemetry/core/src/propagation/composite.ts","../../../node_modules/@opentelemetry/core/src/internal/validators.ts","../../../node_modules/@opentelemetry/core/src/trace/TraceState.ts","../../../node_modules/@opentelemetry/core/src/trace/W3CTraceContextPropagator.ts","../../../node_modules/@opentelemetry/core/src/trace/IdGenerator.ts","../../../node_modules/@opentelemetry/core/src/trace/rpc-metadata.ts","../../../node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOffSampler.ts","../../../node_modules/@opentelemetry/core/src/trace/sampler/AlwaysOnSampler.ts","../../../node_modules/@opentelemetry/core/src/trace/sampler/ParentBasedSampler.ts","../../../node_modules/@opentelemetry/core/src/trace/sampler/TraceIdRatioBasedSampler.ts","../../../node_modules/@opentelemetry/core/src/utils/lodash.merge.ts","../../../node_modules/@opentelemetry/core/src/utils/merge.ts","../../../node_modules/@opentelemetry/core/src/utils/timeout.ts","../../../node_modules/@opentelemetry/core/src/utils/url.ts","../../../node_modules/@opentelemetry/core/src/utils/wrap.ts","../../../node_modules/@opentelemetry/core/src/utils/promise.ts","../../../node_modules/@opentelemetry/core/src/utils/callback.ts","../../../node_modules/@opentelemetry/core/src/internal/exporter.ts","../../../node_modules/@opentelemetry/core/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/instrumentation-http/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-http/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-http/src/version.ts","../../../node_modules/@opentelemetry/api-logs/src/types/Logger.ts","../../../node_modules/@opentelemetry/api-logs/src/types/LoggerProvider.ts","../../../node_modules/@opentelemetry/api-logs/src/types/LogRecord.ts","../../../node_modules/@opentelemetry/api-logs/build/esm/types/LoggerOptions.js","../../../node_modules/@opentelemetry/api-logs/src/types/AnyValue.ts","../../../node_modules/@opentelemetry/api-logs/src/NoopLogger.ts","../../../node_modules/@opentelemetry/api-logs/src/NoopLoggerProvider.ts","../../../node_modules/@opentelemetry/api-logs/src/platform/node/globalThis.ts","../../../node_modules/@opentelemetry/api-logs/src/platform/node/index.ts","../../../node_modules/@opentelemetry/api-logs/src/platform/index.ts","../../../node_modules/@opentelemetry/api-logs/src/internal/global-utils.ts","../../../node_modules/@opentelemetry/api-logs/src/api/logs.ts","../../../node_modules/@opentelemetry/api-logs/src/index.ts","../../../node_modules/@opentelemetry/instrumentation/src/autoLoaderUtils.ts","../../../node_modules/@opentelemetry/instrumentation/src/autoLoader.ts","../../../node_modules/shimmer/index.js","../../../node_modules/@opentelemetry/instrumentation/src/instrumentation.ts","../../../node_modules/resolve/lib/homedir.js","../../../node_modules/resolve/lib/caller.js","../../../node_modules/path-parse/index.js","../../../node_modules/resolve/lib/node-modules-paths.js","../../../node_modules/resolve/lib/normalize-options.js","../../../node_modules/function-bind/implementation.js","../../../node_modules/function-bind/index.js","../../../node_modules/hasown/index.js","../../../node_modules/is-core-module/core.json","../../../node_modules/is-core-module/index.js","../../../node_modules/resolve/lib/async.js","../../../node_modules/resolve/lib/core.json","../../../node_modules/resolve/lib/core.js","../../../node_modules/resolve/lib/is-core.js","../../../node_modules/resolve/lib/sync.js","../../../node_modules/resolve/index.js","../../../node_modules/module-details-from-path/index.js","../../../node_modules/require-in-the-middle/package.json","../../../node_modules/require-in-the-middle/index.js","../../../node_modules/@opentelemetry/instrumentation/src/platform/node/ModuleNameTrie.ts","../../../node_modules/@opentelemetry/instrumentation/src/platform/node/RequireInTheMiddleSingleton.ts","../../../node_modules/import-in-the-middle/lib/register.js","../../../node_modules/import-in-the-middle/index.js","../../../node_modules/@opentelemetry/instrumentation/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation/src/platform/node/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation/src/platform/node/normalize.ts","../../../node_modules/@opentelemetry/instrumentation/src/platform/node/index.ts","../../../node_modules/@opentelemetry/instrumentation/src/platform/index.ts","../../../node_modules/@opentelemetry/instrumentation/src/instrumentationNodeModuleDefinition.ts","../../../node_modules/@opentelemetry/instrumentation/src/instrumentationNodeModuleFile.ts","../../../node_modules/@opentelemetry/instrumentation/src/types.ts","../../../node_modules/@opentelemetry/instrumentation/src/types_internal.ts","../../../node_modules/@opentelemetry/instrumentation/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-http/src/http.ts","../../../node_modules/@opentelemetry/instrumentation-http/build/src/types.js","../../../node_modules/@opentelemetry/instrumentation-http/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/enums/ExpressLayerType.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-express/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/constants.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-fastify/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/enum.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/symbols.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-graphql/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-mongodb/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-mongodb/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-mongodb/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-mongodb/src/types.ts","../../../node_modules/@opentelemetry/instrumentation-mongodb/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-mongoose/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-mongoose/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-mongoose/src/mongoose.ts","../../../node_modules/@opentelemetry/instrumentation-mongoose/build/src/types.js","../../../node_modules/@opentelemetry/instrumentation-mongoose/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-mysql/src/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-mysql/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-mysql/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-mysql/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-mysql/src/index.ts","../../../node_modules/@opentelemetry/sql-common/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-mysql2/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-mysql2/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-mysql2/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-mysql2/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-ioredis/src/utils.ts","../../../node_modules/@opentelemetry/redis-common/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-ioredis/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-ioredis/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-ioredis/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-redis-4/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-redis-4/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-redis-4/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-redis-4/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/enums/NestType.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/enums/index.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-nestjs-core/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/enums/SpanNames.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-pg/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-hapi/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/types.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-koa/src/index.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/enums/AttributeNames.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/version.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/internal-types.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/utils.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/instrumentation.ts","../../../node_modules/@opentelemetry/instrumentation-connect/src/index.ts","../../cli-auth/src/index.ts","../../cli-auth/src/auth-strategies/index.ts","../../cli-auth/src/auth-strategies/api-key-auth-strategy.ts","../../cli-auth/src/client.ts","../../../node_modules/p-retry/index.js","../../../node_modules/is-network-error/index.js","../../../node_modules/@wix/ambassador-identity-account-v2-account/http.impl.ts","../../../node_modules/@wix/metro-runtime/src/index.ts","../../../node_modules/@wix/metro-runtime/src/serialization/index.ts","../../../node_modules/@wix/metro-runtime/src/serialization/utils.ts","../../../node_modules/@wix/metro-runtime/src/url-resolver.ts","../../../node_modules/@wix/metro-runtime/src/utils.ts","../../../node_modules/@wix/metro-runtime/src/flatten-params.ts","../../../node_modules/js-base64/base64.mjs","../../../node_modules/@wix/metro-runtime/src/ambassador-index.ts","../../../node_modules/@wix/metro-runtime/src/serializer/domain.ts","../../../node_modules/@wix/metro-runtime/src/serializer/serializer.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/converters.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/timestamp.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/field-mask.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/bytes.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/duration.ts","../../../node_modules/@wix/metro-runtime/src/serializer/protobuf-converters/float.ts","../../../node_modules/@wix/metro-runtime/src/serializer/utils.ts","../../../node_modules/@wix/ambassador-identity-oauth-v1-refresh-token/http.impl.ts","../../cli-http-client/src/create-http-client.ts","../../cli-http-client/src/is-http-error.ts","../../cli-http-client/src/extract-error.ts","../../cli-http-client/src/error-info.ts","../../cli-auth/src/schemas.ts","../../cli-auth/src/auth-data.ts","../../cli-auth/src/auth-strategies/account-auth-strategy.ts","../../../node_modules/p-limit/index.js","../../../node_modules/p-limit/node_modules/yocto-queue/index.js","../../../node_modules/p-wait-for/index.js","../../../node_modules/p-timeout/index.js","../../cli-auth/src/auth-strategies/site-auth-strategy.ts","../../cli-auth/src/logout.ts","../../cli-auth/src/useAuth.ts","../../cli-auth/src/context.ts","../../cli-auth/src/components/ApiKeyLogin.tsx","../../cli-telemetry-react/src/index.ts","../../cli-telemetry-react/src/useBi.tsx","../../cli-auth/src/components/Login.tsx","../../cli-auth/src/messages.json","../../cli-auth/src/components/LoginInstructions.tsx","../../user-browser/src/index.ts","../../../node_modules/open/index.js","../../../node_modules/is-wsl/index.js","../../../node_modules/is-inside-container/index.js","../../../node_modules/is-docker/index.js","../../../node_modules/define-lazy-prop/index.js","../../../node_modules/default-browser/index.js","../../../node_modules/default-browser-id/index.js","../../../node_modules/bundle-name/index.js","../../../node_modules/run-applescript/index.js","../../../node_modules/default-browser/windows.js","../../user-browser/src/open-testkit.ts","../../cli-error-reporting/src/index.ts","../../cli-error-reporting/src/create-error-handler.tsx","../../cli-debug-log/src/index.tsx","../../cli-env/src/index.ts","../../cli-error-reporting/src/components/ErrorViewer.ts","../../cli-error-reporting/src/get-error-component.tsx","../../../node_modules/outdent/src/index.ts","../../cli-error-reporting/src/components/ErrorMessage.tsx","../../cli-error-reporting/src/components/OutdatedVersionMessage.tsx","../../cli-error-reporting/src/messages.json","../../cli-error-reporting/src/components/ServeDeprecationMessage.tsx","../../cli-error-reporting/src/error-reporter.ts","../../../node_modules/@sentry/node/build/esm/index.js","../../../node_modules/@sentry/opentelemetry/src/utils/spanTypes.ts","../../../node_modules/@sentry/opentelemetry/src/utils/getRequestSpanData.ts","../../../node_modules/@sentry/opentelemetry/src/custom/client.ts","../../../node_modules/@sentry/opentelemetry/src/utils/getSpanKind.ts","../../../node_modules/@sentry/opentelemetry/src/constants.ts","../../../node_modules/@sentry/opentelemetry/src/utils/contextData.ts","../../../node_modules/@sentry/opentelemetry/src/utils/isSentryRequest.ts","../../../node_modules/@sentry/opentelemetry/src/utils/parseSpanDescription.ts","../../../node_modules/@sentry/opentelemetry/src/utils/enhanceDscWithOpenTelemetryRootSpanName.ts","../../../node_modules/@sentry/opentelemetry/src/utils/makeTraceState.ts","../../../node_modules/@sentry/opentelemetry/src/utils/generateSpanContextForPropagationContext.ts","../../../node_modules/@sentry/opentelemetry/src/utils/getActiveSpan.ts","../../../node_modules/@sentry/opentelemetry/src/debug-build.ts","../../../node_modules/@sentry/opentelemetry/src/utils/getSamplingDecision.ts","../../../node_modules/@sentry/opentelemetry/src/utils/setupCheck.ts","../../../node_modules/@sentry/opentelemetry/src/propagator.ts","../../../node_modules/@sentry/opentelemetry/src/trace.ts","../../../node_modules/@sentry/opentelemetry/src/utils/suppressTracing.ts","../../../node_modules/@sentry/opentelemetry/src/setupEventContextTrace.ts","../../../node_modules/@sentry/opentelemetry/src/asyncContextStrategy.ts","../../../node_modules/@sentry/opentelemetry/src/contextManager.ts","../../../node_modules/@sentry/opentelemetry/src/semanticAttributes.ts","../../../node_modules/@sentry/opentelemetry/src/utils/groupSpansWithParents.ts","../../../node_modules/@sentry/opentelemetry/src/utils/mapStatus.ts","../../../node_modules/@sentry/opentelemetry/src/spanExporter.ts","../../../node_modules/@sentry/opentelemetry/src/spanProcessor.ts","../../../node_modules/@sentry/opentelemetry/src/sampler.ts","../../../node_modules/@sentry/opentelemetry/src/instrumentation.ts","../../../node_modules/@sentry/node/src/sdk/scope.ts","../../../node_modules/@sentry/node/src/utils/addOriginToSpan.ts","../../../node_modules/@sentry/node/src/utils/getRequestUrl.ts","../../../node_modules/@sentry/node/src/integrations/http.ts","../../../node_modules/@sentry/node/src/debug-build.ts","../../../node_modules/@sentry/node/src/nodeVersion.ts","../../../node_modules/@sentry/node/src/integrations/node-fetch.ts","../../../node_modules/@sentry/node/src/integrations/console.ts","../../../node_modules/@sentry/node/src/integrations/context.ts","../../../node_modules/@sentry/node/src/integrations/contextlines.ts","../../../node_modules/@sentry/node/src/integrations/local-variables/common.ts","../../../node_modules/@sentry/node/src/integrations/local-variables/local-variables-async.ts","../../../node_modules/@sentry/node/src/integrations/local-variables/local-variables-sync.ts","../../../node_modules/@sentry/node/src/integrations/local-variables/index.ts","../../../node_modules/@sentry/node/src/integrations/modules.ts","../../../node_modules/@sentry/node/src/utils/errorhandling.ts","../../../node_modules/@sentry/node/src/integrations/onuncaughtexception.ts","../../../node_modules/@sentry/node/src/integrations/onunhandledrejection.ts","../../../node_modules/@sentry/node/src/otel/instrument.ts","../../../node_modules/@sentry/node/src/utils/commonjs.ts","../../../node_modules/@sentry/node/src/integrations/tracing/express.ts","../../../node_modules/@sentry/node/src/integrations/tracing/fastify.ts","../../../node_modules/@sentry/node/src/integrations/tracing/graphql.ts","../../../node_modules/@sentry/node/src/integrations/tracing/mongo.ts","../../../node_modules/@sentry/node/src/integrations/tracing/mongoose.ts","../../../node_modules/@sentry/node/src/integrations/tracing/mysql.ts","../../../node_modules/@sentry/node/src/integrations/tracing/mysql2.ts","../../../node_modules/@sentry/node/src/utils/redisCache.ts","../../../node_modules/@sentry/node/src/integrations/tracing/redis.ts","../../../node_modules/@sentry/node/src/integrations/tracing/nest.ts","../../../node_modules/@sentry/node/src/integrations/tracing/postgres.ts","../../../node_modules/@sentry/node/src/integrations/tracing/hapi/index.ts","../../../node_modules/@sentry/node/src/integrations/tracing/koa.ts","../../../node_modules/@sentry/node/src/integrations/tracing/connect.ts","../../../node_modules/@sentry/node/src/integrations/tracing/index.ts","../../../node_modules/@sentry/node/src/proxy/base.ts","../../../node_modules/@sentry/node/src/proxy/parse-proxy-response.ts","../../../node_modules/@sentry/node/src/proxy/index.ts","../../../node_modules/@sentry/node/src/transports/http.ts","../../../node_modules/@sentry/node/src/utils/module.ts","../../../node_modules/@sentry/node/src/sdk/api.ts","../../../node_modules/@sentry/node/src/sdk/client.ts","../../../node_modules/@sentry/node/src/sdk/index.ts","../../cli-error-reporting/src/user-feedback.tsx","../../cli-fs-cache/src/index.ts","../../cli-error-reporting/src/components/UserFeedback/Form.tsx","../../cli-error-reporting/src/components/UserFeedback/ContactUs.tsx","../../cli-error-reporting/src/components/UserFeedback/Fallback.tsx","../../cli-error-reporting/src/components/RawErrorViewer.tsx","../../cli-error-reporting/src/error-reporter-context.tsx","../../cli-auth/src/useColoredVerificationUri.ts","../../cli-auth/src/providers/AccountAuthProvider.tsx","../../cli-auth/src/components/EnsureLoggedIn.tsx","../../cli-auth/src/components/WarnLegacyAuthData.tsx","../../cli-auth/src/providers/SiteAuthProvider.tsx","../../cli-auth/src/hooks/useSiteAuth.ts","../../cli-auth/src/authenticate.tsx"],"sourcesContent":["function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","module.exports = require('./lib/retry');","/*\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.25.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 SEMRESATTRS_TELEMETRY_SDK_NAME,\n SEMRESATTRS_PROCESS_RUNTIME_NAME,\n SEMRESATTRS_TELEMETRY_SDK_LANGUAGE,\n TELEMETRYSDKLANGUAGEVALUES_NODEJS,\n SEMRESATTRS_TELEMETRY_SDK_VERSION,\n} from '@opentelemetry/semantic-conventions';\n\n/** Constants describing the SDK in use */\nexport const SDK_INFO = {\n [SEMRESATTRS_TELEMETRY_SDK_NAME]: 'opentelemetry',\n [SEMRESATTRS_PROCESS_RUNTIME_NAME]: 'node',\n [SEMRESATTRS_TELEMETRY_SDK_LANGUAGE]: TELEMETRYSDKLANGUAGEVALUES_NODEJS,\n [SEMRESATTRS_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 */\nexport function urlMatches(url: string, urlToMatch: string | RegExp): boolean {\n if (typeof urlToMatch === 'string') {\n return url === urlToMatch;\n } else {\n return !!url.match(urlToMatch);\n }\n}\n/**\n * Check if {@param url} should be ignored when comparing against {@param ignoredUrls}\n * @param url\n * @param ignoredUrls\n */\nexport function isUrlIgnored(\n url: string,\n ignoredUrls?: Array<string | RegExp>\n): boolean {\n if (!ignoredUrls) {\n return false;\n }\n\n for (const ignoreUrl of ignoredUrls) {\n if (urlMatches(url, ignoreUrl)) {\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 { 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","// 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\n/**\n * https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md\n */\nexport enum AttributeNames {\n HTTP_ERROR_NAME = 'http.error_name',\n HTTP_ERROR_MESSAGE = 'http.error_message',\n HTTP_STATUS_TEXT = 'http.status_text',\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 {\n MetricAttributes,\n SpanAttributes,\n SpanStatusCode,\n Span,\n context,\n SpanKind,\n} from '@opentelemetry/api';\nimport {\n NETTRANSPORTVALUES_IP_TCP,\n NETTRANSPORTVALUES_IP_UDP,\n SEMATTRS_HTTP_CLIENT_IP,\n SEMATTRS_HTTP_FLAVOR,\n SEMATTRS_HTTP_HOST,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH,\n SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED,\n SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH,\n SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED,\n SEMATTRS_HTTP_ROUTE,\n SEMATTRS_HTTP_SCHEME,\n SEMATTRS_HTTP_SERVER_NAME,\n SEMATTRS_HTTP_STATUS_CODE,\n SEMATTRS_HTTP_TARGET,\n SEMATTRS_HTTP_URL,\n SEMATTRS_HTTP_USER_AGENT,\n SEMATTRS_NET_HOST_IP,\n SEMATTRS_NET_HOST_NAME,\n SEMATTRS_NET_HOST_PORT,\n SEMATTRS_NET_PEER_IP,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n SEMATTRS_NET_TRANSPORT,\n} from '@opentelemetry/semantic-conventions';\nimport {\n IncomingHttpHeaders,\n IncomingMessage,\n OutgoingHttpHeaders,\n RequestOptions,\n ServerResponse,\n} from 'http';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport * as url from 'url';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { Err, IgnoreMatcher, ParsedRequestOptions } from './types';\n\n/**\n * Get an absolute url\n */\nexport const getAbsoluteUrl = (\n requestUrl: ParsedRequestOptions | null,\n headers: IncomingHttpHeaders | OutgoingHttpHeaders,\n fallbackProtocol = 'http:'\n): string => {\n const reqUrlObject = requestUrl || {};\n const protocol = reqUrlObject.protocol || fallbackProtocol;\n const port = (reqUrlObject.port || '').toString();\n const path = reqUrlObject.path || '/';\n let host =\n reqUrlObject.host || reqUrlObject.hostname || headers.host || 'localhost';\n\n // if there is no port in host and there is a port\n // it should be displayed if it's not 80 and 443 (default ports)\n if (\n (host as string).indexOf(':') === -1 &&\n port &&\n port !== '80' &&\n port !== '443'\n ) {\n host += `:${port}`;\n }\n\n return `${protocol}//${host}${path}`;\n};\n\n/**\n * Parse status code from HTTP response. [More details](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md#status)\n */\nexport const parseResponseStatus = (\n kind: SpanKind,\n statusCode?: number\n): SpanStatusCode => {\n const upperBound = kind === SpanKind.CLIENT ? 400 : 500;\n // 1xx, 2xx, 3xx are OK on client and server\n // 4xx is OK on server\n if (statusCode && statusCode >= 100 && statusCode < upperBound) {\n return SpanStatusCode.UNSET;\n }\n\n // All other codes are error\n return SpanStatusCode.ERROR;\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param pattern Match pattern\n */\nexport const satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isIgnored = (\n constant: string,\n list?: IgnoreMatcher[],\n onException?: (error: unknown) => void\n): boolean => {\n if (!list) {\n // No ignored urls - trace everything\n return false;\n }\n // Try/catch outside the loop for failing fast\n try {\n for (const pattern of list) {\n if (satisfiesPattern(constant, pattern)) {\n return true;\n }\n }\n } catch (e) {\n if (onException) {\n onException(e);\n }\n }\n\n return false;\n};\n\n/**\n * Sets the span with the error passed in params\n * @param {Span} span the span that need to be set\n * @param {Error} error error that will be set to span\n */\nexport const setSpanWithError = (span: Span, error: Err): void => {\n const message = error.message;\n\n span.setAttribute(AttributeNames.HTTP_ERROR_NAME, error.name);\n span.setAttribute(AttributeNames.HTTP_ERROR_MESSAGE, message);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.recordException(error);\n};\n\n/**\n * Adds attributes for request content-length and content-encoding HTTP headers\n * @param { IncomingMessage } Request object whose headers will be analyzed\n * @param { SpanAttributes } SpanAttributes object to be modified\n */\nexport const setRequestContentLengthAttribute = (\n request: IncomingMessage,\n attributes: SpanAttributes\n): void => {\n const length = getContentLength(request.headers);\n if (length === null) return;\n\n if (isCompressed(request.headers)) {\n attributes[SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH] = length;\n } else {\n attributes[SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED] = length;\n }\n};\n\n/**\n * Adds attributes for response content-length and content-encoding HTTP headers\n * @param { IncomingMessage } Response object whose headers will be analyzed\n * @param { SpanAttributes } SpanAttributes object to be modified\n */\nexport const setResponseContentLengthAttribute = (\n response: IncomingMessage,\n attributes: SpanAttributes\n): void => {\n const length = getContentLength(response.headers);\n if (length === null) return;\n\n if (isCompressed(response.headers)) {\n attributes[SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH] = length;\n } else {\n attributes[SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED] = length;\n }\n};\n\nfunction getContentLength(\n headers: OutgoingHttpHeaders | IncomingHttpHeaders\n): number | null {\n const contentLengthHeader = headers['content-length'];\n if (contentLengthHeader === undefined) return null;\n\n const contentLength = parseInt(contentLengthHeader as string, 10);\n if (isNaN(contentLength)) return null;\n\n return contentLength;\n}\n\nexport const isCompressed = (\n headers: OutgoingHttpHeaders | IncomingHttpHeaders\n): boolean => {\n const encoding = headers['content-encoding'];\n\n return !!encoding && encoding !== 'identity';\n};\n\n/**\n * Makes sure options is an url object\n * return an object with default value and parsed options\n * @param options original options for the request\n * @param [extraOptions] additional options for the request\n */\nexport const getRequestInfo = (\n options: url.URL | RequestOptions | string,\n extraOptions?: RequestOptions\n): {\n origin: string;\n pathname: string;\n method: string;\n optionsParsed: RequestOptions;\n} => {\n let pathname = '/';\n let origin = '';\n let optionsParsed: RequestOptions;\n if (typeof options === 'string') {\n optionsParsed = url.parse(options);\n pathname = (optionsParsed as url.UrlWithStringQuery).pathname || '/';\n origin = `${optionsParsed.protocol || 'http:'}//${optionsParsed.host}`;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else if (options instanceof url.URL) {\n optionsParsed = {\n protocol: options.protocol,\n hostname:\n typeof options.hostname === 'string' && options.hostname.startsWith('[')\n ? options.hostname.slice(1, -1)\n : options.hostname,\n path: `${options.pathname || ''}${options.search || ''}`,\n };\n if (options.port !== '') {\n optionsParsed.port = Number(options.port);\n }\n if (options.username || options.password) {\n optionsParsed.auth = `${options.username}:${options.password}`;\n }\n pathname = options.pathname;\n origin = options.origin;\n if (extraOptions !== undefined) {\n Object.assign(optionsParsed, extraOptions);\n }\n } else {\n optionsParsed = Object.assign(\n { protocol: options.host ? 'http:' : undefined },\n options\n );\n pathname = (options as url.URL).pathname;\n if (!pathname && optionsParsed.path) {\n pathname = url.parse(optionsParsed.path).pathname || '/';\n }\n const hostname =\n optionsParsed.host ||\n (optionsParsed.port != null\n ? `${optionsParsed.hostname}${optionsParsed.port}`\n : optionsParsed.hostname);\n origin = `${optionsParsed.protocol || 'http:'}//${hostname}`;\n }\n\n // some packages return method in lowercase..\n // ensure upperCase for consistency\n const method = optionsParsed.method\n ? optionsParsed.method.toUpperCase()\n : 'GET';\n\n return { origin, pathname, method, optionsParsed };\n};\n\n/**\n * Makes sure options is of type string or object\n * @param options for the request\n */\nexport const isValidOptionsType = (options: unknown): boolean => {\n if (!options) {\n return false;\n }\n\n const type = typeof options;\n return type === 'string' || (type === 'object' && !Array.isArray(options));\n};\n\nexport const extractHostnameAndPort = (\n requestOptions: Pick<\n ParsedRequestOptions,\n 'hostname' | 'host' | 'port' | 'protocol'\n >\n): { hostname: string; port: number | string } => {\n if (requestOptions.hostname && requestOptions.port) {\n return { hostname: requestOptions.hostname, port: requestOptions.port };\n }\n const matches = requestOptions.host?.match(/^([^:/ ]+)(:\\d{1,5})?/) || null;\n const hostname =\n requestOptions.hostname || (matches === null ? 'localhost' : matches[1]);\n let port = requestOptions.port;\n if (!port) {\n if (matches && matches[2]) {\n // remove the leading \":\". The extracted port would be something like \":8080\"\n port = matches[2].substring(1);\n } else {\n port = requestOptions.protocol === 'https:' ? '443' : '80';\n }\n }\n return { hostname, port };\n};\n\n/**\n * Returns outgoing request attributes scoped to the options passed to the request\n * @param {ParsedRequestOptions} requestOptions the same options used to make the request\n * @param {{ component: string, hostname: string, hookAttributes?: SpanAttributes }} options used to pass data needed to create attributes\n */\nexport const getOutgoingRequestAttributes = (\n requestOptions: ParsedRequestOptions,\n options: {\n component: string;\n hostname: string;\n port: string | number;\n hookAttributes?: SpanAttributes;\n }\n): SpanAttributes => {\n const hostname = options.hostname;\n const port = options.port;\n const requestMethod = requestOptions.method;\n const method = requestMethod ? requestMethod.toUpperCase() : 'GET';\n const headers = requestOptions.headers || {};\n const userAgent = headers['user-agent'];\n const attributes: SpanAttributes = {\n [SEMATTRS_HTTP_URL]: getAbsoluteUrl(\n requestOptions,\n headers,\n `${options.component}:`\n ),\n [SEMATTRS_HTTP_METHOD]: method,\n [SEMATTRS_HTTP_TARGET]: requestOptions.path || '/',\n [SEMATTRS_NET_PEER_NAME]: hostname,\n [SEMATTRS_HTTP_HOST]: headers.host ?? `${hostname}:${port}`,\n };\n\n if (userAgent !== undefined) {\n attributes[SEMATTRS_HTTP_USER_AGENT] = userAgent;\n }\n return Object.assign(attributes, options.hookAttributes);\n};\n\n/**\n * Returns outgoing request Metric attributes scoped to the request data\n * @param {SpanAttributes} spanAttributes the span attributes\n */\nexport const getOutgoingRequestMetricAttributes = (\n spanAttributes: SpanAttributes\n): MetricAttributes => {\n const metricAttributes: MetricAttributes = {};\n metricAttributes[SEMATTRS_HTTP_METHOD] = spanAttributes[SEMATTRS_HTTP_METHOD];\n metricAttributes[SEMATTRS_NET_PEER_NAME] =\n spanAttributes[SEMATTRS_NET_PEER_NAME];\n //TODO: http.url attribute, it should substitute any parameters to avoid high cardinality.\n return metricAttributes;\n};\n\n/**\n * Returns attributes related to the kind of HTTP protocol used\n * @param {string} [kind] Kind of HTTP protocol used: \"1.0\", \"1.1\", \"2\", \"SPDY\" or \"QUIC\".\n */\nexport const setAttributesFromHttpKind = (\n kind: string | undefined,\n attributes: SpanAttributes\n): void => {\n if (kind) {\n attributes[SEMATTRS_HTTP_FLAVOR] = kind;\n if (kind.toUpperCase() !== 'QUIC') {\n attributes[SEMATTRS_NET_TRANSPORT] = NETTRANSPORTVALUES_IP_TCP;\n } else {\n attributes[SEMATTRS_NET_TRANSPORT] = NETTRANSPORTVALUES_IP_UDP;\n }\n }\n};\n\n/**\n * Returns outgoing request attributes scoped to the response data\n * @param {IncomingMessage} response the response object\n * @param {{ hostname: string }} options used to pass data needed to create attributes\n */\nexport const getOutgoingRequestAttributesOnResponse = (\n response: IncomingMessage\n): SpanAttributes => {\n const { statusCode, statusMessage, httpVersion, socket } = response;\n const attributes: SpanAttributes = {};\n if (socket) {\n const { remoteAddress, remotePort } = socket;\n attributes[SEMATTRS_NET_PEER_IP] = remoteAddress;\n attributes[SEMATTRS_NET_PEER_PORT] = remotePort;\n }\n setResponseContentLengthAttribute(response, attributes);\n\n if (statusCode) {\n attributes[SEMATTRS_HTTP_STATUS_CODE] = statusCode;\n attributes[AttributeNames.HTTP_STATUS_TEXT] = (\n statusMessage || ''\n ).toUpperCase();\n }\n\n setAttributesFromHttpKind(httpVersion, attributes);\n return attributes;\n};\n\n/**\n * Returns outgoing request Metric attributes scoped to the response data\n * @param {SpanAttributes} spanAttributes the span attributes\n */\nexport const getOutgoingRequestMetricAttributesOnResponse = (\n spanAttributes: SpanAttributes\n): MetricAttributes => {\n const metricAttributes: MetricAttributes = {};\n metricAttributes[SEMATTRS_NET_PEER_PORT] =\n spanAttributes[SEMATTRS_NET_PEER_PORT];\n metricAttributes[SEMATTRS_HTTP_STATUS_CODE] =\n spanAttributes[SEMATTRS_HTTP_STATUS_CODE];\n metricAttributes[SEMATTRS_HTTP_FLAVOR] = spanAttributes[SEMATTRS_HTTP_FLAVOR];\n return metricAttributes;\n};\n\n/**\n * Returns incoming request attributes scoped to the request data\n * @param {IncomingMessage} request the request object\n * @param {{ component: string, serverName?: string, hookAttributes?: SpanAttributes }} options used to pass data needed to create attributes\n */\nexport const getIncomingRequestAttributes = (\n request: IncomingMessage,\n options: {\n component: string;\n serverName?: string;\n hookAttributes?: SpanAttributes;\n }\n): SpanAttributes => {\n const headers = request.headers;\n const userAgent = headers['user-agent'];\n const ips = headers['x-forwarded-for'];\n const method = request.method || 'GET';\n const httpVersion = request.httpVersion;\n const requestUrl = request.url ? url.parse(request.url) : null;\n const host = requestUrl?.host || headers.host;\n const hostname =\n requestUrl?.hostname ||\n host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') ||\n 'localhost';\n const serverName = options.serverName;\n const attributes: SpanAttributes = {\n [SEMATTRS_HTTP_URL]: getAbsoluteUrl(\n requestUrl,\n headers,\n `${options.component}:`\n ),\n [SEMATTRS_HTTP_HOST]: host,\n [SEMATTRS_NET_HOST_NAME]: hostname,\n [SEMATTRS_HTTP_METHOD]: method,\n [SEMATTRS_HTTP_SCHEME]: options.component,\n };\n\n if (typeof ips === 'string') {\n attributes[SEMATTRS_HTTP_CLIENT_IP] = ips.split(',')[0];\n }\n\n if (typeof serverName === 'string') {\n attributes[SEMATTRS_HTTP_SERVER_NAME] = serverName;\n }\n\n if (requestUrl) {\n attributes[SEMATTRS_HTTP_TARGET] = requestUrl.path || '/';\n }\n\n if (userAgent !== undefined) {\n attributes[SEMATTRS_HTTP_USER_AGENT] = userAgent;\n }\n setRequestContentLengthAttribute(request, attributes);\n setAttributesFromHttpKind(httpVersion, attributes);\n return Object.assign(attributes, options.hookAttributes);\n};\n\n/**\n * Returns incoming request Metric attributes scoped to the request data\n * @param {SpanAttributes} spanAttributes the span attributes\n * @param {{ component: string }} options used to pass data needed to create attributes\n */\nexport const getIncomingRequestMetricAttributes = (\n spanAttributes: SpanAttributes\n): MetricAttributes => {\n const metricAttributes: MetricAttributes = {};\n metricAttributes[SEMATTRS_HTTP_SCHEME] = spanAttributes[SEMATTRS_HTTP_SCHEME];\n metricAttributes[SEMATTRS_HTTP_METHOD] = spanAttributes[SEMATTRS_HTTP_METHOD];\n metricAttributes[SEMATTRS_NET_HOST_NAME] =\n spanAttributes[SEMATTRS_NET_HOST_NAME];\n metricAttributes[SEMATTRS_HTTP_FLAVOR] = spanAttributes[SEMATTRS_HTTP_FLAVOR];\n //TODO: http.target attribute, it should substitute any parameters to avoid high cardinality.\n return metricAttributes;\n};\n\n/**\n * Returns incoming request attributes scoped to the response data\n * @param {(ServerResponse & { socket: Socket; })} response the response object\n */\nexport const getIncomingRequestAttributesOnResponse = (\n request: IncomingMessage,\n response: ServerResponse\n): SpanAttributes => {\n // take socket from the request,\n // since it may be detached from the response object in keep-alive mode\n const { socket } = request;\n const { statusCode, statusMessage } = response;\n\n const rpcMetadata = getRPCMetadata(context.active());\n const attributes: SpanAttributes = {};\n if (socket) {\n const { localAddress, localPort, remoteAddress, remotePort } = socket;\n attributes[SEMATTRS_NET_HOST_IP] = localAddress;\n attributes[SEMATTRS_NET_HOST_PORT] = localPort;\n attributes[SEMATTRS_NET_PEER_IP] = remoteAddress;\n attributes[SEMATTRS_NET_PEER_PORT] = remotePort;\n }\n attributes[SEMATTRS_HTTP_STATUS_CODE] = statusCode;\n attributes[AttributeNames.HTTP_STATUS_TEXT] = (\n statusMessage || ''\n ).toUpperCase();\n\n if (rpcMetadata?.type === RPCType.HTTP && rpcMetadata.route !== undefined) {\n attributes[SEMATTRS_HTTP_ROUTE] = rpcMetadata.route;\n }\n return attributes;\n};\n\n/**\n * Returns incoming request Metric attributes scoped to the request data\n * @param {SpanAttributes} spanAttributes the span attributes\n */\nexport const getIncomingRequestMetricAttributesOnResponse = (\n spanAttributes: SpanAttributes\n): MetricAttributes => {\n const metricAttributes: MetricAttributes = {};\n metricAttributes[SEMATTRS_HTTP_STATUS_CODE] =\n spanAttributes[SEMATTRS_HTTP_STATUS_CODE];\n metricAttributes[SEMATTRS_NET_HOST_PORT] =\n spanAttributes[SEMATTRS_NET_HOST_PORT];\n if (spanAttributes[SEMATTRS_HTTP_ROUTE] !== undefined) {\n metricAttributes[SEMATTRS_HTTP_ROUTE] = spanAttributes[SEMATTRS_HTTP_ROUTE];\n }\n return metricAttributes;\n};\n\nexport function headerCapture(type: 'request' | 'response', headers: string[]) {\n const normalizedHeaders = new Map<string, string>();\n for (let i = 0, len = headers.length; i < len; i++) {\n const capturedHeader = headers[i].toLowerCase();\n normalizedHeaders.set(capturedHeader, capturedHeader.replace(/-/g, '_'));\n }\n\n return (\n span: Span,\n getHeader: (key: string) => undefined | string | string[] | number\n ) => {\n for (const capturedHeader of normalizedHeaders.keys()) {\n const value = getHeader(capturedHeader);\n\n if (value === undefined) {\n continue;\n }\n\n const normalizedHeader = normalizedHeaders.get(capturedHeader);\n const key = `http.${type}.header.${normalizedHeader}`;\n\n if (typeof value === 'string') {\n span.setAttribute(key, [value]);\n } else if (Array.isArray(value)) {\n span.setAttribute(key, value);\n } else {\n span.setAttribute(key, [value]);\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\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.52.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 { LogRecord } from './LogRecord';\n\nexport interface Logger {\n /**\n * Emit a log record. This method should only be used by log appenders.\n *\n * @param logRecord\n */\n emit(logRecord: LogRecord): 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 { Logger } from './Logger';\nimport { LoggerOptions } from './LoggerOptions';\n\n/**\n * A registry for creating named {@link Logger}s.\n */\nexport interface LoggerProvider {\n /**\n * Returns a Logger, creating one if one with the given name, version, and\n * schemaUrl pair is not already created.\n *\n * @param name The name of the logger or instrumentation library.\n * @param version The version of the logger or instrumentation library.\n * @param options The options of the logger or instrumentation library.\n * @returns Logger A Logger with the given name and version\n */\n getLogger(name: string, version?: string, options?: LoggerOptions): Logger;\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, TimeInput } from '@opentelemetry/api';\nimport { AnyValue, AnyValueMap } from './AnyValue';\n\nexport type LogBody = AnyValue;\nexport type LogAttributes = AnyValueMap;\n\nexport enum SeverityNumber {\n UNSPECIFIED = 0,\n TRACE = 1,\n TRACE2 = 2,\n TRACE3 = 3,\n TRACE4 = 4,\n DEBUG = 5,\n DEBUG2 = 6,\n DEBUG3 = 7,\n DEBUG4 = 8,\n INFO = 9,\n INFO2 = 10,\n INFO3 = 11,\n INFO4 = 12,\n WARN = 13,\n WARN2 = 14,\n WARN3 = 15,\n WARN4 = 16,\n ERROR = 17,\n ERROR2 = 18,\n ERROR3 = 19,\n ERROR4 = 20,\n FATAL = 21,\n FATAL2 = 22,\n FATAL3 = 23,\n FATAL4 = 24,\n}\n\nexport interface LogRecord {\n /**\n * The time when the log record occurred as UNIX Epoch time in nanoseconds.\n */\n timestamp?: TimeInput;\n\n /**\n * Time when the event was observed by the collection system.\n */\n observedTimestamp?: TimeInput;\n\n /**\n * Numerical value of the severity.\n */\n severityNumber?: SeverityNumber;\n\n /**\n * The severity text.\n */\n severityText?: string;\n\n /**\n * A value containing the body of the log record.\n */\n body?: LogBody;\n\n /**\n * Attributes that define the log record.\n */\n attributes?: LogAttributes;\n\n /**\n * The Context associated with the LogRecord.\n */\n context?: Context;\n}\n","export {};\n//# sourceMappingURL=LoggerOptions.js.map","/*\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 { AttributeValue } from '@opentelemetry/api';\n\n/**\n * AnyValueMap is a map from string to AnyValue (attribute value or a nested map)\n */\nexport interface AnyValueMap {\n [attributeKey: string]: AnyValue | undefined;\n}\n\n/**\n * AnyValue is a either an attribute value or a map of AnyValue(s)\n */\nexport type AnyValue = AttributeValue | AnyValueMap;\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 { Logger } from './types/Logger';\nimport { LogRecord } from './types/LogRecord';\n\nexport class NoopLogger implements Logger {\n emit(_logRecord: LogRecord): void {}\n}\n\nexport const NOOP_LOGGER = new NoopLogger();\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 { LoggerProvider } from './types/LoggerProvider';\nimport { Logger } from './types/Logger';\nimport { LoggerOptions } from './types/LoggerOptions';\nimport { NoopLogger } from './NoopLogger';\n\nexport class NoopLoggerProvider implements LoggerProvider {\n getLogger(\n _name: string,\n _version?: string | undefined,\n _options?: LoggerOptions | undefined\n ): Logger {\n return new NoopLogger();\n }\n}\n\nexport const NOOP_LOGGER_PROVIDER = new NoopLoggerProvider();\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\nexport * from './globalThis';\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 { LoggerProvider } from '../types/LoggerProvider';\nimport { _globalThis } from '../platform';\n\nexport const GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs');\n\ntype Get<T> = (version: number) => T;\ntype OtelGlobal = Partial<{\n [GLOBAL_LOGS_API_KEY]: Get<LoggerProvider>;\n}>;\n\nexport const _global = _globalThis as OtelGlobal;\n\n/**\n * Make a function which accepts a version integer and returns the instance of an API if the version\n * is compatible, or a fallback version (usually NOOP) if it is not.\n *\n * @param requiredVersion Backwards compatibility version which is required to return the instance\n * @param instance Instance which should be returned if the required version is compatible\n * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible\n */\nexport function makeGetter<T>(\n requiredVersion: number,\n instance: T,\n fallback: T\n): Get<T> {\n return (version: number): T =>\n version === requiredVersion ? instance : fallback;\n}\n\n/**\n * A number which should be incremented each time a backwards incompatible\n * change is made to the API. This number is used when an API package\n * attempts to access the global API to ensure it is getting a compatible\n * version. If the global API is not compatible with the API package\n * attempting to get it, a NOOP API implementation will be returned.\n */\nexport const API_BACKWARDS_COMPATIBILITY_VERSION = 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 {\n API_BACKWARDS_COMPATIBILITY_VERSION,\n GLOBAL_LOGS_API_KEY,\n _global,\n makeGetter,\n} from '../internal/global-utils';\nimport { LoggerProvider } from '../types/LoggerProvider';\nimport { NOOP_LOGGER_PROVIDER } from '../NoopLoggerProvider';\nimport { Logger } from '../types/Logger';\nimport { LoggerOptions } from '../types/LoggerOptions';\n\nexport class LogsAPI {\n private static _instance?: LogsAPI;\n\n private constructor() {}\n\n public static getInstance(): LogsAPI {\n if (!this._instance) {\n this._instance = new LogsAPI();\n }\n\n return this._instance;\n }\n\n public setGlobalLoggerProvider(provider: LoggerProvider): LoggerProvider {\n if (_global[GLOBAL_LOGS_API_KEY]) {\n return this.getLoggerProvider();\n }\n\n _global[GLOBAL_LOGS_API_KEY] = makeGetter<LoggerProvider>(\n API_BACKWARDS_COMPATIBILITY_VERSION,\n provider,\n NOOP_LOGGER_PROVIDER\n );\n\n return provider;\n }\n\n /**\n * Returns the global logger provider.\n *\n * @returns LoggerProvider\n */\n public getLoggerProvider(): LoggerProvider {\n return (\n _global[GLOBAL_LOGS_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ??\n NOOP_LOGGER_PROVIDER\n );\n }\n\n /**\n * Returns a logger from the global logger provider.\n *\n * @returns Logger\n */\n public getLogger(\n name: string,\n version?: string,\n options?: LoggerOptions\n ): Logger {\n return this.getLoggerProvider().getLogger(name, version, options);\n }\n\n /** Remove the global logger provider */\n public disable(): void {\n delete _global[GLOBAL_LOGS_API_KEY];\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 './types/Logger';\nexport * from './types/LoggerProvider';\nexport * from './types/LogRecord';\nexport * from './types/LoggerOptions';\nexport * from './types/AnyValue';\nexport * from './NoopLogger';\nexport * from './NoopLoggerProvider';\n\nimport { LogsAPI } from './api/logs';\nexport const logs = LogsAPI.getInstance();\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 { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/**\n * Enable instrumentations\n * @param instrumentations\n * @param tracerProvider\n * @param meterProvider\n */\nexport function enableInstrumentations(\n instrumentations: Instrumentation[],\n tracerProvider?: TracerProvider,\n meterProvider?: MeterProvider,\n loggerProvider?: LoggerProvider\n): void {\n for (let i = 0, j = instrumentations.length; i < j; i++) {\n const instrumentation = instrumentations[i];\n if (tracerProvider) {\n instrumentation.setTracerProvider(tracerProvider);\n }\n if (meterProvider) {\n instrumentation.setMeterProvider(meterProvider);\n }\n if (loggerProvider && instrumentation.setLoggerProvider) {\n instrumentation.setLoggerProvider(loggerProvider);\n }\n // instrumentations have been already enabled during creation\n // so enable only if user prevented that by setting enabled to false\n // this is to prevent double enabling but when calling register all\n // instrumentations should be now enabled\n if (!instrumentation.getConfig().enabled) {\n instrumentation.enable();\n }\n }\n}\n\n/**\n * Disable instrumentations\n * @param instrumentations\n */\nexport function disableInstrumentations(\n instrumentations: Instrumentation[]\n): void {\n instrumentations.forEach(instrumentation => instrumentation.disable());\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 { trace, metrics } from '@opentelemetry/api';\nimport { logs } from '@opentelemetry/api-logs';\nimport {\n disableInstrumentations,\n enableInstrumentations,\n} from './autoLoaderUtils';\nimport { AutoLoaderOptions } from './types_internal';\n\n/**\n * It will register instrumentations and plugins\n * @param options\n * @return returns function to unload instrumentation and plugins that were\n * registered\n */\nexport function registerInstrumentations(\n options: AutoLoaderOptions\n): () => void {\n const tracerProvider = options.tracerProvider || trace.getTracerProvider();\n const meterProvider = options.meterProvider || metrics.getMeterProvider();\n const loggerProvider = options.loggerProvider || logs.getLoggerProvider();\n const instrumentations = options.instrumentations?.flat() ?? [];\n\n enableInstrumentations(\n instrumentations,\n tracerProvider,\n meterProvider,\n loggerProvider\n );\n\n return () => {\n disableInstrumentations(instrumentations);\n };\n}\n","'use strict'\n\nfunction isFunction (funktion) {\n return typeof funktion === 'function'\n}\n\n// Default to complaining loudly when things don't go according to plan.\nvar logger = console.error.bind(console)\n\n// Sets a property on an object, preserving its enumerability.\n// This function assumes that the property is already writable.\nfunction defineProperty (obj, name, value) {\n var enumerable = !!obj[name] && obj.propertyIsEnumerable(name)\n Object.defineProperty(obj, name, {\n configurable: true,\n enumerable: enumerable,\n writable: true,\n value: value\n })\n}\n\n// Keep initialization idempotent.\nfunction shimmer (options) {\n if (options && options.logger) {\n if (!isFunction(options.logger)) logger(\"new logger isn't a function, not replacing\")\n else logger = options.logger\n }\n}\n\nfunction wrap (nodule, name, wrapper) {\n if (!nodule || !nodule[name]) {\n logger('no original function ' + name + ' to wrap')\n return\n }\n\n if (!wrapper) {\n logger('no wrapper function')\n logger((new Error()).stack)\n return\n }\n\n if (!isFunction(nodule[name]) || !isFunction(wrapper)) {\n logger('original object and wrapper must be functions')\n return\n }\n\n var original = nodule[name]\n var wrapped = wrapper(original, name)\n\n defineProperty(wrapped, '__original', original)\n defineProperty(wrapped, '__unwrap', function () {\n if (nodule[name] === wrapped) defineProperty(nodule, name, original)\n })\n defineProperty(wrapped, '__wrapped', true)\n\n defineProperty(nodule, name, wrapped)\n return wrapped\n}\n\nfunction massWrap (nodules, names, wrapper) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to wrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n wrap(nodule, name, wrapper)\n })\n })\n}\n\nfunction unwrap (nodule, name) {\n if (!nodule || !nodule[name]) {\n logger('no function to unwrap.')\n logger((new Error()).stack)\n return\n }\n\n if (!nodule[name].__unwrap) {\n logger('no original to unwrap to -- has ' + name + ' already been unwrapped?')\n } else {\n return nodule[name].__unwrap()\n }\n}\n\nfunction massUnwrap (nodules, names) {\n if (!nodules) {\n logger('must provide one or more modules to patch')\n logger((new Error()).stack)\n return\n } else if (!Array.isArray(nodules)) {\n nodules = [nodules]\n }\n\n if (!(names && Array.isArray(names))) {\n logger('must provide one or more functions to unwrap on modules')\n return\n }\n\n nodules.forEach(function (nodule) {\n names.forEach(function (name) {\n unwrap(nodule, name)\n })\n })\n}\n\nshimmer.wrap = wrap\nshimmer.massWrap = massWrap\nshimmer.unwrap = unwrap\nshimmer.massUnwrap = massUnwrap\n\nmodule.exports = shimmer\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 diag,\n DiagLogger,\n metrics,\n Meter,\n MeterProvider,\n trace,\n Tracer,\n TracerProvider,\n Span,\n} from '@opentelemetry/api';\nimport { Logger, LoggerProvider, logs } from '@opentelemetry/api-logs';\nimport * as shimmer from 'shimmer';\nimport {\n InstrumentationModuleDefinition,\n Instrumentation,\n InstrumentationConfig,\n SpanCustomizationHook,\n} from './types';\n\n/**\n * Base abstract internal class for instrumenting node and web plugins\n */\nexport abstract class InstrumentationAbstract<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n> implements Instrumentation<ConfigType>\n{\n protected _config: ConfigType;\n\n private _tracer: Tracer;\n private _meter: Meter;\n private _logger: Logger;\n protected _diag: DiagLogger;\n\n constructor(\n public readonly instrumentationName: string,\n public readonly instrumentationVersion: string,\n config: ConfigType\n ) {\n // copy config first level properties to ensure they are immutable.\n // nested properties are not copied, thus are mutable from the outside.\n this._config = {\n enabled: true,\n ...config,\n };\n\n this._diag = diag.createComponentLogger({\n namespace: instrumentationName,\n });\n\n this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);\n this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);\n this._logger = logs.getLogger(instrumentationName, instrumentationVersion);\n this._updateMetricInstruments();\n }\n\n /* Api to wrap instrumented method */\n protected _wrap = shimmer.wrap;\n /* Api to unwrap instrumented methods */\n protected _unwrap = shimmer.unwrap;\n /* Api to mass wrap instrumented method */\n protected _massWrap = shimmer.massWrap;\n /* Api to mass unwrap instrumented methods */\n protected _massUnwrap = shimmer.massUnwrap;\n\n /* Returns meter */\n protected get meter(): Meter {\n return this._meter;\n }\n\n /**\n * Sets MeterProvider to this plugin\n * @param meterProvider\n */\n public setMeterProvider(meterProvider: MeterProvider): void {\n this._meter = meterProvider.getMeter(\n this.instrumentationName,\n this.instrumentationVersion\n );\n\n this._updateMetricInstruments();\n }\n\n /* Returns logger */\n protected get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Sets LoggerProvider to this plugin\n * @param loggerProvider\n */\n public setLoggerProvider(loggerProvider: LoggerProvider): void {\n this._logger = loggerProvider.getLogger(\n this.instrumentationName,\n this.instrumentationVersion\n );\n }\n\n /**\n * @experimental\n *\n * Get module definitions defined by {@link init}.\n * This can be used for experimental compile-time instrumentation.\n *\n * @returns an array of {@link InstrumentationModuleDefinition}\n */\n public getModuleDefinitions(): InstrumentationModuleDefinition[] {\n const initResult = this.init() ?? [];\n if (!Array.isArray(initResult)) {\n return [initResult];\n }\n\n return initResult;\n }\n\n /**\n * Sets the new metric instruments with the current Meter.\n */\n protected _updateMetricInstruments(): void {\n return;\n }\n\n /* Returns InstrumentationConfig */\n public getConfig(): ConfigType {\n return this._config;\n }\n\n /**\n * Sets InstrumentationConfig to this plugin\n * @param InstrumentationConfig\n */\n public setConfig(config: ConfigType): void {\n // copy config first level properties to ensure they are immutable.\n // nested properties are not copied, thus are mutable from the outside.\n this._config = { ...config };\n }\n\n /**\n * Sets TraceProvider to this plugin\n * @param tracerProvider\n */\n public setTracerProvider(tracerProvider: TracerProvider): void {\n this._tracer = tracerProvider.getTracer(\n this.instrumentationName,\n this.instrumentationVersion\n );\n }\n\n /* Returns tracer */\n protected get tracer(): Tracer {\n return this._tracer;\n }\n\n /* Disable plugin */\n public abstract enable(): void;\n\n /* Enable plugin */\n public abstract disable(): void;\n\n /**\n * Init method in which plugin should define _modules and patches for\n * methods.\n */\n protected abstract init():\n | InstrumentationModuleDefinition\n | InstrumentationModuleDefinition[]\n | void;\n\n /**\n * Execute span customization hook, if configured, and log any errors.\n * Any semantics of the trigger and info are defined by the specific instrumentation.\n * @param hookHandler The optional hook handler which the user has configured via instrumentation config\n * @param triggerName The name of the trigger for executing the hook for logging purposes\n * @param span The span to which the hook should be applied\n * @param info The info object to be passed to the hook, with useful data the hook may use\n */\n protected _runSpanCustomizationHook<SpanCustomizationInfoType>(\n hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined,\n triggerName: string,\n span: Span,\n info: SpanCustomizationInfoType\n ) {\n if (!hookHandler) {\n return;\n }\n\n try {\n hookHandler(span, info);\n } catch (e) {\n this._diag.error(\n `Error running span customization hook due to exception in handler`,\n { triggerName },\n e\n );\n }\n }\n}\n","'use strict';\n\nvar os = require('os');\n\n// adapted from https://github.com/sindresorhus/os-homedir/blob/11e089f4754db38bb535e5a8416320c4446e8cfd/index.js\n\nmodule.exports = os.homedir || function homedir() {\n var home = process.env.HOME;\n var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;\n\n if (process.platform === 'win32') {\n return process.env.USERPROFILE || process.env.HOMEDRIVE + process.env.HOMEPATH || home || null;\n }\n\n if (process.platform === 'darwin') {\n return home || (user ? '/Users/' + user : null);\n }\n\n if (process.platform === 'linux') {\n return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null)); // eslint-disable-line no-extra-parens\n }\n\n return home || null;\n};\n","module.exports = function () {\n // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\n var origPrepareStackTrace = Error.prepareStackTrace;\n Error.prepareStackTrace = function (_, stack) { return stack; };\n var stack = (new Error()).stack;\n Error.prepareStackTrace = origPrepareStackTrace;\n return stack[2].getFileName();\n};\n","'use strict';\n\nvar isWindows = process.platform === 'win32';\n\n// Regex to split a windows path into into [dir, root, basename, name, ext]\nvar splitWindowsRe =\n /^(((?:[a-zA-Z]:|[\\\\\\/]{2}[^\\\\\\/]+[\\\\\\/]+[^\\\\\\/]+)?[\\\\\\/]?)(?:[^\\\\\\/]*[\\\\\\/])*)((\\.{1,2}|[^\\\\\\/]+?|)(\\.[^.\\/\\\\]*|))[\\\\\\/]*$/;\n\nvar win32 = {};\n\nfunction win32SplitPath(filename) {\n return splitWindowsRe.exec(filename).slice(1);\n}\n\nwin32.parse = function(pathString) {\n if (typeof pathString !== 'string') {\n throw new TypeError(\n \"Parameter 'pathString' must be a string, not \" + typeof pathString\n );\n }\n var allParts = win32SplitPath(pathString);\n if (!allParts || allParts.length !== 5) {\n throw new TypeError(\"Invalid path '\" + pathString + \"'\");\n }\n return {\n root: allParts[1],\n dir: allParts[0] === allParts[1] ? allParts[0] : allParts[0].slice(0, -1),\n base: allParts[2],\n ext: allParts[4],\n name: allParts[3]\n };\n};\n\n\n\n// Split a filename into [dir, root, basename, name, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe =\n /^((\\/?)(?:[^\\/]*\\/)*)((\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))[\\/]*$/;\nvar posix = {};\n\n\nfunction posixSplitPath(filename) {\n return splitPathRe.exec(filename).slice(1);\n}\n\n\nposix.parse = function(pathString) {\n if (typeof pathString !== 'string') {\n throw new TypeError(\n \"Parameter 'pathString' must be a string, not \" + typeof pathString\n );\n }\n var allParts = posixSplitPath(pathString);\n if (!allParts || allParts.length !== 5) {\n throw new TypeError(\"Invalid path '\" + pathString + \"'\");\n }\n \n return {\n root: allParts[1],\n dir: allParts[0].slice(0, -1),\n base: allParts[2],\n ext: allParts[4],\n name: allParts[3],\n };\n};\n\n\nif (isWindows)\n module.exports = win32.parse;\nelse /* posix */\n module.exports = posix.parse;\n\nmodule.exports.posix = posix.parse;\nmodule.exports.win32 = win32.parse;\n","var path = require('path');\nvar parse = path.parse || require('path-parse'); // eslint-disable-line global-require\n\nvar getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {\n var prefix = '/';\n if ((/^([A-Za-z]:)/).test(absoluteStart)) {\n prefix = '';\n } else if ((/^\\\\\\\\/).test(absoluteStart)) {\n prefix = '\\\\\\\\';\n }\n\n var paths = [absoluteStart];\n var parsed = parse(absoluteStart);\n while (parsed.dir !== paths[paths.length - 1]) {\n paths.push(parsed.dir);\n parsed = parse(parsed.dir);\n }\n\n return paths.reduce(function (dirs, aPath) {\n return dirs.concat(modules.map(function (moduleDir) {\n return path.resolve(prefix, aPath, moduleDir);\n }));\n }, []);\n};\n\nmodule.exports = function nodeModulesPaths(start, opts, request) {\n var modules = opts && opts.moduleDirectory\n ? [].concat(opts.moduleDirectory)\n : ['node_modules'];\n\n if (opts && typeof opts.paths === 'function') {\n return opts.paths(\n request,\n start,\n function () { return getNodeModulesDirs(start, modules); },\n opts\n );\n }\n\n var dirs = getNodeModulesDirs(start, modules);\n return opts && opts.paths ? dirs.concat(opts.paths) : dirs;\n};\n","// Info: this file has been generated by Yarn with the approval of the\n// `resolve` maintainers. Bugs caused by a code located here should be\n// opened against the Yarn repository.\n\nconst path = require(`path`);\n\nmodule.exports = function (_, opts) {\n opts = opts || {};\n\n if (opts.forceNodeResolution || !process.versions.pnp)\n return opts;\n\n // It would be nice if we could throw, but that would break the transparent\n // compatibility with packages that use `resolve` today (such as Gulp). Since\n // it's the whole point of this patch, we don't.\n //\n // if (opts.packageIterator || opts.paths)\n // throw new Error(`The \"packageIterator\" and \"paths\" options cannot be used in PnP environments. Set \"forceNodeResolution: true\" if absolutely needed, or branch on process.versions.pnp otherwise.`);\n\n const {findPnpApi} = require(`module`);\n\n const runPnpResolution = (request, basedir) => {\n // Extract the name of the package being requested (1=package name, 2=internal path)\n const parts = request.match(/^((?:@[^/]+\\/)?[^/]+)(\\/.*)?/);\n if (!parts)\n throw new Error(`Assertion failed: Expected the \"resolve\" package to call the \"paths\" callback with package names only (got \"${request}\")`);\n\n // Make sure that basedir ends with a slash\n if (basedir.charAt(basedir.length - 1) !== `/`)\n basedir = path.join(basedir, `/`);\n\n const api = findPnpApi(basedir);\n if (api === null)\n return undefined;\n\n // This is guaranteed to return the path to the \"package.json\" file from the given package\n let manifestPath;\n try {\n manifestPath = api.resolveToUnqualified(`${parts[1]}/package.json`, basedir, {considerBuiltins: false});\n } catch (err) {\n return null;\n }\n\n if (manifestPath === null)\n throw new Error(`Assertion failed: The resolution thinks that \"${parts[1]}\" is a Node builtin`);\n\n // Strip the package.json to get the package folder\n const packagePath = path.dirname(manifestPath);\n\n // Attach the internal path to the resolved package directory\n const unqualifiedPath = typeof parts[2] !== `undefined`\n ? path.join(packagePath, parts[2])\n : packagePath;\n\n return {packagePath, unqualifiedPath};\n };\n\n const runPnpResolutionOnArray = (request, paths) => {\n for (let i = 0; i < paths.length; i++) {\n const resolution = runPnpResolution(request, paths[i]);\n if (resolution || i === paths.length - 1) {\n return resolution;\n }\n }\n\n return null;\n };\n\n const originalPaths = Array.isArray(opts.paths) ? opts.paths : [];\n\n const packageIterator = (request, basedir, getCandidates, opts) => {\n const pathsToTest = [basedir].concat(originalPaths);\n const resolution = runPnpResolutionOnArray(request, pathsToTest);\n if (resolution == null)\n return getCandidates();\n\n return [resolution.unqualifiedPath];\n };\n\n const paths = (request, basedir, getNodeModulePaths, opts) => {\n const pathsToTest = [basedir].concat(originalPaths);\n const resolution = runPnpResolutionOnArray(request, pathsToTest);\n if (resolution == null)\n return getNodeModulePaths().concat(originalPaths);\n\n // Stip the local named folder\n let nodeModules = path.dirname(resolution.packagePath);\n\n // Strip the scope named folder if needed\n if (request.match(/^@[^/]+\\//))\n nodeModules = path.dirname(nodeModules);\n\n return [nodeModules];\n };\n\n // We need to keep track whether we're in `packageIterator` or not so that\n // the code is compatible with both `resolve` 1.9+ and `resolve` 1.15+\n let isInsideIterator = false;\n\n if (!opts.__skipPackageIterator) {\n opts.packageIterator = function (request, basedir, getCandidates, opts) {\n isInsideIterator = true;\n try {\n return packageIterator(request, basedir, getCandidates, opts);\n } finally {\n isInsideIterator = false;\n }\n };\n }\n\n opts.paths = function (request, basedir, getNodeModulePaths, opts) {\n if (isInsideIterator)\n return getNodeModulePaths().concat(originalPaths);\n\n return paths(request, basedir, getNodeModulePaths, opts);\n };\n\n return opts;\n};\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar toStr = Object.prototype.toString;\nvar max = Math.max;\nvar funcType = '[object Function]';\n\nvar concatty = function concatty(a, b) {\n var arr = [];\n\n for (var i = 0; i < a.length; i += 1) {\n arr[i] = a[i];\n }\n for (var j = 0; j < b.length; j += 1) {\n arr[j + a.length] = b[j];\n }\n\n return arr;\n};\n\nvar slicy = function slicy(arrLike, offset) {\n var arr = [];\n for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {\n arr[j] = arrLike[i];\n }\n return arr;\n};\n\nvar joiny = function (arr, joiner) {\n var str = '';\n for (var i = 0; i < arr.length; i += 1) {\n str += arr[i];\n if (i + 1 < arr.length) {\n str += joiner;\n }\n }\n return str;\n};\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.apply(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slicy(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n concatty(args, arguments)\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n }\n return target.apply(\n that,\n concatty(args, arguments)\n );\n\n };\n\n var boundLength = max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs[i] = '$' + i;\n }\n\n bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","'use strict';\n\nvar call = Function.prototype.call;\nvar $hasOwn = Object.prototype.hasOwnProperty;\nvar bind = require('function-bind');\n\n/** @type {import('.')} */\nmodule.exports = bind.call(call, $hasOwn);\n","{\n\t\"assert\": true,\n\t\"node:assert\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"assert/strict\": \">= 15\",\n\t\"node:assert/strict\": \">= 16\",\n\t\"async_hooks\": \">= 8\",\n\t\"node:async_hooks\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"buffer_ieee754\": \">= 0.5 && < 0.9.7\",\n\t\"buffer\": true,\n\t\"node:buffer\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"child_process\": true,\n\t\"node:child_process\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"cluster\": \">= 0.5\",\n\t\"node:cluster\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"console\": true,\n\t\"node:console\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"constants\": true,\n\t\"node:constants\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"crypto\": true,\n\t\"node:crypto\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_debug_agent\": \">= 1 && < 8\",\n\t\"_debugger\": \"< 8\",\n\t\"dgram\": true,\n\t\"node:dgram\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"diagnostics_channel\": [\">= 14.17 && < 15\", \">= 15.1\"],\n\t\"node:diagnostics_channel\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"dns\": true,\n\t\"node:dns\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"dns/promises\": \">= 15\",\n\t\"node:dns/promises\": \">= 16\",\n\t\"domain\": \">= 0.7.12\",\n\t\"node:domain\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"events\": true,\n\t\"node:events\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"freelist\": \"< 6\",\n\t\"fs\": true,\n\t\"node:fs\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"fs/promises\": [\">= 10 && < 10.1\", \">= 14\"],\n\t\"node:fs/promises\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_agent\": \">= 0.11.1\",\n\t\"node:_http_agent\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_client\": \">= 0.11.1\",\n\t\"node:_http_client\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_common\": \">= 0.11.1\",\n\t\"node:_http_common\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_incoming\": \">= 0.11.1\",\n\t\"node:_http_incoming\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_outgoing\": \">= 0.11.1\",\n\t\"node:_http_outgoing\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_server\": \">= 0.11.1\",\n\t\"node:_http_server\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"http\": true,\n\t\"node:http\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"http2\": \">= 8.8\",\n\t\"node:http2\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"https\": true,\n\t\"node:https\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"inspector\": \">= 8\",\n\t\"node:inspector\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"inspector/promises\": [\">= 19\"],\n\t\"node:inspector/promises\": [\">= 19\"],\n\t\"_linklist\": \"< 8\",\n\t\"module\": true,\n\t\"node:module\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"net\": true,\n\t\"node:net\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"node-inspect/lib/_inspect\": \">= 7.6 && < 12\",\n\t\"node-inspect/lib/internal/inspect_client\": \">= 7.6 && < 12\",\n\t\"node-inspect/lib/internal/inspect_repl\": \">= 7.6 && < 12\",\n\t\"os\": true,\n\t\"node:os\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"path\": true,\n\t\"node:path\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"path/posix\": \">= 15.3\",\n\t\"node:path/posix\": \">= 16\",\n\t\"path/win32\": \">= 15.3\",\n\t\"node:path/win32\": \">= 16\",\n\t\"perf_hooks\": \">= 8.5\",\n\t\"node:perf_hooks\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"process\": \">= 1\",\n\t\"node:process\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"punycode\": \">= 0.5\",\n\t\"node:punycode\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"querystring\": true,\n\t\"node:querystring\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"readline\": true,\n\t\"node:readline\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"readline/promises\": \">= 17\",\n\t\"node:readline/promises\": \">= 17\",\n\t\"repl\": true,\n\t\"node:repl\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"node:sea\": [\">= 20.12 && < 21\", \">= 21.7\"],\n\t\"smalloc\": \">= 0.11.5 && < 3\",\n\t\"_stream_duplex\": \">= 0.9.4\",\n\t\"node:_stream_duplex\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_transform\": \">= 0.9.4\",\n\t\"node:_stream_transform\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_wrap\": \">= 1.4.1\",\n\t\"node:_stream_wrap\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_passthrough\": \">= 0.9.4\",\n\t\"node:_stream_passthrough\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_readable\": \">= 0.9.4\",\n\t\"node:_stream_readable\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_writable\": \">= 0.9.4\",\n\t\"node:_stream_writable\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"stream\": true,\n\t\"node:stream\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"stream/consumers\": \">= 16.7\",\n\t\"node:stream/consumers\": \">= 16.7\",\n\t\"stream/promises\": \">= 15\",\n\t\"node:stream/promises\": \">= 16\",\n\t\"stream/web\": \">= 16.5\",\n\t\"node:stream/web\": \">= 16.5\",\n\t\"string_decoder\": true,\n\t\"node:string_decoder\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"sys\": [\">= 0.4 && < 0.7\", \">= 0.8\"],\n\t\"node:sys\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"test/reporters\": \">= 19.9 && < 20.2\",\n\t\"node:test/reporters\": [\">= 18.17 && < 19\", \">= 19.9\", \">= 20\"],\n\t\"test/mock_loader\": \">= 22.3 && < 22.7\",\n\t\"node:test/mock_loader\": \">= 22.3 && < 22.7\",\n\t\"node:test\": [\">= 16.17 && < 17\", \">= 18\"],\n\t\"timers\": true,\n\t\"node:timers\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"timers/promises\": \">= 15\",\n\t\"node:timers/promises\": \">= 16\",\n\t\"_tls_common\": \">= 0.11.13\",\n\t\"node:_tls_common\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_tls_legacy\": \">= 0.11.3 && < 10\",\n\t\"_tls_wrap\": \">= 0.11.3\",\n\t\"node:_tls_wrap\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"tls\": true,\n\t\"node:tls\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"trace_events\": \">= 10\",\n\t\"node:trace_events\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"tty\": true,\n\t\"node:tty\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"url\": true,\n\t\"node:url\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"util\": true,\n\t\"node:util\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"util/types\": \">= 15.3\",\n\t\"node:util/types\": \">= 16\",\n\t\"v8/tools/arguments\": \">= 10 && < 12\",\n\t\"v8/tools/codemap\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/consarray\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/csvparser\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/logreader\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/profile_view\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/splaytree\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8\": \">= 1\",\n\t\"node:v8\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"vm\": true,\n\t\"node:vm\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"wasi\": [\">= 13.4 && < 13.5\", \">= 18.17 && < 19\", \">= 20\"],\n\t\"node:wasi\": [\">= 18.17 && < 19\", \">= 20\"],\n\t\"worker_threads\": \">= 11.7\",\n\t\"node:worker_threads\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"zlib\": \">= 0.5\",\n\t\"node:zlib\": [\">= 14.18 && < 15\", \">= 16\"]\n}\n","'use strict';\n\nvar hasOwn = require('hasown');\n\nfunction specifierIncluded(current, specifier) {\n\tvar nodeParts = current.split('.');\n\tvar parts = specifier.split(' ');\n\tvar op = parts.length > 1 ? parts[0] : '=';\n\tvar versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');\n\n\tfor (var i = 0; i < 3; ++i) {\n\t\tvar cur = parseInt(nodeParts[i] || 0, 10);\n\t\tvar ver = parseInt(versionParts[i] || 0, 10);\n\t\tif (cur === ver) {\n\t\t\tcontinue; // eslint-disable-line no-restricted-syntax, no-continue\n\t\t}\n\t\tif (op === '<') {\n\t\t\treturn cur < ver;\n\t\t}\n\t\tif (op === '>=') {\n\t\t\treturn cur >= ver;\n\t\t}\n\t\treturn false;\n\t}\n\treturn op === '>=';\n}\n\nfunction matchesRange(current, range) {\n\tvar specifiers = range.split(/ ?&& ?/);\n\tif (specifiers.length === 0) {\n\t\treturn false;\n\t}\n\tfor (var i = 0; i < specifiers.length; ++i) {\n\t\tif (!specifierIncluded(current, specifiers[i])) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nfunction versionIncluded(nodeVersion, specifierValue) {\n\tif (typeof specifierValue === 'boolean') {\n\t\treturn specifierValue;\n\t}\n\n\tvar current = typeof nodeVersion === 'undefined'\n\t\t? process.versions && process.versions.node\n\t\t: nodeVersion;\n\n\tif (typeof current !== 'string') {\n\t\tthrow new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');\n\t}\n\n\tif (specifierValue && typeof specifierValue === 'object') {\n\t\tfor (var i = 0; i < specifierValue.length; ++i) {\n\t\t\tif (matchesRange(current, specifierValue[i])) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\treturn matchesRange(current, specifierValue);\n}\n\nvar data = require('./core.json');\n\nmodule.exports = function isCore(x, nodeVersion) {\n\treturn hasOwn(data, x) && versionIncluded(nodeVersion, data[x]);\n};\n","var fs = require('fs');\nvar getHomedir = require('./homedir');\nvar path = require('path');\nvar caller = require('./caller');\nvar nodeModulesPaths = require('./node-modules-paths');\nvar normalizeOptions = require('./normalize-options');\nvar isCore = require('is-core-module');\n\nvar realpathFS = process.platform !== 'win32' && fs.realpath && typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;\n\nvar homedir = getHomedir();\nvar defaultPaths = function () {\n return [\n path.join(homedir, '.node_modules'),\n path.join(homedir, '.node_libraries')\n ];\n};\n\nvar defaultIsFile = function isFile(file, cb) {\n fs.stat(file, function (err, stat) {\n if (!err) {\n return cb(null, stat.isFile() || stat.isFIFO());\n }\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);\n return cb(err);\n });\n};\n\nvar defaultIsDir = function isDirectory(dir, cb) {\n fs.stat(dir, function (err, stat) {\n if (!err) {\n return cb(null, stat.isDirectory());\n }\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);\n return cb(err);\n });\n};\n\nvar defaultRealpath = function realpath(x, cb) {\n realpathFS(x, function (realpathErr, realPath) {\n if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);\n else cb(null, realpathErr ? x : realPath);\n });\n};\n\nvar maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {\n if (opts && opts.preserveSymlinks === false) {\n realpath(x, cb);\n } else {\n cb(null, x);\n }\n};\n\nvar defaultReadPackage = function defaultReadPackage(readFile, pkgfile, cb) {\n readFile(pkgfile, function (readFileErr, body) {\n if (readFileErr) cb(readFileErr);\n else {\n try {\n var pkg = JSON.parse(body);\n cb(null, pkg);\n } catch (jsonErr) {\n cb(null);\n }\n }\n });\n};\n\nvar getPackageCandidates = function getPackageCandidates(x, start, opts) {\n var dirs = nodeModulesPaths(start, opts, x);\n for (var i = 0; i < dirs.length; i++) {\n dirs[i] = path.join(dirs[i], x);\n }\n return dirs;\n};\n\nmodule.exports = function resolve(x, options, callback) {\n var cb = callback;\n var opts = options;\n if (typeof options === 'function') {\n cb = opts;\n opts = {};\n }\n if (typeof x !== 'string') {\n var err = new TypeError('Path must be a string.');\n return process.nextTick(function () {\n cb(err);\n });\n }\n\n opts = normalizeOptions(x, opts);\n\n var isFile = opts.isFile || defaultIsFile;\n var isDirectory = opts.isDirectory || defaultIsDir;\n var readFile = opts.readFile || fs.readFile;\n var realpath = opts.realpath || defaultRealpath;\n var readPackage = opts.readPackage || defaultReadPackage;\n if (opts.readFile && opts.readPackage) {\n var conflictErr = new TypeError('`readFile` and `readPackage` are mutually exclusive.');\n return process.nextTick(function () {\n cb(conflictErr);\n });\n }\n var packageIterator = opts.packageIterator;\n\n var extensions = opts.extensions || ['.js'];\n var includeCoreModules = opts.includeCoreModules !== false;\n var basedir = opts.basedir || path.dirname(caller());\n var parent = opts.filename || basedir;\n\n opts.paths = opts.paths || defaultPaths();\n\n // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory\n var absoluteStart = path.resolve(basedir);\n\n maybeRealpath(\n realpath,\n absoluteStart,\n opts,\n function (err, realStart) {\n if (err) cb(err);\n else init(realStart);\n }\n );\n\n var res;\n function init(basedir) {\n if ((/^(?:\\.\\.?(?:\\/|$)|\\/|([A-Za-z]:)?[/\\\\])/).test(x)) {\n res = path.resolve(basedir, x);\n if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';\n if ((/\\/$/).test(x) && res === basedir) {\n loadAsDirectory(res, opts.package, onfile);\n } else loadAsFile(res, opts.package, onfile);\n } else if (includeCoreModules && isCore(x)) {\n return cb(null, x);\n } else loadNodeModules(x, basedir, function (err, n, pkg) {\n if (err) cb(err);\n else if (n) {\n return maybeRealpath(realpath, n, opts, function (err, realN) {\n if (err) {\n cb(err);\n } else {\n cb(null, realN, pkg);\n }\n });\n } else {\n var moduleError = new Error(\"Cannot find module '\" + x + \"' from '\" + parent + \"'\");\n moduleError.code = 'MODULE_NOT_FOUND';\n cb(moduleError);\n }\n });\n }\n\n function onfile(err, m, pkg) {\n if (err) cb(err);\n else if (m) cb(null, m, pkg);\n else loadAsDirectory(res, function (err, d, pkg) {\n if (err) cb(err);\n else if (d) {\n maybeRealpath(realpath, d, opts, function (err, realD) {\n if (err) {\n cb(err);\n } else {\n cb(null, realD, pkg);\n }\n });\n } else {\n var moduleError = new Error(\"Cannot find module '\" + x + \"' from '\" + parent + \"'\");\n moduleError.code = 'MODULE_NOT_FOUND';\n cb(moduleError);\n }\n });\n }\n\n function loadAsFile(x, thePackage, callback) {\n var loadAsFilePackage = thePackage;\n var cb = callback;\n if (typeof loadAsFilePackage === 'function') {\n cb = loadAsFilePackage;\n loadAsFilePackage = undefined;\n }\n\n var exts = [''].concat(extensions);\n load(exts, x, loadAsFilePackage);\n\n function load(exts, x, loadPackage) {\n if (exts.length === 0) return cb(null, undefined, loadPackage);\n var file = x + exts[0];\n\n var pkg = loadPackage;\n if (pkg) onpkg(null, pkg);\n else loadpkg(path.dirname(file), onpkg);\n\n function onpkg(err, pkg_, dir) {\n pkg = pkg_;\n if (err) return cb(err);\n if (dir && pkg && opts.pathFilter) {\n var rfile = path.relative(dir, file);\n var rel = rfile.slice(0, rfile.length - exts[0].length);\n var r = opts.pathFilter(pkg, x, rel);\n if (r) return load(\n [''].concat(extensions.slice()),\n path.resolve(dir, r),\n pkg\n );\n }\n isFile(file, onex);\n }\n function onex(err, ex) {\n if (err) return cb(err);\n if (ex) return cb(null, file, pkg);\n load(exts.slice(1), x, pkg);\n }\n }\n }\n\n function loadpkg(dir, cb) {\n if (dir === '' || dir === '/') return cb(null);\n if (process.platform === 'win32' && (/^\\w:[/\\\\]*$/).test(dir)) {\n return cb(null);\n }\n if ((/[/\\\\]node_modules[/\\\\]*$/).test(dir)) return cb(null);\n\n maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {\n if (unwrapErr) return loadpkg(path.dirname(dir), cb);\n var pkgfile = path.join(pkgdir, 'package.json');\n isFile(pkgfile, function (err, ex) {\n // on err, ex is false\n if (!ex) return loadpkg(path.dirname(dir), cb);\n\n readPackage(readFile, pkgfile, function (err, pkgParam) {\n if (err) cb(err);\n\n var pkg = pkgParam;\n\n if (pkg && opts.packageFilter) {\n pkg = opts.packageFilter(pkg, pkgfile);\n }\n cb(null, pkg, dir);\n });\n });\n });\n }\n\n function loadAsDirectory(x, loadAsDirectoryPackage, callback) {\n var cb = callback;\n var fpkg = loadAsDirectoryPackage;\n if (typeof fpkg === 'function') {\n cb = fpkg;\n fpkg = opts.package;\n }\n\n maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {\n if (unwrapErr) return cb(unwrapErr);\n var pkgfile = path.join(pkgdir, 'package.json');\n isFile(pkgfile, function (err, ex) {\n if (err) return cb(err);\n if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);\n\n readPackage(readFile, pkgfile, function (err, pkgParam) {\n if (err) return cb(err);\n\n var pkg = pkgParam;\n\n if (pkg && opts.packageFilter) {\n pkg = opts.packageFilter(pkg, pkgfile);\n }\n\n if (pkg && pkg.main) {\n if (typeof pkg.main !== 'string') {\n var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');\n mainError.code = 'INVALID_PACKAGE_MAIN';\n return cb(mainError);\n }\n if (pkg.main === '.' || pkg.main === './') {\n pkg.main = 'index';\n }\n loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {\n if (err) return cb(err);\n if (m) return cb(null, m, pkg);\n if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);\n\n var dir = path.resolve(x, pkg.main);\n loadAsDirectory(dir, pkg, function (err, n, pkg) {\n if (err) return cb(err);\n if (n) return cb(null, n, pkg);\n loadAsFile(path.join(x, 'index'), pkg, cb);\n });\n });\n return;\n }\n\n loadAsFile(path.join(x, '/index'), pkg, cb);\n });\n });\n });\n }\n\n function processDirs(cb, dirs) {\n if (dirs.length === 0) return cb(null, undefined);\n var dir = dirs[0];\n\n isDirectory(path.dirname(dir), isdir);\n\n function isdir(err, isdir) {\n if (err) return cb(err);\n if (!isdir) return processDirs(cb, dirs.slice(1));\n loadAsFile(dir, opts.package, onfile);\n }\n\n function onfile(err, m, pkg) {\n if (err) return cb(err);\n if (m) return cb(null, m, pkg);\n loadAsDirectory(dir, opts.package, ondir);\n }\n\n function ondir(err, n, pkg) {\n if (err) return cb(err);\n if (n) return cb(null, n, pkg);\n processDirs(cb, dirs.slice(1));\n }\n }\n function loadNodeModules(x, start, cb) {\n var thunk = function () { return getPackageCandidates(x, start, opts); };\n processDirs(\n cb,\n packageIterator ? packageIterator(x, start, thunk, opts) : thunk()\n );\n }\n};\n","{\n\t\"assert\": true,\n\t\"node:assert\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"assert/strict\": \">= 15\",\n\t\"node:assert/strict\": \">= 16\",\n\t\"async_hooks\": \">= 8\",\n\t\"node:async_hooks\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"buffer_ieee754\": \">= 0.5 && < 0.9.7\",\n\t\"buffer\": true,\n\t\"node:buffer\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"child_process\": true,\n\t\"node:child_process\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"cluster\": \">= 0.5\",\n\t\"node:cluster\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"console\": true,\n\t\"node:console\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"constants\": true,\n\t\"node:constants\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"crypto\": true,\n\t\"node:crypto\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_debug_agent\": \">= 1 && < 8\",\n\t\"_debugger\": \"< 8\",\n\t\"dgram\": true,\n\t\"node:dgram\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"diagnostics_channel\": [\">= 14.17 && < 15\", \">= 15.1\"],\n\t\"node:diagnostics_channel\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"dns\": true,\n\t\"node:dns\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"dns/promises\": \">= 15\",\n\t\"node:dns/promises\": \">= 16\",\n\t\"domain\": \">= 0.7.12\",\n\t\"node:domain\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"events\": true,\n\t\"node:events\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"freelist\": \"< 6\",\n\t\"fs\": true,\n\t\"node:fs\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"fs/promises\": [\">= 10 && < 10.1\", \">= 14\"],\n\t\"node:fs/promises\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_agent\": \">= 0.11.1\",\n\t\"node:_http_agent\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_client\": \">= 0.11.1\",\n\t\"node:_http_client\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_common\": \">= 0.11.1\",\n\t\"node:_http_common\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_incoming\": \">= 0.11.1\",\n\t\"node:_http_incoming\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_outgoing\": \">= 0.11.1\",\n\t\"node:_http_outgoing\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_http_server\": \">= 0.11.1\",\n\t\"node:_http_server\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"http\": true,\n\t\"node:http\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"http2\": \">= 8.8\",\n\t\"node:http2\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"https\": true,\n\t\"node:https\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"inspector\": \">= 8\",\n\t\"node:inspector\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"inspector/promises\": [\">= 19\"],\n\t\"node:inspector/promises\": [\">= 19\"],\n\t\"_linklist\": \"< 8\",\n\t\"module\": true,\n\t\"node:module\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"net\": true,\n\t\"node:net\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"node-inspect/lib/_inspect\": \">= 7.6 && < 12\",\n\t\"node-inspect/lib/internal/inspect_client\": \">= 7.6 && < 12\",\n\t\"node-inspect/lib/internal/inspect_repl\": \">= 7.6 && < 12\",\n\t\"os\": true,\n\t\"node:os\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"path\": true,\n\t\"node:path\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"path/posix\": \">= 15.3\",\n\t\"node:path/posix\": \">= 16\",\n\t\"path/win32\": \">= 15.3\",\n\t\"node:path/win32\": \">= 16\",\n\t\"perf_hooks\": \">= 8.5\",\n\t\"node:perf_hooks\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"process\": \">= 1\",\n\t\"node:process\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"punycode\": \">= 0.5\",\n\t\"node:punycode\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"querystring\": true,\n\t\"node:querystring\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"readline\": true,\n\t\"node:readline\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"readline/promises\": \">= 17\",\n\t\"node:readline/promises\": \">= 17\",\n\t\"repl\": true,\n\t\"node:repl\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"smalloc\": \">= 0.11.5 && < 3\",\n\t\"_stream_duplex\": \">= 0.9.4\",\n\t\"node:_stream_duplex\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_transform\": \">= 0.9.4\",\n\t\"node:_stream_transform\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_wrap\": \">= 1.4.1\",\n\t\"node:_stream_wrap\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_passthrough\": \">= 0.9.4\",\n\t\"node:_stream_passthrough\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_readable\": \">= 0.9.4\",\n\t\"node:_stream_readable\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_stream_writable\": \">= 0.9.4\",\n\t\"node:_stream_writable\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"stream\": true,\n\t\"node:stream\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"stream/consumers\": \">= 16.7\",\n\t\"node:stream/consumers\": \">= 16.7\",\n\t\"stream/promises\": \">= 15\",\n\t\"node:stream/promises\": \">= 16\",\n\t\"stream/web\": \">= 16.5\",\n\t\"node:stream/web\": \">= 16.5\",\n\t\"string_decoder\": true,\n\t\"node:string_decoder\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"sys\": [\">= 0.4 && < 0.7\", \">= 0.8\"],\n\t\"node:sys\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"test/reporters\": \">= 19.9 && < 20.2\",\n\t\"node:test/reporters\": [\">= 18.17 && < 19\", \">= 19.9\", \">= 20\"],\n\t\"node:test\": [\">= 16.17 && < 17\", \">= 18\"],\n\t\"timers\": true,\n\t\"node:timers\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"timers/promises\": \">= 15\",\n\t\"node:timers/promises\": \">= 16\",\n\t\"_tls_common\": \">= 0.11.13\",\n\t\"node:_tls_common\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"_tls_legacy\": \">= 0.11.3 && < 10\",\n\t\"_tls_wrap\": \">= 0.11.3\",\n\t\"node:_tls_wrap\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"tls\": true,\n\t\"node:tls\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"trace_events\": \">= 10\",\n\t\"node:trace_events\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"tty\": true,\n\t\"node:tty\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"url\": true,\n\t\"node:url\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"util\": true,\n\t\"node:util\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"util/types\": \">= 15.3\",\n\t\"node:util/types\": \">= 16\",\n\t\"v8/tools/arguments\": \">= 10 && < 12\",\n\t\"v8/tools/codemap\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/consarray\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/csvparser\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/logreader\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/profile_view\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8/tools/splaytree\": [\">= 4.4 && < 5\", \">= 5.2 && < 12\"],\n\t\"v8\": \">= 1\",\n\t\"node:v8\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"vm\": true,\n\t\"node:vm\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"wasi\": [\">= 13.4 && < 13.5\", \">= 18.17 && < 19\", \">= 20\"],\n\t\"node:wasi\": [\">= 18.17 && < 19\", \">= 20\"],\n\t\"worker_threads\": \">= 11.7\",\n\t\"node:worker_threads\": [\">= 14.18 && < 15\", \">= 16\"],\n\t\"zlib\": \">= 0.5\",\n\t\"node:zlib\": [\">= 14.18 && < 15\", \">= 16\"]\n}\n","'use strict';\n\nvar isCoreModule = require('is-core-module');\nvar data = require('./core.json');\n\nvar core = {};\nfor (var mod in data) { // eslint-disable-line no-restricted-syntax\n if (Object.prototype.hasOwnProperty.call(data, mod)) {\n core[mod] = isCoreModule(mod);\n }\n}\nmodule.exports = core;\n","var isCoreModule = require('is-core-module');\n\nmodule.exports = function isCore(x) {\n return isCoreModule(x);\n};\n","var isCore = require('is-core-module');\nvar fs = require('fs');\nvar path = require('path');\nvar getHomedir = require('./homedir');\nvar caller = require('./caller');\nvar nodeModulesPaths = require('./node-modules-paths');\nvar normalizeOptions = require('./normalize-options');\n\nvar realpathFS = process.platform !== 'win32' && fs.realpathSync && typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;\n\nvar homedir = getHomedir();\nvar defaultPaths = function () {\n return [\n path.join(homedir, '.node_modules'),\n path.join(homedir, '.node_libraries')\n ];\n};\n\nvar defaultIsFile = function isFile(file) {\n try {\n var stat = fs.statSync(file, { throwIfNoEntry: false });\n } catch (e) {\n if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;\n throw e;\n }\n return !!stat && (stat.isFile() || stat.isFIFO());\n};\n\nvar defaultIsDir = function isDirectory(dir) {\n try {\n var stat = fs.statSync(dir, { throwIfNoEntry: false });\n } catch (e) {\n if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;\n throw e;\n }\n return !!stat && stat.isDirectory();\n};\n\nvar defaultRealpathSync = function realpathSync(x) {\n try {\n return realpathFS(x);\n } catch (realpathErr) {\n if (realpathErr.code !== 'ENOENT') {\n throw realpathErr;\n }\n }\n return x;\n};\n\nvar maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {\n if (opts && opts.preserveSymlinks === false) {\n return realpathSync(x);\n }\n return x;\n};\n\nvar defaultReadPackageSync = function defaultReadPackageSync(readFileSync, pkgfile) {\n var body = readFileSync(pkgfile);\n try {\n var pkg = JSON.parse(body);\n return pkg;\n } catch (jsonErr) {}\n};\n\nvar getPackageCandidates = function getPackageCandidates(x, start, opts) {\n var dirs = nodeModulesPaths(start, opts, x);\n for (var i = 0; i < dirs.length; i++) {\n dirs[i] = path.join(dirs[i], x);\n }\n return dirs;\n};\n\nmodule.exports = function resolveSync(x, options) {\n if (typeof x !== 'string') {\n throw new TypeError('Path must be a string.');\n }\n var opts = normalizeOptions(x, options);\n\n var isFile = opts.isFile || defaultIsFile;\n var readFileSync = opts.readFileSync || fs.readFileSync;\n var isDirectory = opts.isDirectory || defaultIsDir;\n var realpathSync = opts.realpathSync || defaultRealpathSync;\n var readPackageSync = opts.readPackageSync || defaultReadPackageSync;\n if (opts.readFileSync && opts.readPackageSync) {\n throw new TypeError('`readFileSync` and `readPackageSync` are mutually exclusive.');\n }\n var packageIterator = opts.packageIterator;\n\n var extensions = opts.extensions || ['.js'];\n var includeCoreModules = opts.includeCoreModules !== false;\n var basedir = opts.basedir || path.dirname(caller());\n var parent = opts.filename || basedir;\n\n opts.paths = opts.paths || defaultPaths();\n\n // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory\n var absoluteStart = maybeRealpathSync(realpathSync, path.resolve(basedir), opts);\n\n if ((/^(?:\\.\\.?(?:\\/|$)|\\/|([A-Za-z]:)?[/\\\\])/).test(x)) {\n var res = path.resolve(absoluteStart, x);\n if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';\n var m = loadAsFileSync(res) || loadAsDirectorySync(res);\n if (m) return maybeRealpathSync(realpathSync, m, opts);\n } else if (includeCoreModules && isCore(x)) {\n return x;\n } else {\n var n = loadNodeModulesSync(x, absoluteStart);\n if (n) return maybeRealpathSync(realpathSync, n, opts);\n }\n\n var err = new Error(\"Cannot find module '\" + x + \"' from '\" + parent + \"'\");\n err.code = 'MODULE_NOT_FOUND';\n throw err;\n\n function loadAsFileSync(x) {\n var pkg = loadpkg(path.dirname(x));\n\n if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {\n var rfile = path.relative(pkg.dir, x);\n var r = opts.pathFilter(pkg.pkg, x, rfile);\n if (r) {\n x = path.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign\n }\n }\n\n if (isFile(x)) {\n return x;\n }\n\n for (var i = 0; i < extensions.length; i++) {\n var file = x + extensions[i];\n if (isFile(file)) {\n return file;\n }\n }\n }\n\n function loadpkg(dir) {\n if (dir === '' || dir === '/') return;\n if (process.platform === 'win32' && (/^\\w:[/\\\\]*$/).test(dir)) {\n return;\n }\n if ((/[/\\\\]node_modules[/\\\\]*$/).test(dir)) return;\n\n var pkgfile = path.join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');\n\n if (!isFile(pkgfile)) {\n return loadpkg(path.dirname(dir));\n }\n\n var pkg = readPackageSync(readFileSync, pkgfile);\n\n if (pkg && opts.packageFilter) {\n // v2 will pass pkgfile\n pkg = opts.packageFilter(pkg, /*pkgfile,*/ dir); // eslint-disable-line spaced-comment\n }\n\n return { pkg: pkg, dir: dir };\n }\n\n function loadAsDirectorySync(x) {\n var pkgfile = path.join(maybeRealpathSync(realpathSync, x, opts), '/package.json');\n if (isFile(pkgfile)) {\n try {\n var pkg = readPackageSync(readFileSync, pkgfile);\n } catch (e) {}\n\n if (pkg && opts.packageFilter) {\n // v2 will pass pkgfile\n pkg = opts.packageFilter(pkg, /*pkgfile,*/ x); // eslint-disable-line spaced-comment\n }\n\n if (pkg && pkg.main) {\n if (typeof pkg.main !== 'string') {\n var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');\n mainError.code = 'INVALID_PACKAGE_MAIN';\n throw mainError;\n }\n if (pkg.main === '.' || pkg.main === './') {\n pkg.main = 'index';\n }\n try {\n var m = loadAsFileSync(path.resolve(x, pkg.main));\n if (m) return m;\n var n = loadAsDirectorySync(path.resolve(x, pkg.main));\n if (n) return n;\n } catch (e) {}\n }\n }\n\n return loadAsFileSync(path.join(x, '/index'));\n }\n\n function loadNodeModulesSync(x, start) {\n var thunk = function () { return getPackageCandidates(x, start, opts); };\n var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();\n\n for (var i = 0; i < dirs.length; i++) {\n var dir = dirs[i];\n if (isDirectory(path.dirname(dir))) {\n var m = loadAsFileSync(dir);\n if (m) return m;\n var n = loadAsDirectorySync(dir);\n if (n) return n;\n }\n }\n }\n};\n","var async = require('./lib/async');\nasync.core = require('./lib/core');\nasync.isCore = require('./lib/is-core');\nasync.sync = require('./lib/sync');\n\nmodule.exports = async;\n","'use strict'\n\nvar path = require('path')\n\nmodule.exports = function (file) {\n var segments = file.split(path.sep)\n var index = segments.lastIndexOf('node_modules')\n if (index === -1) return\n if (!segments[index + 1]) return\n var scoped = segments[index + 1][0] === '@'\n var name = scoped ? segments[index + 1] + '/' + segments[index + 2] : segments[index + 1]\n var offset = scoped ? 3 : 2\n return {\n name: name,\n basedir: segments.slice(0, index + offset).join(path.sep),\n path: segments.slice(index + offset).join(path.sep)\n }\n}\n","{\n \"name\": \"require-in-the-middle\",\n \"version\": \"7.4.0\",\n \"description\": \"Module to hook into the Node.js require function\",\n \"main\": \"index.js\",\n \"types\": \"types/index.d.ts\",\n \"dependencies\": {\n \"debug\": \"^4.3.5\",\n \"module-details-from-path\": \"^1.0.3\",\n \"resolve\": \"^1.22.8\"\n },\n \"devDependencies\": {\n \"@babel/core\": \"^7.9.0\",\n \"@babel/preset-env\": \"^7.9.5\",\n \"@babel/preset-typescript\": \"^7.9.0\",\n \"@babel/register\": \"^7.9.0\",\n \"ipp-printer\": \"^1.0.0\",\n \"patterns\": \"^1.0.3\",\n \"roundround\": \"^0.2.0\",\n \"semver\": \"^6.3.0\",\n \"standard\": \"^14.3.1\",\n \"tape\": \"^4.11.0\"\n },\n \"scripts\": {\n \"test\": \"npm run test:lint && npm run test:tape && npm run test:babel\",\n \"test:lint\": \"standard\",\n \"test:tape\": \"tape test/*.js\",\n \"test:babel\": \"node test/babel/babel-register.js\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/elastic/require-in-the-middle.git\"\n },\n \"keywords\": [\n \"require\",\n \"hook\",\n \"shim\",\n \"shimmer\",\n \"shimming\",\n \"patch\",\n \"monkey\",\n \"monkeypatch\",\n \"module\",\n \"load\"\n ],\n \"files\": [\n \"types\"\n ],\n \"author\": \"Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/elastic/require-in-the-middle/issues\"\n },\n \"homepage\": \"https://github.com/elastic/require-in-the-middle#readme\",\n \"engines\": {\n \"node\": \">=8.6.0\"\n }\n}\n","'use strict'\n\nconst path = require('path')\nconst Module = require('module')\nconst resolve = require('resolve')\nconst debug = require('debug')('require-in-the-middle')\nconst moduleDetailsFromPath = require('module-details-from-path')\n\n// Using the default export is discouraged, but kept for backward compatibility.\n// Use this instead:\n// const { Hook } = require('require-in-the-middle')\nmodule.exports = Hook\nmodule.exports.Hook = Hook\n\n/**\n * Is the given module a \"core\" module?\n * https://nodejs.org/api/modules.html#core-modules\n *\n * @type {(moduleName: string) => boolean}\n */\nlet isCore\nif (Module.isBuiltin) { // Added in node v18.6.0, v16.17.0\n isCore = Module.isBuiltin\n} else {\n const [major, minor] = process.versions.node.split('.').map(Number)\n if (major === 8 && minor < 8) {\n // For node versions `[8.0, 8.8)` the \"http2\" module was built-in but\n // behind the `--expose-http2` flag. `resolve` only considers unflagged\n // modules to be core: https://github.com/browserify/resolve/issues/139\n // However, for `ExportsCache` to work for \"http2\" we need it to be\n // considered core.\n isCore = moduleName => {\n if (moduleName === 'http2') {\n return true\n }\n // Prefer `resolve.core` lookup to `resolve.isCore(moduleName)` because\n // the latter is doing version range matches for every call.\n return !!resolve.core[moduleName]\n }\n } else {\n isCore = moduleName => {\n // Prefer `resolve.core` lookup to `resolve.isCore(moduleName)` because\n // the latter is doing version range matches for every call.\n return !!resolve.core[moduleName]\n }\n }\n}\n\n// 'foo/bar.js' or 'foo/bar/index.js' => 'foo/bar'\nconst normalize = /([/\\\\]index)?(\\.js)?$/\n\n// Cache `onrequire`-patched exports for modules.\n//\n// Exports for built-in (a.k.a. \"core\") modules are stored in an internal Map.\n//\n// Exports for non-core modules are stored on a private field on the `Module`\n// object in `require.cache`. This allows users to delete from `require.cache`\n// to trigger a re-load (and re-run of the hook's `onrequire`) of a module the\n// next time it is required.\n// https://nodejs.org/docs/latest/api/all.html#all_modules_requirecache\n//\n// In some special cases -- e.g. some other `require()` hook swapping out\n// `Module._cache` like `@babel/register` -- a non-core module won't be in\n// `require.cache`. In that case this falls back to caching on the internal Map.\nclass ExportsCache {\n constructor () {\n this._localCache = new Map() // <module filename or id> -> <exports>\n this._kRitmExports = Symbol('RitmExports')\n }\n\n has (filename, isBuiltin) {\n if (this._localCache.has(filename)) {\n return true\n } else if (!isBuiltin) {\n const mod = require.cache[filename]\n return !!(mod && this._kRitmExports in mod)\n } else {\n return false\n }\n }\n\n get (filename, isBuiltin) {\n const cachedExports = this._localCache.get(filename)\n if (cachedExports !== undefined) {\n return cachedExports\n } else if (!isBuiltin) {\n const mod = require.cache[filename]\n return (mod && mod[this._kRitmExports])\n }\n }\n\n set (filename, exports, isBuiltin) {\n if (isBuiltin) {\n this._localCache.set(filename, exports)\n } else if (filename in require.cache) {\n require.cache[filename][this._kRitmExports] = exports\n } else {\n debug('non-core module is unexpectedly not in require.cache: \"%s\"', filename)\n this._localCache.set(filename, exports)\n }\n }\n}\n\nfunction Hook (modules, options, onrequire) {\n if ((this instanceof Hook) === false) return new Hook(modules, options, onrequire)\n if (typeof modules === 'function') {\n onrequire = modules\n modules = null\n options = null\n } else if (typeof options === 'function') {\n onrequire = options\n options = null\n }\n\n if (typeof Module._resolveFilename !== 'function') {\n console.error('Error: Expected Module._resolveFilename to be a function (was: %s) - aborting!', typeof Module._resolveFilename)\n console.error('Please report this error as an issue related to Node.js %s at %s', process.version, require('./package.json').bugs.url)\n return\n }\n\n this._cache = new ExportsCache()\n\n this._unhooked = false\n this._origRequire = Module.prototype.require\n\n const self = this\n const patching = new Set()\n const internals = options ? options.internals === true : false\n const hasWhitelist = Array.isArray(modules)\n\n debug('registering require hook')\n\n this._require = Module.prototype.require = function (id) {\n if (self._unhooked === true) {\n // if the patched require function could not be removed because\n // someone else patched it after it was patched here, we just\n // abort and pass the request onwards to the original require\n debug('ignoring require call - module is soft-unhooked')\n return self._origRequire.apply(this, arguments)\n }\n\n return patchedRequire.call(this, arguments, false)\n }\n\n if (typeof process.getBuiltinModule === 'function') {\n this._origGetBuiltinModule = process.getBuiltinModule\n this._getBuiltinModule = process.getBuiltinModule = function (id) {\n if (self._unhooked === true) {\n // if the patched process.getBuiltinModule function could not be removed because\n // someone else patched it after it was patched here, we just abort and pass the\n // request onwards to the original process.getBuiltinModule\n debug('ignoring process.getBuiltinModule call - module is soft-unhooked')\n return self._origGetBuiltinModule.apply(this, arguments)\n }\n\n return patchedRequire.call(this, arguments, true)\n }\n }\n\n // Preserve the original require/process.getBuiltinModule arguments in `args`\n function patchedRequire (args, coreOnly) {\n const id = args[0]\n const core = isCore(id)\n let filename // the string used for caching\n if (core) {\n filename = id\n // If this is a builtin module that can be identified both as 'foo' and\n // 'node:foo', then prefer 'foo' as the caching key.\n if (id.startsWith('node:')) {\n const idWithoutPrefix = id.slice(5)\n if (isCore(idWithoutPrefix)) {\n filename = idWithoutPrefix\n }\n }\n } else if (coreOnly) {\n // `coreOnly` is `true` if this was a call to `process.getBuiltinModule`, in which case\n // we don't want to return anything if the requested `id` isn't a core module. Falling\n // back to default behaviour, which at the time of this wrting is simply returning `undefined`\n debug('call to process.getBuiltinModule with unknown built-in id')\n return self._origGetBuiltinModule.apply(this, args)\n } else {\n try {\n filename = Module._resolveFilename(id, this)\n } catch (resolveErr) {\n // If someone *else* monkey-patches before this monkey-patch, then that\n // code might expect `require(someId)` to get through so it can be\n // handled, even if `someId` cannot be resolved to a filename. In this\n // case, instead of throwing we defer to the underlying `require`.\n //\n // For example the Azure Functions Node.js worker module does this,\n // where `@azure/functions-core` resolves to an internal object.\n // https://github.com/Azure/azure-functions-nodejs-worker/blob/v3.5.2/src/setupCoreModule.ts#L46-L54\n debug('Module._resolveFilename(\"%s\") threw %j, calling original Module.require', id, resolveErr.message)\n return self._origRequire.apply(this, args)\n }\n }\n\n let moduleName, basedir\n\n debug('processing %s module require(\\'%s\\'): %s', core === true ? 'core' : 'non-core', id, filename)\n\n // return known patched modules immediately\n if (self._cache.has(filename, core) === true) {\n debug('returning already patched cached module: %s', filename)\n return self._cache.get(filename, core)\n }\n\n // Check if this module has a patcher in-progress already.\n // Otherwise, mark this module as patching in-progress.\n const isPatching = patching.has(filename)\n if (isPatching === false) {\n patching.add(filename)\n }\n\n const exports = coreOnly\n ? self._origGetBuiltinModule.apply(this, args)\n : self._origRequire.apply(this, args)\n\n // If it's already patched, just return it as-is.\n if (isPatching === true) {\n debug('module is in the process of being patched already - ignoring: %s', filename)\n return exports\n }\n\n // The module has already been loaded,\n // so the patching mark can be cleaned up.\n patching.delete(filename)\n\n if (core === true) {\n if (hasWhitelist === true && modules.includes(filename) === false) {\n debug('ignoring core module not on whitelist: %s', filename)\n return exports // abort if module name isn't on whitelist\n }\n moduleName = filename\n } else if (hasWhitelist === true && modules.includes(filename)) {\n // whitelist includes the absolute path to the file including extension\n const parsedPath = path.parse(filename)\n moduleName = parsedPath.name\n basedir = parsedPath.dir\n } else {\n const stat = moduleDetailsFromPath(filename)\n if (stat === undefined) {\n debug('could not parse filename: %s', filename)\n return exports // abort if filename could not be parsed\n }\n moduleName = stat.name\n basedir = stat.basedir\n\n // Ex: require('foo/lib/../bar.js')\n // moduleName = 'foo'\n // fullModuleName = 'foo/bar'\n const fullModuleName = resolveModuleName(stat)\n\n debug('resolved filename to module: %s (id: %s, resolved: %s, basedir: %s)', moduleName, id, fullModuleName, basedir)\n\n let matchFound = false\n if (hasWhitelist) {\n if (!id.startsWith('.') && modules.includes(id)) {\n // Not starting with '.' means `id` is identifying a module path,\n // as opposed to a local file path. (Note: I'm not sure about\n // absolute paths, but those are handled above.)\n // If this `id` is in `modules`, then this could be a match to an\n // package \"exports\" entry point that wouldn't otherwise match below.\n moduleName = id\n matchFound = true\n }\n\n // abort if module name isn't on whitelist\n if (!modules.includes(moduleName) && !modules.includes(fullModuleName)) {\n return exports\n }\n\n if (modules.includes(fullModuleName) && fullModuleName !== moduleName) {\n // if we get to this point, it means that we're requiring a whitelisted sub-module\n moduleName = fullModuleName\n matchFound = true\n }\n }\n\n if (!matchFound) {\n // figure out if this is the main module file, or a file inside the module\n let res\n try {\n res = resolve.sync(moduleName, { basedir })\n } catch (e) {\n debug('could not resolve module: %s', moduleName)\n self._cache.set(filename, exports, core)\n return exports // abort if module could not be resolved (e.g. no main in package.json and no index.js file)\n }\n\n if (res !== filename) {\n // this is a module-internal file\n if (internals === true) {\n // use the module-relative path to the file, prefixed by original module name\n moduleName = moduleName + path.sep + path.relative(basedir, filename)\n debug('preparing to process require of internal file: %s', moduleName)\n } else {\n debug('ignoring require of non-main module file: %s', res)\n self._cache.set(filename, exports, core)\n return exports // abort if not main module file\n }\n }\n }\n }\n\n // ensure that the cache entry is assigned a value before calling\n // onrequire, in case calling onrequire requires the same module.\n self._cache.set(filename, exports, core)\n debug('calling require hook: %s', moduleName)\n const patchedExports = onrequire(exports, moduleName, basedir)\n self._cache.set(filename, patchedExports, core)\n\n debug('returning module: %s', moduleName)\n return patchedExports\n }\n}\n\nHook.prototype.unhook = function () {\n this._unhooked = true\n\n if (this._require === Module.prototype.require) {\n Module.prototype.require = this._origRequire\n debug('require unhook successful')\n } else {\n debug('require unhook unsuccessful')\n }\n\n if (process.getBuiltinModule !== undefined) {\n if (this._getBuiltinModule === process.getBuiltinModule) {\n process.getBuiltinModule = this._origGetBuiltinModule\n debug('process.getBuiltinModule unhook successful')\n } else {\n debug('process.getBuiltinModule unhook unsuccessful')\n }\n }\n}\n\nfunction resolveModuleName (stat) {\n const normalizedPath = path.sep !== '/' ? stat.path.split(path.sep).join('/') : stat.path\n return path.posix.join(stat.name, normalizedPath).replace(normalize, '')\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 type { Hooked } from './RequireInTheMiddleSingleton';\n\nexport const ModuleNameSeparator = '/';\n\n/**\n * Node in a `ModuleNameTrie`\n */\nclass ModuleNameTrieNode {\n hooks: Array<{ hook: Hooked; insertedId: number }> = [];\n children: Map<string, ModuleNameTrieNode> = new Map();\n}\n\ntype ModuleNameTrieSearchOptions = {\n /**\n * Whether to return the results in insertion order\n */\n maintainInsertionOrder?: boolean;\n /**\n * Whether to return only full matches\n */\n fullOnly?: boolean;\n};\n\n/**\n * Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)\n */\nexport class ModuleNameTrie {\n private _trie: ModuleNameTrieNode = new ModuleNameTrieNode();\n private _counter: number = 0;\n\n /**\n * Insert a module hook into the trie\n *\n * @param {Hooked} hook Hook\n */\n insert(hook: Hooked) {\n let trieNode = this._trie;\n\n for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) {\n let nextNode = trieNode.children.get(moduleNamePart);\n if (!nextNode) {\n nextNode = new ModuleNameTrieNode();\n trieNode.children.set(moduleNamePart, nextNode);\n }\n trieNode = nextNode;\n }\n trieNode.hooks.push({ hook, insertedId: this._counter++ });\n }\n\n /**\n * Search for matching hooks in the trie\n *\n * @param {string} moduleName Module name\n * @param {boolean} maintainInsertionOrder Whether to return the results in insertion order\n * @param {boolean} fullOnly Whether to return only full matches\n * @returns {Hooked[]} Matching hooks\n */\n search(\n moduleName: string,\n { maintainInsertionOrder, fullOnly }: ModuleNameTrieSearchOptions = {}\n ): Hooked[] {\n let trieNode = this._trie;\n const results: ModuleNameTrieNode['hooks'] = [];\n let foundFull = true;\n\n for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) {\n const nextNode = trieNode.children.get(moduleNamePart);\n if (!nextNode) {\n foundFull = false;\n break;\n }\n if (!fullOnly) {\n results.push(...nextNode.hooks);\n }\n trieNode = nextNode;\n }\n\n if (fullOnly && foundFull) {\n results.push(...trieNode.hooks);\n }\n\n if (results.length === 0) {\n return [];\n }\n if (results.length === 1) {\n return [results[0].hook];\n }\n if (maintainInsertionOrder) {\n results.sort((a, b) => a.insertedId - b.insertedId);\n }\n return results.map(({ hook }) => hook);\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 type { OnRequireFn } from 'require-in-the-middle';\nimport { Hook } from 'require-in-the-middle';\nimport * as path from 'path';\nimport { ModuleNameTrie, ModuleNameSeparator } from './ModuleNameTrie';\n\nexport type Hooked = {\n moduleName: string;\n onRequire: OnRequireFn;\n};\n\n/**\n * Whether Mocha is running in this process\n * Inspired by https://github.com/AndreasPizsa/detect-mocha\n *\n * @type {boolean}\n */\nconst isMocha = [\n 'afterEach',\n 'after',\n 'beforeEach',\n 'before',\n 'describe',\n 'it',\n].every(fn => {\n // @ts-expect-error TS7053: Element implicitly has an 'any' type\n return typeof global[fn] === 'function';\n});\n\n/**\n * Singleton class for `require-in-the-middle`\n * Allows instrumentation plugins to patch modules with only a single `require` patch\n * WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,\n * we should minimize the number of new instances of this class.\n * Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process\n * will result in multiple instances of RITM, which will have an impact\n * on the performance of instrumentation hooks being applied.\n */\nexport class RequireInTheMiddleSingleton {\n private _moduleNameTrie: ModuleNameTrie = new ModuleNameTrie();\n private static _instance?: RequireInTheMiddleSingleton;\n\n private constructor() {\n this._initialize();\n }\n\n private _initialize() {\n new Hook(\n // Intercept all `require` calls; we will filter the matching ones below\n null,\n { internals: true },\n (exports, name, basedir) => {\n // For internal files on Windows, `name` will use backslash as the path separator\n const normalizedModuleName = normalizePathSeparators(name);\n\n const matches = this._moduleNameTrie.search(normalizedModuleName, {\n maintainInsertionOrder: true,\n // For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').\n // This matches the behavior of `require-in-the-middle`.\n // `basedir` is always `undefined` for core modules.\n fullOnly: basedir === undefined,\n });\n\n for (const { onRequire } of matches) {\n exports = onRequire(exports, name, basedir);\n }\n\n return exports;\n }\n );\n }\n\n /**\n * Register a hook with `require-in-the-middle`\n *\n * @param {string} moduleName Module name\n * @param {OnRequireFn} onRequire Hook function\n * @returns {Hooked} Registered hook\n */\n register(moduleName: string, onRequire: OnRequireFn): Hooked {\n const hooked = { moduleName, onRequire };\n this._moduleNameTrie.insert(hooked);\n return hooked;\n }\n\n /**\n * Get the `RequireInTheMiddleSingleton` singleton\n *\n * @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`\n */\n static getInstance(): RequireInTheMiddleSingleton {\n // Mocha runs all test suites in the same process\n // This prevents test suites from sharing a singleton\n if (isMocha) return new RequireInTheMiddleSingleton();\n\n return (this._instance =\n this._instance ?? new RequireInTheMiddleSingleton());\n }\n}\n\n/**\n * Normalize the path separators to forward slash in a module name or path\n *\n * @param {string} moduleNameOrPath Module name or path\n * @returns {string} Normalized module name or path\n */\nfunction normalizePathSeparators(moduleNameOrPath: string): string {\n return path.sep !== ModuleNameSeparator\n ? moduleNameOrPath.split(path.sep).join(ModuleNameSeparator)\n : moduleNameOrPath;\n}\n","// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2.0 License.\n//\n// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.\n\nconst importHooks = [] // TODO should this be a Set?\nconst setters = new WeakMap()\nconst specifiers = new Map()\nconst toHook = []\n\nconst proxyHandler = {\n set (target, name, value) {\n return setters.get(target)[name](value)\n },\n\n defineProperty (target, property, descriptor) {\n if ((!('value' in descriptor))) {\n throw new Error('Getters/setters are not supported for exports property descriptors.')\n }\n\n return setters.get(target)[property](descriptor.value)\n }\n}\n\nfunction register (name, namespace, set, specifier) {\n specifiers.set(name, specifier)\n setters.set(namespace, set)\n const proxy = new Proxy(namespace, proxyHandler)\n importHooks.forEach(hook => hook(name, proxy))\n toHook.push([name, proxy])\n}\n\nexports.register = register\nexports.importHooks = importHooks\nexports.specifiers = specifiers\nexports.toHook = toHook\n","// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2.0 License.\n//\n// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2021 Datadog, Inc.\n\nconst path = require('path')\nconst parse = require('module-details-from-path')\nconst { fileURLToPath } = require('url')\n\nconst {\n importHooks,\n specifiers,\n toHook\n} = require('./lib/register')\n\nfunction addHook (hook) {\n importHooks.push(hook)\n toHook.forEach(([name, namespace]) => hook(name, namespace))\n}\n\nfunction removeHook (hook) {\n const index = importHooks.indexOf(hook)\n if (index > -1) {\n importHooks.splice(index, 1)\n }\n}\n\nfunction callHookFn (hookFn, namespace, name, baseDir) {\n const newDefault = hookFn(namespace, name, baseDir)\n if (newDefault && newDefault !== namespace) {\n namespace.default = newDefault\n }\n}\n\nfunction Hook (modules, options, hookFn) {\n if ((this instanceof Hook) === false) return new Hook(modules, options, hookFn)\n if (typeof modules === 'function') {\n hookFn = modules\n modules = null\n options = null\n } else if (typeof options === 'function') {\n hookFn = options\n options = null\n }\n const internals = options ? options.internals === true : false\n\n this._iitmHook = (name, namespace) => {\n const filename = name\n const isBuiltin = name.startsWith('node:')\n let baseDir\n\n if (isBuiltin) {\n name = name.replace(/^node:/, '')\n } else {\n if (name.startsWith('file://')) {\n try {\n name = fileURLToPath(name)\n } catch (e) {}\n }\n const details = parse(name)\n if (details) {\n name = details.name\n baseDir = details.basedir\n }\n }\n\n if (modules) {\n for (const moduleName of modules) {\n if (moduleName === name) {\n if (baseDir) {\n if (internals) {\n name = name + path.sep + path.relative(baseDir, fileURLToPath(filename))\n } else {\n if (!baseDir.endsWith(specifiers.get(filename))) continue\n }\n }\n callHookFn(hookFn, namespace, name, baseDir)\n }\n }\n } else {\n callHookFn(hookFn, namespace, name, baseDir)\n }\n }\n\n addHook(this._iitmHook)\n}\n\nHook.prototype.unhook = function () {\n removeHook(this._iitmHook)\n}\n\nmodule.exports = Hook\nmodule.exports.Hook = Hook\nmodule.exports.addHook = addHook\nmodule.exports.removeHook = removeHook\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 './types';\n\n/**\n * function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport function safeExecuteInTheMiddle<T>(\n execute: () => T,\n onFinish: (e: Error | undefined, result: T | undefined) => void,\n preventThrowingError?: boolean\n): T {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = execute();\n } catch (e) {\n error = e;\n } finally {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\n}\n\n/**\n * Async function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport async function safeExecuteInTheMiddleAsync<T>(\n execute: () => T,\n onFinish: (e: Error | undefined, result: T | undefined) => void,\n preventThrowingError?: boolean\n): Promise<T> {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = await execute();\n } catch (e) {\n error = e;\n } finally {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\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\nimport * as types from '../../types';\nimport * as path from 'path';\nimport { types as utilTypes } from 'util';\nimport { satisfies } from 'semver';\nimport { wrap, unwrap, massWrap, massUnwrap } from 'shimmer';\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport {\n RequireInTheMiddleSingleton,\n Hooked,\n} from './RequireInTheMiddleSingleton';\nimport type { HookFn } from 'import-in-the-middle';\nimport { Hook as HookImport } from 'import-in-the-middle';\nimport {\n InstrumentationConfig,\n InstrumentationModuleDefinition,\n} from '../../types';\nimport { diag } from '@opentelemetry/api';\nimport type { OnRequireFn } from 'require-in-the-middle';\nimport { Hook as HookRequire } from 'require-in-the-middle';\nimport { readFileSync } from 'fs';\nimport { isWrapped } from '../../utils';\n\n/**\n * Base abstract class for instrumenting node plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n private _modules: InstrumentationModuleDefinition[];\n private _hooks: (Hooked | HookRequire)[] = [];\n private _requireInTheMiddleSingleton: RequireInTheMiddleSingleton =\n RequireInTheMiddleSingleton.getInstance();\n private _enabled = false;\n\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n let modules = this.init();\n\n if (modules && !Array.isArray(modules)) {\n modules = [modules];\n }\n\n this._modules = (modules as InstrumentationModuleDefinition[]) || [];\n\n if (this._modules.length === 0) {\n diag.debug(\n 'No modules instrumentation has been defined for ' +\n `'${this.instrumentationName}@${this.instrumentationVersion}'` +\n ', nothing will be patched'\n );\n }\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n\n protected override _wrap: typeof wrap = (moduleExports, name, wrapper) => {\n if (isWrapped(moduleExports[name])) {\n this._unwrap(moduleExports, name);\n }\n if (!utilTypes.isProxy(moduleExports)) {\n return wrap(moduleExports, name, wrapper);\n } else {\n const wrapped = wrap(Object.assign({}, moduleExports), name, wrapper);\n\n return Object.defineProperty(moduleExports, name, {\n value: wrapped,\n });\n }\n };\n\n protected override _unwrap: typeof unwrap = (moduleExports, name) => {\n if (!utilTypes.isProxy(moduleExports)) {\n return unwrap(moduleExports, name);\n } else {\n return Object.defineProperty(moduleExports, name, {\n value: moduleExports[name],\n });\n }\n };\n\n protected override _massWrap: typeof massWrap = (\n moduleExportsArray,\n names,\n wrapper\n ) => {\n if (!moduleExportsArray) {\n diag.error('must provide one or more modules to patch');\n return;\n } else if (!Array.isArray(moduleExportsArray)) {\n moduleExportsArray = [moduleExportsArray];\n }\n\n if (!(names && Array.isArray(names))) {\n diag.error('must provide one or more functions to wrap on modules');\n return;\n }\n\n moduleExportsArray.forEach(moduleExports => {\n names.forEach(name => {\n this._wrap(moduleExports, name, wrapper);\n });\n });\n };\n\n protected override _massUnwrap: typeof massUnwrap = (\n moduleExportsArray,\n names\n ) => {\n if (!moduleExportsArray) {\n diag.error('must provide one or more modules to patch');\n return;\n } else if (!Array.isArray(moduleExportsArray)) {\n moduleExportsArray = [moduleExportsArray];\n }\n\n if (!(names && Array.isArray(names))) {\n diag.error('must provide one or more functions to wrap on modules');\n return;\n }\n\n moduleExportsArray.forEach(moduleExports => {\n names.forEach(name => {\n this._unwrap(moduleExports, name);\n });\n });\n };\n\n private _warnOnPreloadedModules(): void {\n this._modules.forEach((module: InstrumentationModuleDefinition) => {\n const { name } = module;\n try {\n const resolvedModule = require.resolve(name);\n if (require.cache[resolvedModule]) {\n // Module is already cached, which means the instrumentation hook might not work\n this._diag.warn(\n `Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`\n );\n }\n } catch {\n // Module isn't available, we can simply skip\n }\n });\n }\n\n private _extractPackageVersion(baseDir: string): string | undefined {\n try {\n const json = readFileSync(path.join(baseDir, 'package.json'), {\n encoding: 'utf8',\n });\n const version = JSON.parse(json).version;\n return typeof version === 'string' ? version : undefined;\n } catch (error) {\n diag.warn('Failed extracting version', baseDir);\n }\n\n return undefined;\n }\n\n private _onRequire<T>(\n module: InstrumentationModuleDefinition,\n exports: T,\n name: string,\n baseDir?: string | void\n ): T {\n if (!baseDir) {\n if (typeof module.patch === 'function') {\n module.moduleExports = exports;\n if (this._enabled) {\n this._diag.debug(\n 'Applying instrumentation patch for nodejs core module on require hook',\n {\n module: module.name,\n }\n );\n return module.patch(exports);\n }\n }\n return exports;\n }\n\n const version = this._extractPackageVersion(baseDir);\n module.moduleVersion = version;\n if (module.name === name) {\n // main module\n if (\n isSupported(module.supportedVersions, version, module.includePrerelease)\n ) {\n if (typeof module.patch === 'function') {\n module.moduleExports = exports;\n if (this._enabled) {\n this._diag.debug(\n 'Applying instrumentation patch for module on require hook',\n {\n module: module.name,\n version: module.moduleVersion,\n baseDir,\n }\n );\n return module.patch(exports, module.moduleVersion);\n }\n }\n }\n return exports;\n }\n // internal file\n const files = module.files ?? [];\n const normalizedName = path.normalize(name);\n const supportedFileInstrumentations = files\n .filter(f => f.name === normalizedName)\n .filter(f =>\n isSupported(f.supportedVersions, version, module.includePrerelease)\n );\n return supportedFileInstrumentations.reduce<T>((patchedExports, file) => {\n file.moduleExports = patchedExports;\n if (this._enabled) {\n this._diag.debug(\n 'Applying instrumentation patch for nodejs module file on require hook',\n {\n module: module.name,\n version: module.moduleVersion,\n fileName: file.name,\n baseDir,\n }\n );\n\n // patch signature is not typed, so we cast it assuming it's correct\n return file.patch(patchedExports, module.moduleVersion) as T;\n }\n return patchedExports;\n }, exports);\n }\n\n public enable(): void {\n if (this._enabled) {\n return;\n }\n this._enabled = true;\n\n // already hooked, just call patch again\n if (this._hooks.length > 0) {\n for (const module of this._modules) {\n if (typeof module.patch === 'function' && module.moduleExports) {\n this._diag.debug(\n 'Applying instrumentation patch for nodejs module on instrumentation enabled',\n {\n module: module.name,\n version: module.moduleVersion,\n }\n );\n module.patch(module.moduleExports, module.moduleVersion);\n }\n for (const file of module.files) {\n if (file.moduleExports) {\n this._diag.debug(\n 'Applying instrumentation patch for nodejs module file on instrumentation enabled',\n {\n module: module.name,\n version: module.moduleVersion,\n fileName: file.name,\n }\n );\n file.patch(file.moduleExports, module.moduleVersion);\n }\n }\n }\n return;\n }\n\n this._warnOnPreloadedModules();\n for (const module of this._modules) {\n const hookFn: HookFn = (exports, name, baseDir) => {\n return this._onRequire<typeof exports>(module, exports, name, baseDir);\n };\n const onRequire: OnRequireFn = (exports, name, baseDir) => {\n return this._onRequire<typeof exports>(module, exports, name, baseDir);\n };\n\n // `RequireInTheMiddleSingleton` does not support absolute paths.\n // For an absolute paths, we must create a separate instance of the\n // require-in-the-middle `Hook`.\n const hook = path.isAbsolute(module.name)\n ? new HookRequire([module.name], { internals: true }, onRequire)\n : this._requireInTheMiddleSingleton.register(module.name, onRequire);\n\n this._hooks.push(hook);\n const esmHook = new HookImport(\n [module.name],\n { internals: false },\n <HookFn>hookFn\n );\n this._hooks.push(esmHook);\n }\n }\n\n public disable(): void {\n if (!this._enabled) {\n return;\n }\n this._enabled = false;\n\n for (const module of this._modules) {\n if (typeof module.unpatch === 'function' && module.moduleExports) {\n this._diag.debug(\n 'Removing instrumentation patch for nodejs module on instrumentation disabled',\n {\n module: module.name,\n version: module.moduleVersion,\n }\n );\n module.unpatch(module.moduleExports, module.moduleVersion);\n }\n for (const file of module.files) {\n if (file.moduleExports) {\n this._diag.debug(\n 'Removing instrumentation patch for nodejs module file on instrumentation disabled',\n {\n module: module.name,\n version: module.moduleVersion,\n fileName: file.name,\n }\n );\n file.unpatch(file.moduleExports, module.moduleVersion);\n }\n }\n }\n }\n\n public isEnabled(): boolean {\n return this._enabled;\n }\n}\n\nfunction isSupported(\n supportedVersions: string[],\n version?: string,\n includePrerelease?: boolean\n): boolean {\n if (typeof version === 'undefined') {\n // If we don't have the version, accept the wildcard case only\n return supportedVersions.includes('*');\n }\n\n return supportedVersions.some(supportedVersion => {\n return satisfies(version, supportedVersion, { includePrerelease });\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 { normalize } from 'path';\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 { InstrumentationBase } from './instrumentation';\nexport { normalize } from './normalize';\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 { InstrumentationBase, normalize } 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 {\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n} from './types';\n\nexport class InstrumentationNodeModuleDefinition\n implements InstrumentationModuleDefinition\n{\n files: InstrumentationModuleFile[];\n constructor(\n public name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch?: (exports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch?: (exports: any, moduleVersion?: string) => void,\n files?: InstrumentationModuleFile[]\n ) {\n this.files = files || [];\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 { InstrumentationModuleFile } from './types';\nimport { normalize } from './platform/index';\n\nexport class InstrumentationNodeModuleFile\n implements InstrumentationModuleFile\n{\n public name: string;\n constructor(\n name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch: (moduleExports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch: (moduleExports?: any, moduleVersion?: string) => void\n ) {\n this.name = normalize(name);\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 { TracerProvider, MeterProvider, Span } from '@opentelemetry/api';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/** Interface Instrumentation to apply patch. */\nexport interface Instrumentation<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n> {\n /** Instrumentation Name */\n instrumentationName: string;\n\n /** Instrumentation Version */\n instrumentationVersion: string;\n\n /**\n * Instrumentation Description - please describe all useful information\n * as Instrumentation might patch different version of different modules,\n * or support different browsers etc.\n */\n instrumentationDescription?: string;\n\n /** Method to disable the instrumentation */\n disable(): void;\n\n /** Method to enable the instrumentation */\n enable(): void;\n\n /** Method to set tracer provider */\n setTracerProvider(tracerProvider: TracerProvider): void;\n\n /** Method to set meter provider */\n setMeterProvider(meterProvider: MeterProvider): void;\n\n /** Method to set logger provider */\n setLoggerProvider?(loggerProvider: LoggerProvider): void;\n\n /** Method to set instrumentation config */\n setConfig(config: ConfigType): void;\n\n /** Method to get instrumentation config */\n getConfig(): ConfigType;\n}\n\n/**\n * Base interface for configuration options common to all instrumentations.\n * This interface can be extended by individual instrumentations to include\n * additional configuration options specific to that instrumentation.\n * All configuration options must be optional.\n */\nexport interface InstrumentationConfig {\n /**\n * Whether to enable the plugin.\n * @default true\n */\n enabled?: boolean;\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\nexport interface InstrumentationModuleFile {\n /** Name of file to be patched with relative path */\n name: string;\n\n moduleExports?: unknown;\n\n /** Supported versions for the file.\n *\n * A module version is supported if one of the supportedVersions in the array satisfies the module version.\n * The syntax of the version is checked with the `satisfies` function of \"The semantic versioner for npm\", see\n * [`semver` package](https://www.npmjs.com/package/semver)\n * If the version is not supported, we won't apply instrumentation patch.\n * If omitted, all versions of the module will be patched.\n *\n * It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.\n * New major versions should be reviewed and tested before being added to the supportedVersions array.\n *\n * Example: ['>=1.2.3 <3']\n */\n supportedVersions: string[];\n\n /** Method to patch the instrumentation */\n patch(moduleExports: unknown, moduleVersion?: string): unknown;\n\n /** Method to unpatch the instrumentation */\n unpatch(moduleExports?: unknown, moduleVersion?: string): void;\n}\n\nexport interface InstrumentationModuleDefinition {\n /** Module name or path */\n name: string;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n moduleExports?: any;\n\n /** Instrumented module version */\n moduleVersion?: string;\n\n /** Supported version of module.\n *\n * A module version is supported if one of the supportedVersions in the array satisfies the module version.\n * The syntax of the version is checked with the `satisfies` function of \"The semantic versioner for npm\", see\n * [`semver` package](https://www.npmjs.com/package/semver)\n * If the version is not supported, we won't apply instrumentation patch (see `enable` method).\n * If omitted, all versions of the module will be patched.\n *\n * It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.\n * New major versions should be reviewed and tested before being added to the supportedVersions array.\n *\n * Example: ['>=1.2.3 <3']\n */\n supportedVersions: string[];\n\n /** Module internal files to be patched */\n files: InstrumentationModuleFile[];\n\n /** If set to true, the includePrerelease check will be included when calling semver.satisfies */\n includePrerelease?: boolean;\n\n /** Method to patch the instrumentation */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n patch?: (moduleExports: any, moduleVersion?: string) => any;\n\n /** Method to unpatch the instrumentation */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n unpatch?: (moduleExports: any, moduleVersion?: string) => void;\n}\n\n/**\n * SpanCustomizationHook is a common way for instrumentations to expose extension points\n * where users can add custom behavior to a span based on info object passed to the hook at different times of the span lifecycle.\n * This is an advanced feature, commonly used to add additional or non-spec-compliant attributes to the span,\n * capture payloads, modify the span in some way, or carry some other side effect.\n *\n * The hook is registered with the instrumentation specific config by implementing an handler function with this signature,\n * and if the hook is present, it will be called with the span and the event information\n * when the event is emitted.\n *\n * When and under what conditions the hook is called and what data is passed\n * in the info argument, is specific to each instrumentation and life-cycle event\n * and should be documented where it is used.\n *\n * Instrumentation may define multiple hooks, for different spans, or different span life-cycle events.\n */\nexport type SpanCustomizationHook<SpanCustomizationInfoType> = (\n span: Span,\n info: SpanCustomizationInfoType\n) => 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\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\nexport interface AutoLoaderResult {\n instrumentations: Instrumentation[];\n}\n\nexport interface AutoLoaderOptions {\n instrumentations?: (Instrumentation | Instrumentation[])[];\n tracerProvider?: TracerProvider;\n meterProvider?: MeterProvider;\n loggerProvider?: LoggerProvider;\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 { registerInstrumentations } from './autoLoader';\nexport { InstrumentationBase } from './platform/index';\nexport { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';\nexport { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';\nexport * from './types';\nexport * from './types_internal';\nexport * from './utils';\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 context,\n HrTime,\n INVALID_SPAN_CONTEXT,\n propagation,\n ROOT_CONTEXT,\n Span,\n SpanKind,\n SpanOptions,\n SpanStatus,\n SpanStatusCode,\n trace,\n Histogram,\n MetricAttributes,\n ValueType,\n} from '@opentelemetry/api';\nimport {\n hrTime,\n hrTimeDuration,\n hrTimeToMilliseconds,\n suppressTracing,\n} from '@opentelemetry/core';\nimport type * as http from 'http';\nimport type * as https from 'https';\nimport { Socket } from 'net';\nimport * as semver from 'semver';\nimport * as url from 'url';\nimport {\n Err,\n Func,\n Http,\n HttpInstrumentationConfig,\n HttpRequestArgs,\n Https,\n} from './types';\nimport * as utils from './utils';\nimport { VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { RPCMetadata, RPCType, setRPCMetadata } from '@opentelemetry/core';\nimport { errorMonitor } from 'events';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\n\n/**\n * Http instrumentation instrumentation for Opentelemetry\n */\nexport class HttpInstrumentation extends InstrumentationBase<HttpInstrumentationConfig> {\n /** keep track on spans not ended */\n private readonly _spanNotEnded: WeakSet<Span> = new WeakSet<Span>();\n private _headerCapture;\n private _httpServerDurationHistogram!: Histogram;\n private _httpClientDurationHistogram!: Histogram;\n\n constructor(config: HttpInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-http', VERSION, config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n protected override _updateMetricInstruments() {\n this._httpServerDurationHistogram = this.meter.createHistogram(\n 'http.server.duration',\n {\n description: 'Measures the duration of inbound HTTP requests.',\n unit: 'ms',\n valueType: ValueType.DOUBLE,\n }\n );\n this._httpClientDurationHistogram = this.meter.createHistogram(\n 'http.client.duration',\n {\n description: 'Measures the duration of outbound HTTP requests.',\n unit: 'ms',\n valueType: ValueType.DOUBLE,\n }\n );\n }\n\n override setConfig(config: HttpInstrumentationConfig = {}): void {\n super.setConfig(config);\n this._headerCapture = this._createHeaderCapture();\n }\n\n init(): [\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleDefinition,\n ] {\n return [this._getHttpsInstrumentation(), this._getHttpInstrumentation()];\n }\n\n private _getHttpInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'http',\n ['*'],\n (moduleExports: Http): Http => {\n this._wrap(\n moduleExports,\n 'request',\n this._getPatchOutgoingRequestFunction('http')\n );\n this._wrap(\n moduleExports,\n 'get',\n this._getPatchOutgoingGetFunction(moduleExports.request)\n );\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('http')\n );\n return moduleExports;\n },\n (moduleExports: Http) => {\n if (moduleExports === undefined) return;\n\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n );\n }\n\n private _getHttpsInstrumentation() {\n return new InstrumentationNodeModuleDefinition(\n 'https',\n ['*'],\n (moduleExports: Https): Https => {\n this._wrap(\n moduleExports,\n 'request',\n this._getPatchHttpsOutgoingRequestFunction('https')\n );\n this._wrap(\n moduleExports,\n 'get',\n this._getPatchHttpsOutgoingGetFunction(moduleExports.request)\n );\n this._wrap(\n moduleExports.Server.prototype,\n 'emit',\n this._getPatchIncomingRequestFunction('https')\n );\n return moduleExports;\n },\n (moduleExports: Https) => {\n if (moduleExports === undefined) return;\n\n this._unwrap(moduleExports, 'request');\n this._unwrap(moduleExports, 'get');\n this._unwrap(moduleExports.Server.prototype, 'emit');\n }\n );\n }\n\n /**\n * Creates spans for incoming requests, restoring spans' context if applied.\n */\n protected _getPatchIncomingRequestFunction(component: 'http' | 'https') {\n return (\n original: (event: string, ...args: unknown[]) => boolean\n ): ((this: unknown, event: string, ...args: unknown[]) => boolean) => {\n return this._incomingRequestFunction(component, original);\n };\n }\n\n /**\n * Creates spans for outgoing requests, sending spans' context for distributed\n * tracing.\n */\n protected _getPatchOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n return this._outgoingRequestFunction(component, original);\n };\n }\n\n protected _getPatchOutgoingGetFunction(\n clientRequest: (\n options: http.RequestOptions | string | url.URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (_original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n // Re-implement http.get. This needs to be done (instead of using\n // getPatchOutgoingRequestFunction to patch it) because we need to\n // set the trace context header before the returned http.ClientRequest is\n // ended. The Node.js docs state that the only differences between\n // request and get are that (1) get defaults to the HTTP GET method and\n // (2) the returned request object is ended immediately. The former is\n // already true (at least in supported Node versions up to v10), so we\n // simply follow the latter. Ref:\n // https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback\n // https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/instrumentations/instrumentation-http.ts#L198\n return function outgoingGetRequest<\n T extends http.RequestOptions | string | url.URL,\n >(options: T, ...args: HttpRequestArgs): http.ClientRequest {\n const req = clientRequest(options, ...args);\n req.end();\n return req;\n };\n };\n }\n\n /** Patches HTTPS outgoing requests */\n private _getPatchHttpsOutgoingRequestFunction(component: 'http' | 'https') {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n // Makes sure options will have default HTTPS parameters\n if (\n component === 'https' &&\n typeof options === 'object' &&\n options?.constructor?.name !== 'URL'\n ) {\n options = Object.assign({}, options);\n instrumentation._setDefaultOptions(options);\n }\n return instrumentation._getPatchOutgoingRequestFunction(component)(\n original\n )(options, ...args);\n };\n };\n }\n\n private _setDefaultOptions(options: https.RequestOptions) {\n options.protocol = options.protocol || 'https:';\n options.port = options.port || 443;\n }\n\n /** Patches HTTPS outgoing get requests */\n private _getPatchHttpsOutgoingGetFunction(\n clientRequest: (\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n options: http.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ) => http.ClientRequest\n ) {\n return (original: Func<http.ClientRequest>): Func<http.ClientRequest> => {\n const instrumentation = this;\n return function httpsOutgoingRequest(\n // eslint-disable-next-line node/no-unsupported-features/node-builtins\n options: https.RequestOptions | string | URL,\n ...args: HttpRequestArgs\n ): http.ClientRequest {\n return instrumentation._getPatchOutgoingGetFunction(clientRequest)(\n original\n )(options, ...args);\n };\n };\n }\n\n /**\n * Attach event listeners to a client request to end span and add span attributes.\n *\n * @param request The original request object.\n * @param span representing the current operation\n * @param startTime representing the start time of the request to calculate duration in Metric\n * @param metricAttributes metric attributes\n */\n private _traceClientRequest(\n request: http.ClientRequest,\n span: Span,\n startTime: HrTime,\n metricAttributes: MetricAttributes\n ): http.ClientRequest {\n if (this.getConfig().requestHook) {\n this._callRequestHook(span, request);\n }\n\n /**\n * Determines if the request has errored or the response has ended/errored.\n */\n let responseFinished = false;\n\n /*\n * User 'response' event listeners can be added before our listener,\n * force our listener to be the first, so response emitter is bound\n * before any user listeners are added to it.\n */\n request.prependListener(\n 'response',\n (response: http.IncomingMessage & { aborted?: boolean }) => {\n this._diag.debug('outgoingRequest on response()');\n if (request.listenerCount('response') <= 1) {\n response.resume();\n }\n const responseAttributes =\n utils.getOutgoingRequestAttributesOnResponse(response);\n span.setAttributes(responseAttributes);\n metricAttributes = Object.assign(\n metricAttributes,\n utils.getOutgoingRequestMetricAttributesOnResponse(responseAttributes)\n );\n\n if (this.getConfig().responseHook) {\n this._callResponseHook(span, response);\n }\n\n this._headerCapture.client.captureRequestHeaders(span, header =>\n request.getHeader(header)\n );\n this._headerCapture.client.captureResponseHeaders(\n span,\n header => response.headers[header]\n );\n\n context.bind(context.active(), response);\n\n const endHandler = () => {\n this._diag.debug('outgoingRequest on end()');\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n let status: SpanStatus;\n\n if (response.aborted && !response.complete) {\n status = { code: SpanStatusCode.ERROR };\n } else {\n status = {\n code: utils.parseResponseStatus(\n SpanKind.CLIENT,\n response.statusCode\n ),\n };\n }\n\n span.setStatus(status);\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n };\n\n response.on('end', endHandler);\n // See https://github.com/open-telemetry/opentelemetry-js/pull/3625#issuecomment-1475673533\n if (semver.lt(process.version, '16.0.0')) {\n response.on('close', endHandler);\n }\n response.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n utils.setSpanWithError(span, error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n this._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n });\n }\n );\n request.on('close', () => {\n this._diag.debug('outgoingRequest on request close()');\n if (request.aborted || responseFinished) {\n return;\n }\n responseFinished = true;\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n });\n request.on(errorMonitor, (error: Err) => {\n this._diag.debug('outgoingRequest on request error()', error);\n if (responseFinished) {\n return;\n }\n responseFinished = true;\n utils.setSpanWithError(span, error);\n this._closeHttpSpan(span, SpanKind.CLIENT, startTime, metricAttributes);\n });\n\n this._diag.debug('http.ClientRequest return request');\n return request;\n }\n\n private _incomingRequestFunction(\n component: 'http' | 'https',\n original: (event: string, ...args: unknown[]) => boolean\n ) {\n const instrumentation = this;\n return function incomingRequest(\n this: unknown,\n event: string,\n ...args: unknown[]\n ): boolean {\n // Only traces request events\n if (event !== 'request') {\n return original.apply(this, [event, ...args]);\n }\n\n const request = args[0] as http.IncomingMessage;\n const response = args[1] as http.ServerResponse & { socket: Socket };\n const pathname = request.url\n ? url.parse(request.url).pathname || '/'\n : '/';\n const method = request.method || 'GET';\n\n instrumentation._diag.debug(\n `${component} instrumentation incomingRequest`\n );\n\n if (\n utils.isIgnored(\n pathname,\n instrumentation.getConfig().ignoreIncomingPaths,\n (e: unknown) =>\n instrumentation._diag.error('caught ignoreIncomingPaths error: ', e)\n ) ||\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().ignoreIncomingRequestHook?.(request),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreIncomingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return context.with(suppressTracing(context.active()), () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n return original.apply(this, [event, ...args]);\n });\n }\n\n const headers = request.headers;\n\n const spanAttributes = utils.getIncomingRequestAttributes(request, {\n component: component,\n serverName: instrumentation.getConfig().serverName,\n hookAttributes: instrumentation._callStartSpanHook(\n request,\n instrumentation.getConfig().startIncomingSpanHook\n ),\n });\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.SERVER,\n attributes: spanAttributes,\n };\n\n const startTime = hrTime();\n const metricAttributes =\n utils.getIncomingRequestMetricAttributes(spanAttributes);\n\n const ctx = propagation.extract(ROOT_CONTEXT, headers);\n const span = instrumentation._startHttpSpan(method, spanOptions, ctx);\n const rpcMetadata: RPCMetadata = {\n type: RPCType.HTTP,\n span,\n };\n\n return context.with(\n setRPCMetadata(trace.setSpan(ctx, span), rpcMetadata),\n () => {\n context.bind(context.active(), request);\n context.bind(context.active(), response);\n\n if (instrumentation.getConfig().requestHook) {\n instrumentation._callRequestHook(span, request);\n }\n if (instrumentation.getConfig().responseHook) {\n instrumentation._callResponseHook(span, response);\n }\n\n instrumentation._headerCapture.server.captureRequestHeaders(\n span,\n header => request.headers[header]\n );\n\n // After 'error', no further events other than 'close' should be emitted.\n let hasError = false;\n response.on('close', () => {\n if (hasError) {\n return;\n }\n instrumentation._onServerResponseFinish(\n request,\n response,\n span,\n metricAttributes,\n startTime\n );\n });\n response.on(errorMonitor, (err: Err) => {\n hasError = true;\n instrumentation._onServerResponseError(\n span,\n metricAttributes,\n startTime,\n err\n );\n });\n\n return safeExecuteInTheMiddle(\n () => original.apply(this, [event, ...args]),\n error => {\n if (error) {\n utils.setSpanWithError(span, error);\n instrumentation._closeHttpSpan(\n span,\n SpanKind.SERVER,\n startTime,\n metricAttributes\n );\n throw error;\n }\n }\n );\n }\n );\n };\n }\n\n private _outgoingRequestFunction(\n component: 'http' | 'https',\n original: Func<http.ClientRequest>\n ): Func<http.ClientRequest> {\n const instrumentation = this;\n return function outgoingRequest(\n this: unknown,\n options: url.URL | http.RequestOptions | string,\n ...args: unknown[]\n ): http.ClientRequest {\n if (!utils.isValidOptionsType(options)) {\n return original.apply(this, [options, ...args]);\n }\n const extraOptions =\n typeof args[0] === 'object' &&\n (typeof options === 'string' || options instanceof url.URL)\n ? (args.shift() as http.RequestOptions)\n : undefined;\n const { origin, pathname, method, optionsParsed } = utils.getRequestInfo(\n options,\n extraOptions\n );\n /**\n * Node 8's https module directly call the http one so to avoid creating\n * 2 span for the same request we need to check that the protocol is correct\n * See: https://github.com/nodejs/node/blob/v8.17.0/lib/https.js#L245\n */\n if (\n component === 'http' &&\n semver.lt(process.version, '9.0.0') &&\n optionsParsed.protocol === 'https:'\n ) {\n return original.apply(this, [optionsParsed, ...args]);\n }\n\n if (\n utils.isIgnored(\n origin + pathname,\n instrumentation.getConfig().ignoreOutgoingUrls,\n (e: unknown) =>\n instrumentation._diag.error('caught ignoreOutgoingUrls error: ', e)\n ) ||\n safeExecuteInTheMiddle(\n () =>\n instrumentation\n .getConfig()\n .ignoreOutgoingRequestHook?.(optionsParsed),\n (e: unknown) => {\n if (e != null) {\n instrumentation._diag.error(\n 'caught ignoreOutgoingRequestHook error: ',\n e\n );\n }\n },\n true\n )\n ) {\n return original.apply(this, [optionsParsed, ...args]);\n }\n\n const { hostname, port } = utils.extractHostnameAndPort(optionsParsed);\n\n const attributes = utils.getOutgoingRequestAttributes(optionsParsed, {\n component,\n port,\n hostname,\n hookAttributes: instrumentation._callStartSpanHook(\n optionsParsed,\n instrumentation.getConfig().startOutgoingSpanHook\n ),\n });\n\n const startTime = hrTime();\n const metricAttributes: MetricAttributes =\n utils.getOutgoingRequestMetricAttributes(attributes);\n\n const spanOptions: SpanOptions = {\n kind: SpanKind.CLIENT,\n attributes,\n };\n const span = instrumentation._startHttpSpan(method, spanOptions);\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n if (!optionsParsed.headers) {\n optionsParsed.headers = {};\n } else {\n // Make a copy of the headers object to avoid mutating an object the\n // caller might have a reference to.\n optionsParsed.headers = Object.assign({}, optionsParsed.headers);\n }\n propagation.inject(requestContext, optionsParsed.headers);\n\n return context.with(requestContext, () => {\n /*\n * The response callback is registered before ClientRequest is bound,\n * thus it is needed to bind it before the function call.\n */\n const cb = args[args.length - 1];\n if (typeof cb === 'function') {\n args[args.length - 1] = context.bind(parentContext, cb);\n }\n\n const request: http.ClientRequest = safeExecuteInTheMiddle(\n () => original.apply(this, [optionsParsed, ...args]),\n error => {\n if (error) {\n utils.setSpanWithError(span, error);\n instrumentation._closeHttpSpan(\n span,\n SpanKind.CLIENT,\n startTime,\n metricAttributes\n );\n throw error;\n }\n }\n );\n\n instrumentation._diag.debug(\n `${component} instrumentation outgoingRequest`\n );\n context.bind(parentContext, request);\n return instrumentation._traceClientRequest(\n request,\n span,\n startTime,\n metricAttributes\n );\n });\n };\n }\n\n private _onServerResponseFinish(\n request: http.IncomingMessage,\n response: http.ServerResponse,\n span: Span,\n metricAttributes: MetricAttributes,\n startTime: HrTime\n ) {\n const attributes = utils.getIncomingRequestAttributesOnResponse(\n request,\n response\n );\n metricAttributes = Object.assign(\n metricAttributes,\n utils.getIncomingRequestMetricAttributesOnResponse(attributes)\n );\n\n this._headerCapture.server.captureResponseHeaders(span, header =>\n response.getHeader(header)\n );\n\n span.setAttributes(attributes).setStatus({\n code: utils.parseResponseStatus(SpanKind.SERVER, response.statusCode),\n });\n\n const route = attributes[SEMATTRS_HTTP_ROUTE];\n if (route) {\n span.updateName(`${request.method || 'GET'} ${route}`);\n }\n\n if (this.getConfig().applyCustomAttributesOnSpan) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().applyCustomAttributesOnSpan!(\n span,\n request,\n response\n ),\n () => {},\n true\n );\n }\n\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _onServerResponseError(\n span: Span,\n metricAttributes: MetricAttributes,\n startTime: HrTime,\n error: Err\n ) {\n utils.setSpanWithError(span, error);\n this._closeHttpSpan(span, SpanKind.SERVER, startTime, metricAttributes);\n }\n\n private _startHttpSpan(\n name: string,\n options: SpanOptions,\n ctx = context.active()\n ) {\n /*\n * If a parent is required but not present, we use a `NoopSpan` to still\n * propagate context without recording it.\n */\n const requireParent =\n options.kind === SpanKind.CLIENT\n ? this.getConfig().requireParentforOutgoingSpans\n : this.getConfig().requireParentforIncomingSpans;\n\n let span: Span;\n const currentSpan = trace.getSpan(ctx);\n\n if (requireParent === true && currentSpan === undefined) {\n span = trace.wrapSpanContext(INVALID_SPAN_CONTEXT);\n } else if (requireParent === true && currentSpan?.spanContext().isRemote) {\n span = currentSpan;\n } else {\n span = this.tracer.startSpan(name, options, ctx);\n }\n this._spanNotEnded.add(span);\n return span;\n }\n\n private _closeHttpSpan(\n span: Span,\n spanKind: SpanKind,\n startTime: HrTime,\n metricAttributes: MetricAttributes\n ) {\n if (!this._spanNotEnded.has(span)) {\n return;\n }\n\n span.end();\n this._spanNotEnded.delete(span);\n\n // Record metrics\n const duration = hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime()));\n if (spanKind === SpanKind.SERVER) {\n this._httpServerDurationHistogram.record(duration, metricAttributes);\n } else if (spanKind === SpanKind.CLIENT) {\n this._httpClientDurationHistogram.record(duration, metricAttributes);\n }\n }\n\n private _callResponseHook(\n span: Span,\n response: http.IncomingMessage | http.ServerResponse\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().responseHook!(span, response),\n () => {},\n true\n );\n }\n\n private _callRequestHook(\n span: Span,\n request: http.ClientRequest | http.IncomingMessage\n ) {\n safeExecuteInTheMiddle(\n () => this.getConfig().requestHook!(span, request),\n () => {},\n true\n );\n }\n\n private _callStartSpanHook(\n request: http.IncomingMessage | http.RequestOptions,\n hookFunc: Function | undefined\n ) {\n if (typeof hookFunc === 'function') {\n return safeExecuteInTheMiddle(\n () => hookFunc(request),\n () => {},\n true\n );\n }\n }\n\n private _createHeaderCapture() {\n const config = this.getConfig();\n\n return {\n client: {\n captureRequestHeaders: utils.headerCapture(\n 'request',\n config.headersToSpanAttributes?.client?.requestHeaders ?? []\n ),\n captureResponseHeaders: utils.headerCapture(\n 'response',\n config.headersToSpanAttributes?.client?.responseHeaders ?? []\n ),\n },\n server: {\n captureRequestHeaders: utils.headerCapture(\n 'request',\n config.headersToSpanAttributes?.server?.requestHeaders ?? []\n ),\n captureResponseHeaders: utils.headerCapture(\n 'response',\n config.headersToSpanAttributes?.server?.responseHeaders ?? []\n ),\n },\n };\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","/*\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 './http';\nexport * from './types';\nexport * from './utils';\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 enum ExpressLayerType {\n ROUTER = 'router',\n MIDDLEWARE = 'middleware',\n REQUEST_HANDLER = 'request_handler',\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 enum AttributeNames {\n EXPRESS_TYPE = 'express.type',\n EXPRESS_NAME = 'express.name',\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 type { Request } from 'express';\nimport { Attributes } from '@opentelemetry/api';\n\n/**\n * This symbol is used to mark express layer as being already instrumented\n * since its possible to use a given layer multiple times (ex: middlewares)\n */\nexport const kLayerPatched: unique symbol = Symbol('express-layer-patched');\n\n/**\n * This const define where on the `request` object the Instrumentation will mount the\n * current stack of express layer.\n *\n * It is necessary because express doesn't store the different layers\n * (ie: middleware, router etc) that it called to get to the current layer.\n * Given that, the only way to know the route of a given layer is to\n * store the path of where each previous layer has been mounted.\n *\n * ex: bodyParser > auth middleware > /users router > get /:id\n * in this case the stack would be: [\"/users\", \"/:id\"]\n *\n * ex2: bodyParser > /api router > /v1 router > /users router > get /:id\n * stack: [\"/api\", \"/v1\", \"/users\", \":id\"]\n *\n */\nexport const _LAYERS_STORE_PROPERTY = '__ot_middlewares';\n\nexport type PatchedRequest = {\n [_LAYERS_STORE_PROPERTY]?: string[];\n} & Request;\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\n// https://github.com/expressjs/express/blob/main/lib/router/index.js#L53\nexport type ExpressRouter = {\n params: { [key: string]: string };\n _params: string[];\n caseSensitive: boolean;\n mergeParams: boolean;\n strict: boolean;\n stack: ExpressLayer[];\n};\n\n// https://github.com/expressjs/express/blob/main/lib/router/layer.js#L33\nexport type ExpressLayer = {\n handle: Function & Record<string, any>;\n [kLayerPatched]?: boolean;\n name: string;\n params: { [key: string]: string };\n path: string;\n regexp: RegExp;\n};\n\nexport type LayerMetadata = {\n attributes: Attributes;\n name: 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 { Attributes } from '@opentelemetry/api';\nimport {\n IgnoreMatcher,\n ExpressInstrumentationConfig,\n LayerPathSegment,\n} from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (request: PatchedRequest, value?: string) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return;\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${layerPath}`,\n };\n } else if (layer.name === 'bound dispatch') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layerPath ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n\n/**\n * Extracts the layer path from the route arguments\n *\n * @param args - Arguments of the route\n * @returns The layer path\n */\nexport const getLayerPath = (\n args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]\n): string | undefined => {\n if (Array.isArray(args[0])) {\n return args[0].map(arg => extractLayerPathSegment(arg) || '').join(',');\n }\n\n return extractLayerPathSegment(args[0]);\n};\n\nconst extractLayerPathSegment = (arg: LayerPathSegment) => {\n if (typeof arg === 'string') {\n return arg;\n }\n\n if (arg instanceof RegExp || typeof arg === 'number') {\n return arg.toString();\n }\n\n return;\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.41.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-express';\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 { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n getLayerPath,\n isLayerIgnored,\n storeLayerPath,\n} from './utils';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override setConfig(config: ExpressInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): ExpressInstrumentationConfig {\n return this._config as ExpressInstrumentationConfig;\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'express',\n ['>=4.0.0 <5'],\n moduleExports => {\n const routerProto = moduleExports.Router as unknown as express.Router;\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch() as any\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports === undefined) return;\n const routerProto = moduleExports.Router as unknown as express.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch() {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n this: { _router: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this._router.stack[this._router.stack.length - 1];\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', original => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n\n const patched = function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('')\n // remove duplicate slashes to normalize route\n .replace(/\\/{2,}/g, '/');\n\n const attributes: Attributes = {\n [SEMATTRS_HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation._config)) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n if (instrumentation.getConfig().requestHook) {\n safeExecuteInTheMiddle(\n () =>\n instrumentation.getConfig().requestHook!(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] !==\n ExpressLayerType.MIDDLEWARE\n ) {\n span.end();\n spanHasEnded = true;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (!spanHasEnded && isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError)) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return callback.apply(this, arguments);\n };\n }\n\n try {\n return original.apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly end the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n\n // `handle` isn't just a regular function in some cases. It also contains\n // some properties holding metadata and state so we need to proxy them\n // through through patched function\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n Object.keys(original).forEach(key => {\n Object.defineProperty(patched, key, {\n get() {\n return original[key];\n },\n set(value) {\n original[key] = value;\n },\n });\n });\n\n return patched;\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const hook = this.getConfig().spanNameHook;\n\n if (!(hook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return hook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\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 './instrumentation';\nexport * from './enums/ExpressLayerType';\nexport * from './enums/AttributeNames';\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\nexport enum AttributeNames {\n FASTIFY_NAME = 'fastify.name',\n FASTIFY_TYPE = 'fastify.type',\n HOOK_NAME = 'hook.name',\n PLUGIN_NAME = 'plugin.name',\n}\n\nexport enum FastifyTypes {\n MIDDLEWARE = 'middleware',\n REQUEST_HANDLER = 'request_handler',\n}\n\nexport enum FastifyNames {\n MIDDLEWARE = 'middleware',\n REQUEST_HANDLER = 'request handler',\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 spanRequestSymbol = Symbol(\n 'opentelemetry.instrumentation.fastify.request_active_span'\n);\n\n// The instrumentation creates a span for invocations of lifecycle hook handlers\n// that take `(request, reply, ...[, done])` arguments. Currently this is all\n// lifecycle hooks except `onRequestAbort`.\n// https://fastify.dev/docs/latest/Reference/Hooks\nexport const hooksNamesToWrap = new Set([\n 'onTimeout',\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preSerialization',\n 'preHandler',\n 'onSend',\n 'onResponse',\n 'onError',\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 { Attributes, Span, SpanStatusCode, Tracer } from '@opentelemetry/api';\nimport { spanRequestSymbol } from './constants';\n\nimport type { PluginFastifyReply } from './internal-types';\n\n/**\n * Starts Span\n * @param reply - reply function\n * @param tracer - tracer\n * @param spanName - span name\n * @param spanAttributes - span attributes\n */\nexport function startSpan(\n reply: PluginFastifyReply,\n tracer: Tracer,\n spanName: string,\n spanAttributes: Attributes = {}\n) {\n const span = tracer.startSpan(spanName, { attributes: spanAttributes });\n\n const spans: Span[] = reply[spanRequestSymbol] || [];\n spans.push(span);\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Object.defineProperty(reply, spanRequestSymbol, {\n enumerable: false,\n configurable: true,\n value: spans,\n });\n\n return span;\n}\n\n/**\n * Ends span\n * @param reply - reply function\n * @param err - error\n */\nexport function endSpan(reply: PluginFastifyReply, err?: any) {\n const spans = reply[spanRequestSymbol] || [];\n // there is no active span, or it has already ended\n if (!spans.length) {\n return;\n }\n spans.forEach(span => {\n if (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n span.recordException(err);\n }\n span.end();\n });\n delete reply[spanRequestSymbol];\n}\n\n// @TODO after approve add this to instrumentation package and replace usage\n// when it will be released\n\n/**\n * This function handles the missing case from instrumentation package when\n * execute can either return a promise or void. And using async is not an\n * option as it is producing unwanted side effects.\n * @param execute - function to be executed\n * @param onFinish - function called when function executed\n * @param preventThrowingError - prevent to throw error when execute\n * function fails\n */\nexport function safeExecuteInTheMiddleMaybePromise<T>(\n execute: () => Promise<T>,\n onFinish: (e: unknown, result?: T) => void,\n preventThrowingError?: boolean\n): Promise<T>;\nexport function safeExecuteInTheMiddleMaybePromise<T>(\n execute: () => T,\n onFinish: (e: unknown, result?: T) => void,\n preventThrowingError?: boolean\n): T;\nexport function safeExecuteInTheMiddleMaybePromise<T>(\n execute: () => T | Promise<T>,\n onFinish: (e: unknown, result?: T) => void,\n preventThrowingError?: boolean\n): T | Promise<T> | undefined {\n let error: unknown;\n let result: T | Promise<T> | undefined = undefined;\n try {\n result = execute();\n\n if (isPromise(result)) {\n result.then(\n res => onFinish(undefined, res),\n err => onFinish(err)\n );\n }\n } catch (e) {\n error = e;\n } finally {\n if (!isPromise(result)) {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n }\n // eslint-disable-next-line no-unsafe-finally\n return result;\n }\n}\n\nfunction isPromise<T>(val: T | Promise<T>): val is Promise<T> {\n return (\n (typeof val === 'object' &&\n val &&\n typeof Object.getOwnPropertyDescriptor(val, 'then')?.value ===\n 'function') ||\n false\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.38.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-fastify';\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, Attributes, SpanStatusCode, trace } from '@opentelemetry/api';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport type {\n HookHandlerDoneFunction,\n FastifyInstance,\n FastifyRequest,\n FastifyReply,\n} from 'fastify';\nimport { hooksNamesToWrap } from './constants';\nimport {\n AttributeNames,\n FastifyNames,\n FastifyTypes,\n} from './enums/AttributeNames';\nimport type { HandlerOriginal, PluginFastifyReply } from './internal-types';\nimport type { FastifyInstrumentationConfig } from './types';\nimport {\n endSpan,\n safeExecuteInTheMiddleMaybePromise,\n startSpan,\n} from './utils';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\nexport const ANONYMOUS_NAME = 'anonymous';\n\n/** Fastify instrumentation for OpenTelemetry */\nexport class FastifyInstrumentation extends InstrumentationBase {\n constructor(config: FastifyInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override setConfig(config: FastifyInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): FastifyInstrumentationConfig {\n return this._config as FastifyInstrumentationConfig;\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'fastify',\n ['>=3.0.0 <5'],\n moduleExports => {\n return this._patchConstructor(moduleExports);\n }\n ),\n ];\n }\n\n private _hookOnRequest() {\n const instrumentation = this;\n return function onRequest(\n request: FastifyRequest,\n reply: FastifyReply,\n done: HookHandlerDoneFunction\n ) {\n if (!instrumentation.isEnabled()) {\n return done();\n }\n instrumentation._wrap(reply, 'send', instrumentation._patchSend());\n\n const anyRequest = request as any;\n\n const rpcMetadata = getRPCMetadata(context.active());\n const routeName = anyRequest.routeOptions\n ? anyRequest.routeOptions.url // since fastify@4.10.0\n : request.routerPath;\n if (routeName && rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = routeName;\n }\n done();\n };\n }\n\n private _wrapHandler(\n pluginName: string,\n hookName: string,\n original: (...args: unknown[]) => Promise<unknown>,\n syncFunctionWithDone: boolean\n ): () => Promise<unknown> {\n const instrumentation = this;\n this._diag.debug('Patching fastify route.handler function');\n\n return function (this: any, ...args: unknown[]): Promise<unknown> {\n if (!instrumentation.isEnabled()) {\n return original.apply(this, args);\n }\n\n const name = original.name || pluginName || ANONYMOUS_NAME;\n const spanName = `${FastifyNames.MIDDLEWARE} - ${name}`;\n\n const reply = args[1] as PluginFastifyReply;\n\n const span = startSpan(reply, instrumentation.tracer, spanName, {\n [AttributeNames.FASTIFY_TYPE]: FastifyTypes.MIDDLEWARE,\n [AttributeNames.PLUGIN_NAME]: pluginName,\n [AttributeNames.HOOK_NAME]: hookName,\n });\n\n const origDone =\n syncFunctionWithDone &&\n (args[args.length - 1] as HookHandlerDoneFunction);\n if (origDone) {\n args[args.length - 1] = function (\n ...doneArgs: Parameters<HookHandlerDoneFunction>\n ) {\n endSpan(reply);\n origDone.apply(this, doneArgs);\n };\n }\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddleMaybePromise(\n () => {\n return original.apply(this, args);\n },\n err => {\n if (err instanceof Error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n span.recordException(err);\n }\n // async hooks should end the span as soon as the promise is resolved\n if (!syncFunctionWithDone) {\n endSpan(reply);\n }\n }\n );\n });\n };\n }\n\n private _wrapAddHook(): (\n original: FastifyInstance['addHook']\n ) => () => FastifyInstance {\n const instrumentation = this;\n this._diag.debug('Patching fastify server.addHook function');\n\n return function (\n original: FastifyInstance['addHook']\n ): () => FastifyInstance {\n return function wrappedAddHook(this: any, ...args: any) {\n const name = args[0] as string;\n const handler = args[1] as HandlerOriginal;\n const pluginName = this.pluginName;\n if (!hooksNamesToWrap.has(name)) {\n return original.apply(this, args);\n }\n\n const syncFunctionWithDone =\n typeof args[args.length - 1] === 'function' &&\n handler.constructor.name !== 'AsyncFunction';\n\n return original.apply(this, [\n name,\n instrumentation._wrapHandler(\n pluginName,\n name,\n handler,\n syncFunctionWithDone\n ),\n ] as never);\n };\n };\n }\n\n private _patchConstructor(moduleExports: {\n fastify: () => FastifyInstance;\n }): () => FastifyInstance {\n const instrumentation = this;\n\n function fastify(this: FastifyInstance, ...args: any) {\n const app: FastifyInstance = moduleExports.fastify.apply(this, args);\n app.addHook('onRequest', instrumentation._hookOnRequest());\n app.addHook('preHandler', instrumentation._hookPreHandler());\n\n instrumentation._wrap(app, 'addHook', instrumentation._wrapAddHook());\n\n return app;\n }\n\n fastify.fastify = fastify;\n fastify.default = fastify;\n return fastify;\n }\n\n private _patchSend() {\n const instrumentation = this;\n this._diag.debug('Patching fastify reply.send function');\n\n return function patchSend(\n original: () => FastifyReply\n ): () => FastifyReply {\n return function send(this: FastifyReply, ...args: any) {\n const maybeError: any = args[0];\n\n if (!instrumentation.isEnabled()) {\n return original.apply(this, args);\n }\n\n return safeExecuteInTheMiddle<FastifyReply>(\n () => {\n return original.apply(this, args);\n },\n err => {\n if (!err && maybeError instanceof Error) {\n err = maybeError;\n }\n endSpan(this, err);\n }\n );\n };\n };\n }\n\n private _hookPreHandler() {\n const instrumentation = this;\n this._diag.debug('Patching fastify preHandler function');\n\n return function preHandler(\n this: any,\n request: FastifyRequest,\n reply: FastifyReply,\n done: HookHandlerDoneFunction\n ) {\n if (!instrumentation.isEnabled()) {\n return done();\n }\n const anyRequest = request as any;\n\n const handler =\n anyRequest.routeOptions?.handler || anyRequest.context?.handler;\n\n const handlerName = handler?.name.startsWith('bound ')\n ? handler.name.substr(6)\n : handler?.name;\n const spanName = `${FastifyNames.REQUEST_HANDLER} - ${\n handlerName || this.pluginName || ANONYMOUS_NAME\n }`;\n\n const spanAttributes: Attributes = {\n [AttributeNames.PLUGIN_NAME]: this.pluginName,\n [AttributeNames.FASTIFY_TYPE]: FastifyTypes.REQUEST_HANDLER,\n [SEMATTRS_HTTP_ROUTE]: anyRequest.routeOptions\n ? anyRequest.routeOptions.url // since fastify@4.10.0\n : request.routerPath,\n };\n if (handlerName) {\n spanAttributes[AttributeNames.FASTIFY_NAME] = handlerName;\n }\n const span = startSpan(\n reply,\n instrumentation.tracer,\n spanName,\n spanAttributes\n );\n\n if (instrumentation.getConfig().requestHook) {\n safeExecuteInTheMiddle(\n () => instrumentation.getConfig().requestHook!(span, { request }),\n e => {\n if (e) {\n instrumentation._diag.error('request hook failed', e);\n }\n },\n true\n );\n }\n\n return context.with(trace.setSpan(context.active(), span), () => {\n done();\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 './enums/AttributeNames';\nexport * from './types';\nexport * from './instrumentation';\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 AllowedOperationTypes {\n QUERY = 'query',\n MUTATION = 'mutation',\n SUBSCRIPTION = 'subscription',\n}\n\nexport enum TokenKind {\n SOF = '<SOF>',\n EOF = '<EOF>',\n BANG = '!',\n DOLLAR = '$',\n AMP = '&',\n PAREN_L = '(',\n PAREN_R = ')',\n SPREAD = '...',\n COLON = ':',\n EQUALS = '=',\n AT = '@',\n BRACKET_L = '[',\n BRACKET_R = ']',\n BRACE_L = '{',\n PIPE = '|',\n BRACE_R = '}',\n NAME = 'Name',\n INT = 'Int',\n FLOAT = 'Float',\n STRING = 'String',\n BLOCK_STRING = 'BlockString',\n COMMENT = 'Comment',\n}\n\nexport enum SpanNames {\n EXECUTE = 'graphql.execute',\n PARSE = 'graphql.parse',\n RESOLVE = 'graphql.resolve',\n VALIDATE = 'graphql.validate',\n SCHEMA_VALIDATE = 'graphql.validateSchema',\n SCHEMA_PARSE = 'graphql.parseSchema',\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 enum AttributeNames {\n SOURCE = 'graphql.source',\n FIELD_NAME = 'graphql.field.name',\n FIELD_PATH = 'graphql.field.path',\n FIELD_TYPE = 'graphql.field.type',\n OPERATION_TYPE = 'graphql.operation.type',\n OPERATION_NAME = 'graphql.operation.name',\n VARIABLES = 'graphql.variables.',\n ERROR_VALIDATION_NAME = 'graphql.validation.error',\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 OTEL_PATCHED_SYMBOL = Symbol.for('opentelemetry.patched');\n\nexport const OTEL_GRAPHQL_DATA_SYMBOL = Symbol.for(\n 'opentelemetry.graphql_data'\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 { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport type * as graphqlTypes from 'graphql';\nimport type * as api from '@opentelemetry/api';\nimport type { PromiseOrValue } from 'graphql/jsutils/PromiseOrValue';\nimport type { DocumentNode } from 'graphql/language/ast';\nimport type {\n GraphQLFieldResolver,\n GraphQLTypeResolver,\n} from 'graphql/type/definition';\nimport { OTEL_GRAPHQL_DATA_SYMBOL, OTEL_PATCHED_SYMBOL } from './symbols';\nimport { GraphQLInstrumentationConfig } from './types';\n\nexport const OPERATION_NOT_SUPPORTED =\n 'Operation$operationName$not' + ' supported';\n\n/**\n * Merged and parsed config of default instrumentation config and GraphQL\n */\nexport type GraphQLInstrumentationParsedConfig =\n Required<GraphQLInstrumentationConfig> & InstrumentationConfig;\n\nexport type executeFunctionWithObj = (\n args: graphqlTypes.ExecutionArgs\n) => PromiseOrValue<graphqlTypes.ExecutionResult>;\n\nexport type executeArgumentsArray = [\n graphqlTypes.GraphQLSchema,\n graphqlTypes.DocumentNode,\n any,\n any,\n Maybe<{ [key: string]: any }>,\n Maybe<string>,\n Maybe<graphqlTypes.GraphQLFieldResolver<any, any>>,\n Maybe<graphqlTypes.GraphQLTypeResolver<any, any>>\n];\n\nexport type executeFunctionWithArgs = (\n schema: graphqlTypes.GraphQLSchema,\n document: graphqlTypes.DocumentNode,\n rootValue?: any,\n contextValue?: any,\n variableValues?: Maybe<{ [key: string]: any }>,\n operationName?: Maybe<string>,\n fieldResolver?: Maybe<graphqlTypes.GraphQLFieldResolver<any, any>>,\n typeResolver?: Maybe<graphqlTypes.GraphQLTypeResolver<any, any>>\n) => PromiseOrValue<graphqlTypes.ExecutionResult>;\n\nexport interface OtelExecutionArgs {\n schema: graphqlTypes.GraphQLSchema;\n document: DocumentNode & ObjectWithGraphQLData;\n rootValue?: any;\n contextValue?: any & ObjectWithGraphQLData;\n variableValues?: Maybe<{ [key: string]: any }>;\n operationName?: Maybe<string>;\n fieldResolver?: Maybe<GraphQLFieldResolver<any, any> & OtelPatched>;\n typeResolver?: Maybe<GraphQLTypeResolver<any, any>>;\n}\n\nexport type executeType = executeFunctionWithObj | executeFunctionWithArgs;\n\nexport type parseType = (\n source: string | graphqlTypes.Source,\n options?: graphqlTypes.ParseOptions\n) => graphqlTypes.DocumentNode;\n\nexport type validateType = (\n schema: graphqlTypes.GraphQLSchema,\n documentAST: graphqlTypes.DocumentNode,\n rules?: ReadonlyArray<graphqlTypes.ValidationRule>,\n options?: { maxErrors?: number },\n typeInfo?: graphqlTypes.TypeInfo\n) => ReadonlyArray<graphqlTypes.GraphQLError>;\n\nexport interface GraphQLField {\n parent: api.Span;\n span: api.Span;\n error: Error | null;\n}\n\ninterface OtelGraphQLData {\n source?: any;\n span: api.Span;\n fields: { [key: string]: GraphQLField };\n}\n\nexport interface ObjectWithGraphQLData {\n [OTEL_GRAPHQL_DATA_SYMBOL]?: OtelGraphQLData;\n}\n\nexport interface OtelPatched {\n [OTEL_PATCHED_SYMBOL]?: boolean;\n}\n\nexport interface GraphQLPath {\n prev: GraphQLPath | undefined;\n key: string | number;\n /**\n * optional as it didn't exist yet in ver 14\n */\n typename?: string | undefined;\n}\n\n/**\n * Moving this type from ver 15 of graphql as it is nto available in ver. 14s\n * this way it can compile against ver 14.\n */\nexport type Maybe<T> = null | undefined | T;\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 type * as graphqlTypes from 'graphql';\nimport * as api from '@opentelemetry/api';\nimport { AllowedOperationTypes, SpanNames, TokenKind } from './enum';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { OTEL_GRAPHQL_DATA_SYMBOL, OTEL_PATCHED_SYMBOL } from './symbols';\nimport {\n GraphQLField,\n GraphQLPath,\n GraphQLInstrumentationParsedConfig,\n ObjectWithGraphQLData,\n OtelPatched,\n Maybe,\n} from './internal-types';\nimport { GraphQLInstrumentationConfig } from './types';\n\nconst OPERATION_VALUES = Object.values(AllowedOperationTypes);\n\n// https://github.com/graphql/graphql-js/blob/main/src/jsutils/isPromise.ts\nexport const isPromise = (value: any): value is Promise<unknown> => {\n return typeof value?.then === 'function';\n};\n\n// https://github.com/graphql/graphql-js/blob/main/src/jsutils/isObjectLike.ts\nconst isObjectLike = (value: unknown): value is { [key: string]: unknown } => {\n return typeof value == 'object' && value !== null;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction addInputVariableAttribute(span: api.Span, key: string, variable: any) {\n if (Array.isArray(variable)) {\n variable.forEach((value, idx) => {\n addInputVariableAttribute(span, `${key}.${idx}`, value);\n });\n } else if (variable instanceof Object) {\n Object.entries(variable).forEach(([nestedKey, value]) => {\n addInputVariableAttribute(span, `${key}.${nestedKey}`, value);\n });\n } else {\n span.setAttribute(`${AttributeNames.VARIABLES}${String(key)}`, variable);\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function addInputVariableAttributes(\n span: api.Span,\n variableValues: { [key: string]: any }\n) {\n Object.entries(variableValues).forEach(([key, value]) => {\n addInputVariableAttribute(span, key, value);\n });\n}\n\nexport function addSpanSource(\n span: api.Span,\n loc?: graphqlTypes.Location,\n allowValues?: boolean,\n start?: number,\n end?: number\n): void {\n const source = getSourceFromLocation(loc, allowValues, start, end);\n span.setAttribute(AttributeNames.SOURCE, source);\n}\n\nfunction createFieldIfNotExists(\n tracer: api.Tracer,\n getConfig: () => GraphQLInstrumentationParsedConfig,\n contextValue: any,\n info: graphqlTypes.GraphQLResolveInfo,\n path: string[]\n): {\n field: any;\n spanAdded: boolean;\n} {\n let field = getField(contextValue, path);\n\n let spanAdded = false;\n\n if (!field) {\n spanAdded = true;\n const parent = getParentField(contextValue, path);\n\n field = {\n parent,\n span: createResolverSpan(\n tracer,\n getConfig,\n contextValue,\n info,\n path,\n parent.span\n ),\n error: null,\n };\n\n addField(contextValue, path, field);\n }\n\n return { spanAdded, field };\n}\n\nfunction createResolverSpan(\n tracer: api.Tracer,\n getConfig: () => GraphQLInstrumentationParsedConfig,\n contextValue: any,\n info: graphqlTypes.GraphQLResolveInfo,\n path: string[],\n parentSpan?: api.Span\n): api.Span {\n const attributes: api.SpanAttributes = {\n [AttributeNames.FIELD_NAME]: info.fieldName,\n [AttributeNames.FIELD_PATH]: path.join('.'),\n [AttributeNames.FIELD_TYPE]: info.returnType.toString(),\n };\n\n const span = tracer.startSpan(\n `${SpanNames.RESOLVE} ${attributes[AttributeNames.FIELD_PATH]}`,\n {\n attributes,\n },\n parentSpan ? api.trace.setSpan(api.context.active(), parentSpan) : undefined\n );\n\n const document = contextValue[OTEL_GRAPHQL_DATA_SYMBOL].source;\n const fieldNode = info.fieldNodes.find(\n fieldNode => fieldNode.kind === 'Field'\n );\n\n if (fieldNode) {\n addSpanSource(\n span,\n document.loc,\n getConfig().allowValues,\n fieldNode.loc?.start,\n fieldNode.loc?.end\n );\n }\n\n return span;\n}\n\nexport function endSpan(span: api.Span, error?: Error): void {\n if (error) {\n span.recordException(error);\n }\n span.end();\n}\n\nexport function getOperation(\n document: graphqlTypes.DocumentNode,\n operationName?: Maybe<string>\n): graphqlTypes.DefinitionNode | undefined {\n if (!document || !Array.isArray(document.definitions)) {\n return undefined;\n }\n\n if (operationName) {\n return document.definitions\n .filter(\n definition =>\n OPERATION_VALUES.indexOf((definition as any)?.operation) !== -1\n )\n .find(definition => operationName === (definition as any)?.name?.value);\n } else {\n return document.definitions.find(\n definition =>\n OPERATION_VALUES.indexOf((definition as any)?.operation) !== -1\n );\n }\n}\n\nfunction addField(contextValue: any, path: string[], field: GraphQLField) {\n return (contextValue[OTEL_GRAPHQL_DATA_SYMBOL].fields[path.join('.')] =\n field);\n}\n\nfunction getField(contextValue: any, path: string[]) {\n return contextValue[OTEL_GRAPHQL_DATA_SYMBOL].fields[path.join('.')];\n}\n\nfunction getParentField(contextValue: any, path: string[]) {\n for (let i = path.length - 1; i > 0; i--) {\n const field = getField(contextValue, path.slice(0, i));\n\n if (field) {\n return field;\n }\n }\n\n return {\n span: contextValue[OTEL_GRAPHQL_DATA_SYMBOL].span,\n };\n}\n\nfunction pathToArray(mergeItems: boolean, path: GraphQLPath): string[] {\n const flattened: string[] = [];\n let curr: GraphQLPath | undefined = path;\n while (curr) {\n let key = curr.key;\n\n if (mergeItems && typeof key === 'number') {\n key = '*';\n }\n flattened.push(String(key));\n curr = curr.prev;\n }\n return flattened.reverse();\n}\n\nfunction repeatBreak(i: number): string {\n return repeatChar('\\n', i);\n}\n\nfunction repeatSpace(i: number): string {\n return repeatChar(' ', i);\n}\n\nfunction repeatChar(char: string, to: number): string {\n let text = '';\n for (let i = 0; i < to; i++) {\n text += char;\n }\n return text;\n}\n\nconst KindsToBeRemoved: string[] = [\n TokenKind.FLOAT,\n TokenKind.STRING,\n TokenKind.INT,\n TokenKind.BLOCK_STRING,\n];\n\nexport function getSourceFromLocation(\n loc?: graphqlTypes.Location,\n allowValues = false,\n inputStart?: number,\n inputEnd?: number\n): string {\n let source = '';\n\n if (loc?.startToken) {\n const start = typeof inputStart === 'number' ? inputStart : loc.start;\n const end = typeof inputEnd === 'number' ? inputEnd : loc.end;\n\n let next: graphqlTypes.Token | null = loc.startToken.next;\n let previousLine: number | undefined = 1;\n while (next) {\n if (next.start < start) {\n next = next.next;\n previousLine = next?.line;\n continue;\n }\n if (next.end > end) {\n next = next.next;\n previousLine = next?.line;\n continue;\n }\n let value = next.value || next.kind;\n let space = '';\n if (!allowValues && KindsToBeRemoved.indexOf(next.kind) >= 0) {\n // value = repeatChar('*', value.length);\n value = '*';\n }\n if (next.kind === TokenKind.STRING) {\n value = `\"${value}\"`;\n }\n if (next.kind === TokenKind.EOF) {\n value = '';\n }\n if (next.line > previousLine!) {\n source += repeatBreak(next.line - previousLine!);\n previousLine = next.line;\n space = repeatSpace(next.column - 1);\n } else {\n if (next.line === next.prev?.line) {\n space = repeatSpace(next.start - (next.prev?.end || 0));\n }\n }\n source += space + value;\n if (next) {\n next = next.next!;\n }\n }\n }\n\n return source;\n}\n\nexport function wrapFields(\n type: Maybe<graphqlTypes.GraphQLObjectType & OtelPatched>,\n tracer: api.Tracer,\n getConfig: () => GraphQLInstrumentationParsedConfig\n): void {\n if (\n !type ||\n typeof type.getFields !== 'function' ||\n type[OTEL_PATCHED_SYMBOL]\n ) {\n return;\n }\n const fields = type.getFields();\n\n type[OTEL_PATCHED_SYMBOL] = true;\n\n Object.keys(fields).forEach(key => {\n const field = fields[key];\n\n if (!field) {\n return;\n }\n\n if (field.resolve) {\n field.resolve = wrapFieldResolver(tracer, getConfig, field.resolve);\n }\n\n if (field.type) {\n let unwrappedType: any = field.type;\n\n while (unwrappedType.ofType) {\n unwrappedType = unwrappedType.ofType;\n }\n wrapFields(unwrappedType, tracer, getConfig);\n }\n });\n}\n\nconst handleResolveSpanError = (\n resolveSpan: api.Span,\n err: any,\n shouldEndSpan: boolean\n) => {\n if (!shouldEndSpan) {\n return;\n }\n resolveSpan.recordException(err);\n resolveSpan.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n resolveSpan.end();\n};\n\nconst handleResolveSpanSuccess = (\n resolveSpan: api.Span,\n shouldEndSpan: boolean\n) => {\n if (!shouldEndSpan) {\n return;\n }\n resolveSpan.end();\n};\n\nexport function wrapFieldResolver<TSource = any, TContext = any, TArgs = any>(\n tracer: api.Tracer,\n getConfig: () => Required<GraphQLInstrumentationConfig>,\n fieldResolver: Maybe<\n graphqlTypes.GraphQLFieldResolver<TSource, TContext, TArgs> & OtelPatched\n >,\n isDefaultResolver = false\n): graphqlTypes.GraphQLFieldResolver<TSource, TContext, TArgs> & OtelPatched {\n if (\n (wrappedFieldResolver as OtelPatched)[OTEL_PATCHED_SYMBOL] ||\n typeof fieldResolver !== 'function'\n ) {\n return fieldResolver!;\n }\n\n function wrappedFieldResolver(\n this: graphqlTypes.GraphQLFieldResolver<TSource, TContext, TArgs>,\n source: TSource,\n args: TArgs,\n contextValue: TContext & ObjectWithGraphQLData,\n info: graphqlTypes.GraphQLResolveInfo\n ) {\n if (!fieldResolver) {\n return undefined;\n }\n const config = getConfig();\n\n // follows what graphql is doing to decide if this is a trivial resolver\n // for which we don't need to create a resolve span\n if (\n config.ignoreTrivialResolveSpans &&\n isDefaultResolver &&\n (isObjectLike(source) || typeof source === 'function')\n ) {\n const property = (source as any)[info.fieldName];\n // a function execution is not trivial and should be recorder.\n // property which is not a function is just a value and we don't want a \"resolve\" span for it\n if (typeof property !== 'function') {\n return fieldResolver.call(this, source, args, contextValue, info);\n }\n }\n\n if (!contextValue[OTEL_GRAPHQL_DATA_SYMBOL]) {\n return fieldResolver.call(this, source, args, contextValue, info);\n }\n const path = pathToArray(config.mergeItems, info && info.path);\n const depth = path.filter((item: any) => typeof item === 'string').length;\n\n let field: any;\n let shouldEndSpan = false;\n if (config.depth >= 0 && config.depth < depth) {\n field = getParentField(contextValue, path);\n } else {\n const newField = createFieldIfNotExists(\n tracer,\n getConfig,\n contextValue,\n info,\n path\n );\n field = newField.field;\n shouldEndSpan = newField.spanAdded;\n }\n\n return api.context.with(\n api.trace.setSpan(api.context.active(), field.span),\n () => {\n try {\n const res = fieldResolver.call(\n this,\n source,\n args,\n contextValue,\n info\n );\n if (isPromise(res)) {\n return res.then(\n (r: any) => {\n handleResolveSpanSuccess(field.span, shouldEndSpan);\n return r;\n },\n (err: Error) => {\n handleResolveSpanError(field.span, err, shouldEndSpan);\n throw err;\n }\n );\n } else {\n handleResolveSpanSuccess(field.span, shouldEndSpan);\n return res;\n }\n } catch (err: any) {\n handleResolveSpanError(field.span, err, shouldEndSpan);\n throw err;\n }\n }\n );\n }\n\n (wrappedFieldResolver as OtelPatched)[OTEL_PATCHED_SYMBOL] = true;\n\n return wrappedFieldResolver;\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.42.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-graphql';\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, trace } from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type * as graphqlTypes from 'graphql';\nimport { SpanNames } from './enum';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { OTEL_GRAPHQL_DATA_SYMBOL } from './symbols';\n\nimport {\n executeFunctionWithObj,\n executeArgumentsArray,\n executeType,\n parseType,\n validateType,\n GraphQLInstrumentationParsedConfig,\n OtelExecutionArgs,\n ObjectWithGraphQLData,\n OPERATION_NOT_SUPPORTED,\n Maybe,\n} from './internal-types';\nimport {\n addInputVariableAttributes,\n addSpanSource,\n endSpan,\n getOperation,\n isPromise,\n wrapFieldResolver,\n wrapFields,\n} from './utils';\n\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport * as api from '@opentelemetry/api';\nimport type { PromiseOrValue } from 'graphql/jsutils/PromiseOrValue';\nimport { GraphQLInstrumentationConfig } from './types';\n\nconst DEFAULT_CONFIG: GraphQLInstrumentationConfig = {\n mergeItems: false,\n depth: -1,\n allowValues: false,\n ignoreResolveSpans: false,\n};\n\nconst supportedVersions = ['>=14.0.0 <17'];\n\nexport class GraphQLInstrumentation extends InstrumentationBase {\n constructor(config: GraphQLInstrumentationConfig = {}) {\n super(\n PACKAGE_NAME,\n PACKAGE_VERSION,\n Object.assign({}, DEFAULT_CONFIG, config)\n );\n }\n\n private _getConfig(): GraphQLInstrumentationParsedConfig {\n return this._config as GraphQLInstrumentationParsedConfig;\n }\n\n override setConfig(config: GraphQLInstrumentationConfig = {}) {\n this._config = Object.assign({}, DEFAULT_CONFIG, config);\n }\n\n protected init() {\n const module = new InstrumentationNodeModuleDefinition(\n 'graphql',\n supportedVersions\n );\n module.files.push(this._addPatchingExecute());\n module.files.push(this._addPatchingParser());\n module.files.push(this._addPatchingValidate());\n\n return module;\n }\n\n private _addPatchingExecute(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/execution/execute.js',\n supportedVersions,\n // cannot make it work with appropriate type as execute function has 2\n //types and/cannot import function but only types\n (moduleExports: any) => {\n if (isWrapped(moduleExports.execute)) {\n this._unwrap(moduleExports, 'execute');\n }\n this._wrap(\n moduleExports,\n 'execute',\n this._patchExecute(moduleExports.defaultFieldResolver)\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'execute');\n }\n }\n );\n }\n\n private _addPatchingParser(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/language/parser.js',\n supportedVersions,\n (moduleExports: typeof graphqlTypes) => {\n if (isWrapped(moduleExports.parse)) {\n this._unwrap(moduleExports, 'parse');\n }\n this._wrap(moduleExports, 'parse', this._patchParse());\n return moduleExports;\n },\n (moduleExports: typeof graphqlTypes) => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'parse');\n }\n }\n );\n }\n\n private _addPatchingValidate(): InstrumentationNodeModuleFile {\n return new InstrumentationNodeModuleFile(\n 'graphql/validation/validate.js',\n supportedVersions,\n moduleExports => {\n if (isWrapped(moduleExports.validate)) {\n this._unwrap(moduleExports, 'validate');\n }\n this._wrap(moduleExports, 'validate', this._patchValidate());\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports) {\n this._unwrap(moduleExports, 'validate');\n }\n }\n );\n }\n\n private _patchExecute(\n defaultFieldResolved: graphqlTypes.GraphQLFieldResolver<any, any>\n ): (original: executeType) => executeType {\n const instrumentation = this;\n return function execute(original) {\n return function patchExecute(\n this: executeType\n ): PromiseOrValue<graphqlTypes.ExecutionResult> {\n let processedArgs: OtelExecutionArgs;\n\n // case when apollo server is used for example\n if (arguments.length >= 2) {\n const args = arguments as unknown as executeArgumentsArray;\n processedArgs = instrumentation._wrapExecuteArgs(\n args[0],\n args[1],\n args[2],\n args[3],\n args[4],\n args[5],\n args[6],\n args[7],\n defaultFieldResolved\n );\n } else {\n const args = arguments[0] as graphqlTypes.ExecutionArgs;\n processedArgs = instrumentation._wrapExecuteArgs(\n args.schema,\n args.document,\n args.rootValue,\n args.contextValue,\n args.variableValues,\n args.operationName,\n args.fieldResolver,\n args.typeResolver,\n defaultFieldResolved\n );\n }\n\n const operation = getOperation(\n processedArgs.document,\n processedArgs.operationName\n );\n\n const span = instrumentation._createExecuteSpan(\n operation,\n processedArgs\n );\n\n processedArgs.contextValue[OTEL_GRAPHQL_DATA_SYMBOL] = {\n source: processedArgs.document\n ? processedArgs.document ||\n (processedArgs.document as ObjectWithGraphQLData)[\n OTEL_GRAPHQL_DATA_SYMBOL\n ]\n : undefined,\n span,\n fields: {},\n };\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<\n PromiseOrValue<graphqlTypes.ExecutionResult>\n >(\n () => {\n return (original as executeFunctionWithObj).apply(this, [\n processedArgs,\n ]);\n },\n (err, result) => {\n instrumentation._handleExecutionResult(span, err, result);\n }\n );\n });\n };\n };\n }\n\n private _handleExecutionResult(\n span: api.Span,\n err?: Error,\n result?: PromiseOrValue<graphqlTypes.ExecutionResult>\n ) {\n const config = this._getConfig();\n if (result === undefined || err) {\n endSpan(span, err);\n return;\n }\n\n if (isPromise(result)) {\n (result as Promise<graphqlTypes.ExecutionResult>).then(\n resultData => {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, resultData);\n },\n error => {\n endSpan(span, error);\n }\n );\n } else {\n if (typeof config.responseHook !== 'function') {\n endSpan(span);\n return;\n }\n this._executeResponseHook(span, result as graphqlTypes.ExecutionResult);\n }\n }\n\n private _executeResponseHook(\n span: api.Span,\n result: graphqlTypes.ExecutionResult\n ) {\n const config = this._getConfig();\n safeExecuteInTheMiddle(\n () => {\n config.responseHook(span, result);\n },\n err => {\n if (err) {\n this._diag.error('Error running response hook', err);\n }\n\n endSpan(span, undefined);\n },\n true\n );\n }\n\n private _patchParse(): (original: parseType) => parseType {\n const instrumentation = this;\n return function parse(original) {\n return function patchParse(\n this: parseType,\n source: string | graphqlTypes.Source,\n options?: graphqlTypes.ParseOptions\n ): graphqlTypes.DocumentNode {\n return instrumentation._parse(this, original, source, options);\n };\n };\n }\n\n private _patchValidate(): (original: validateType) => validateType {\n const instrumentation = this;\n return function validate(original: validateType) {\n return function patchValidate(\n this: validateType,\n schema: graphqlTypes.GraphQLSchema,\n documentAST: graphqlTypes.DocumentNode,\n rules?: ReadonlyArray<graphqlTypes.ValidationRule>,\n options?: { maxErrors?: number },\n typeInfo?: graphqlTypes.TypeInfo\n ): ReadonlyArray<graphqlTypes.GraphQLError> {\n return instrumentation._validate(\n this,\n original,\n schema,\n documentAST,\n rules,\n typeInfo,\n options\n );\n };\n };\n }\n\n private _parse(\n obj: parseType,\n original: parseType,\n source: string | graphqlTypes.Source,\n options?: graphqlTypes.ParseOptions\n ): graphqlTypes.DocumentNode {\n const config = this._getConfig();\n const span = this.tracer.startSpan(SpanNames.PARSE);\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<\n graphqlTypes.DocumentNode & ObjectWithGraphQLData\n >(\n () => {\n return original.call(obj, source, options);\n },\n (err, result) => {\n if (result) {\n const operation = getOperation(result);\n if (!operation) {\n span.updateName(SpanNames.SCHEMA_PARSE);\n } else if (result.loc) {\n addSpanSource(span, result.loc, config.allowValues);\n }\n }\n endSpan(span, err);\n }\n );\n });\n }\n\n private _validate(\n obj: validateType,\n original: validateType,\n schema: graphqlTypes.GraphQLSchema,\n documentAST: graphqlTypes.DocumentNode,\n rules?: ReadonlyArray<graphqlTypes.ValidationRule>,\n typeInfo?: graphqlTypes.TypeInfo,\n options?: { maxErrors?: number }\n ): ReadonlyArray<graphqlTypes.GraphQLError> {\n const span = this.tracer.startSpan(SpanNames.VALIDATE, {});\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return safeExecuteInTheMiddle<ReadonlyArray<graphqlTypes.GraphQLError>>(\n () => {\n return original.call(\n obj,\n schema,\n documentAST,\n rules,\n options,\n typeInfo\n );\n },\n (err, errors) => {\n if (!documentAST.loc) {\n span.updateName(SpanNames.SCHEMA_VALIDATE);\n }\n if (errors && errors.length) {\n span.recordException({\n name: AttributeNames.ERROR_VALIDATION_NAME,\n message: JSON.stringify(errors),\n });\n }\n endSpan(span, err);\n }\n );\n });\n }\n\n private _createExecuteSpan(\n operation: graphqlTypes.DefinitionNode | undefined,\n processedArgs: graphqlTypes.ExecutionArgs\n ): api.Span {\n const config = this._getConfig();\n\n const span = this.tracer.startSpan(SpanNames.EXECUTE, {});\n if (operation) {\n const { operation: operationType, name: nameNode } =\n operation as graphqlTypes.OperationDefinitionNode;\n\n span.setAttribute(AttributeNames.OPERATION_TYPE, operationType);\n\n const operationName = nameNode?.value;\n\n // https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/instrumentation/graphql/\n // > The span name MUST be of the format <graphql.operation.type> <graphql.operation.name> provided that graphql.operation.type and graphql.operation.name are available.\n // > If graphql.operation.name is not available, the span SHOULD be named <graphql.operation.type>.\n if (operationName) {\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n span.updateName(`${operationType} ${operationName}`);\n } else {\n span.updateName(operationType);\n }\n } else {\n let operationName = ' ';\n if (processedArgs.operationName) {\n operationName = ` \"${processedArgs.operationName}\" `;\n }\n operationName = OPERATION_NOT_SUPPORTED.replace(\n '$operationName$',\n operationName\n );\n span.setAttribute(AttributeNames.OPERATION_NAME, operationName);\n }\n\n if (processedArgs.document?.loc) {\n addSpanSource(span, processedArgs.document.loc, config.allowValues);\n }\n\n if (processedArgs.variableValues && config.allowValues) {\n addInputVariableAttributes(span, processedArgs.variableValues);\n }\n\n return span;\n }\n\n private _wrapExecuteArgs(\n schema: graphqlTypes.GraphQLSchema,\n document: graphqlTypes.DocumentNode,\n rootValue: any,\n contextValue: any,\n variableValues: Maybe<{ [key: string]: any }>,\n operationName: Maybe<string>,\n fieldResolver: Maybe<graphqlTypes.GraphQLFieldResolver<any, any>>,\n typeResolver: Maybe<graphqlTypes.GraphQLTypeResolver<any, any>>,\n defaultFieldResolved: graphqlTypes.GraphQLFieldResolver<any, any>\n ): OtelExecutionArgs {\n if (!contextValue) {\n contextValue = {};\n }\n\n if (\n contextValue[OTEL_GRAPHQL_DATA_SYMBOL] ||\n this._getConfig().ignoreResolveSpans\n ) {\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n };\n }\n\n const isUsingDefaultResolver = fieldResolver == null;\n // follows graphql implementation here:\n // https://github.com/graphql/graphql-js/blob/0b7daed9811731362c71900e12e5ea0d1ecc7f1f/src/execution/execute.ts#L494\n const fieldResolverForExecute = fieldResolver ?? defaultFieldResolved;\n fieldResolver = wrapFieldResolver(\n this.tracer,\n this._getConfig.bind(this),\n fieldResolverForExecute,\n isUsingDefaultResolver\n );\n\n if (schema) {\n wrapFields(\n schema.getQueryType(),\n this.tracer,\n this._getConfig.bind(this)\n );\n wrapFields(\n schema.getMutationType(),\n this.tracer,\n this._getConfig.bind(this)\n );\n }\n\n return {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\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 './instrumentation';\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 { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { Span } from '@opentelemetry/api';\n\nexport interface MongoDBInstrumentationExecutionResponseHook {\n (span: Span, responseInfo: MongoResponseHookInformation): void;\n}\n\n/**\n * Function that can be used to serialize db.statement tag\n * @param cmd - MongoDB command object\n *\n * @returns serialized string that will be used as the db.statement attribute.\n */\nexport type DbStatementSerializer = (cmd: Record<string, unknown>) => string;\n\nexport interface MongoDBInstrumentationConfig extends InstrumentationConfig {\n /**\n * If true, additional information about query parameters and\n * results will be attached (as `attributes`) to spans representing\n * database operations.\n */\n enhancedDatabaseReporting?: boolean;\n\n /**\n * Hook that allows adding custom span attributes based on the data\n * returned from MongoDB actions.\n *\n * @default undefined\n */\n responseHook?: MongoDBInstrumentationExecutionResponseHook;\n\n /**\n * Custom serializer function for the db.statement tag\n */\n dbStatementSerializer?: DbStatementSerializer;\n}\n\nexport type Func<T> = (...args: unknown[]) => T;\nexport type MongoInternalCommand = {\n findandmodify: boolean;\n createIndexes: boolean;\n count: boolean;\n aggregate: boolean;\n ismaster: boolean;\n indexes?: unknown[];\n query?: Record<string, unknown>;\n limit?: number;\n q?: Record<string, unknown>;\n u?: Record<string, unknown>;\n};\n\nexport type ServerSession = {\n id: any;\n lastUse: number;\n txnNumber: number;\n isDirty: boolean;\n};\n\nexport type CursorState = { cmd: MongoInternalCommand } & Record<\n string,\n unknown\n>;\n\nexport interface MongoResponseHookInformation {\n data: CommandResult;\n}\n\n// https://github.com/mongodb/node-mongodb-native/blob/3.6/lib/core/connection/command_result.js\nexport type CommandResult = {\n result?: unknown;\n connection?: unknown;\n message?: unknown;\n};\n\n// https://github.com/mongodb/node-mongodb-native/blob/3.6/lib/core/wireprotocol/index.js\nexport type WireProtocolInternal = {\n insert: (\n server: MongoInternalTopology,\n ns: string,\n ops: unknown[],\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n update: (\n server: MongoInternalTopology,\n ns: string,\n ops: unknown[],\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n remove: (\n server: MongoInternalTopology,\n ns: string,\n ops: unknown[],\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n killCursors: (\n server: MongoInternalTopology,\n ns: string,\n cursorState: CursorState,\n callback: Function\n ) => unknown;\n getMore: (\n server: MongoInternalTopology,\n ns: string,\n cursorState: CursorState,\n batchSize: number,\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n query: (\n server: MongoInternalTopology,\n ns: string,\n cmd: MongoInternalCommand,\n cursorState: CursorState,\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n command: (\n server: MongoInternalTopology,\n ns: string,\n cmd: MongoInternalCommand,\n options: unknown | Function,\n callback?: Function\n ) => unknown;\n};\n\n// https://github.com/mongodb/node-mongodb-native/blob/3.6/lib/topologies/server.js#L172\n// https://github.com/mongodb/node-mongodb-native/blob/2.2/lib/server.js#L174\nexport type MongoInternalTopology = {\n s?: {\n // those are for mongodb@3\n options?: {\n host?: string;\n port?: number;\n servername?: string;\n };\n // those are for mongodb@2\n host?: string;\n port?: number;\n };\n // mongodb@3 with useUnifiedTopology option\n description?: {\n address?: string;\n };\n};\n\nexport enum MongodbCommandType {\n CREATE_INDEXES = 'createIndexes',\n FIND_AND_MODIFY = 'findAndModify',\n IS_MASTER = 'isMaster',\n COUNT = 'count',\n AGGREGATE = 'aggregate',\n UNKNOWN = 'unknown',\n}\n\n// https://github.com/mongodb/js-bson/blob/main/src/bson.ts\nexport type Document = {\n [key: string]: any;\n};\n\n// https://github.com/mongodb/node-mongodb-native/blob/v6.4.0/src/utils.ts#L281\nexport interface MongodbNamespace {\n db: string;\n collection?: string;\n}\n\nexport type V4Connection = {\n command: Function;\n // From version 6.4.0 the method does not expect a callback and returns a promise\n // https://github.com/mongodb/node-mongodb-native/blob/v6.4.2/src/cmap/connection.ts\n commandPromise(\n ns: MongodbNamespace,\n cmd: Document,\n options: undefined | unknown,\n // From v6.6.0 we have this new param which is a constructor function\n // https://github.com/mongodb/node-mongodb-native/blob/v6.6.0/src/cmap/connection.ts#L588\n responseType: undefined | unknown\n ): Promise<any>;\n // Earlier versions expect a callback param and return void\n // https://github.com/mongodb/node-mongodb-native/blob/v4.2.2/src/cmap/connection.ts\n commandCallback(\n ns: MongodbNamespace,\n cmd: Document,\n options: undefined | unknown,\n callback: any\n ): void;\n};\n\n// https://github.com/mongodb/node-mongodb-native/blob/v4.2.2/src/cmap/connection_pool.ts\nexport type V4ConnectionPool = {\n // Instrumentation just cares about carrying the async context so\n // types of callback params are not needed\n checkOut: (callback: (error: any, connection: any) => void) => void;\n};\n\nexport type V4Connect = {\n connect: Function;\n // From version 6.4.0 the method does not expect a callback and returns a promise\n // https://github.com/mongodb/node-mongodb-native/blob/v6.4.0/src/cmap/connect.ts\n connectPromise: (options: any) => Promise<any>;\n // Earlier versions expect a callback param and return void\n // https://github.com/mongodb/node-mongodb-native/blob/v4.2.2/src/cmap/connect.ts\n connectCallback: (options: any, callback: any) => void;\n};\n\n// https://github.com/mongodb/node-mongodb-native/blob/v4.2.2/src/sessions.ts\nexport type V4Session = {\n acquire: () => ServerSession;\n release: (session: ServerSession) => 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\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.46.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-mongodb';\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 context,\n trace,\n Span,\n SpanKind,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport {\n DBSYSTEMVALUES_MONGODB,\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_DB_MONGODB_COLLECTION,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_OPERATION,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n} from '@opentelemetry/semantic-conventions';\nimport { MongoDBInstrumentationConfig, CommandResult } from './types';\nimport {\n CursorState,\n ServerSession,\n MongodbCommandType,\n MongoInternalCommand,\n MongodbNamespace,\n MongoInternalTopology,\n WireProtocolInternal,\n V4Connection,\n V4ConnectionPool,\n} from './internal-types';\nimport { V4Connect, V4Session } from './internal-types';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { UpDownCounter } from '@opentelemetry/api';\n\n/** mongodb instrumentation plugin for OpenTelemetry */\nexport class MongoDBInstrumentation extends InstrumentationBase {\n private _connectionsUsage!: UpDownCounter;\n private _poolName!: string;\n\n protected override _config!: MongoDBInstrumentationConfig;\n\n constructor(config: MongoDBInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override _updateMetricInstruments() {\n this._connectionsUsage = this.meter.createUpDownCounter(\n 'db.client.connections.usage',\n {\n description:\n 'The number of connections that are currently in state described by the state attribute.',\n unit: '{connection}',\n }\n );\n }\n\n init() {\n const {\n v3PatchConnection: v3PatchConnection,\n v3UnpatchConnection: v3UnpatchConnection,\n } = this._getV3ConnectionPatches();\n\n const { v4PatchConnect, v4UnpatchConnect } = this._getV4ConnectPatches();\n const {\n v4PatchConnectionCallback,\n v4PatchConnectionPromise,\n v4UnpatchConnection,\n } = this._getV4ConnectionPatches();\n const { v4PatchConnectionPool, v4UnpatchConnectionPool } =\n this._getV4ConnectionPoolPatches();\n const { v4PatchSessions, v4UnpatchSessions } = this._getV4SessionsPatches();\n\n return [\n new InstrumentationNodeModuleDefinition(\n 'mongodb',\n ['>=3.3.0 <4'],\n undefined,\n undefined,\n [\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/core/wireprotocol/index.js',\n ['>=3.3.0 <4'],\n v3PatchConnection,\n v3UnpatchConnection\n ),\n ]\n ),\n new InstrumentationNodeModuleDefinition(\n 'mongodb',\n ['>=4.0.0 <7'],\n undefined,\n undefined,\n [\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/cmap/connection.js',\n ['>=4.0.0 <6.4'],\n v4PatchConnectionCallback,\n v4UnpatchConnection\n ),\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/cmap/connection.js',\n ['>=6.4.0 <7'],\n v4PatchConnectionPromise,\n v4UnpatchConnection\n ),\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/cmap/connection_pool.js',\n ['>=4.0.0 <6.4'],\n v4PatchConnectionPool,\n v4UnpatchConnectionPool\n ),\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/cmap/connect.js',\n ['>=4.0.0 <7'],\n v4PatchConnect,\n v4UnpatchConnect\n ),\n new InstrumentationNodeModuleFile(\n 'mongodb/lib/sessions.js',\n ['>=4.0.0 <7'],\n v4PatchSessions,\n v4UnpatchSessions\n ),\n ]\n ),\n ];\n }\n\n private _getV3ConnectionPatches<T extends WireProtocolInternal>() {\n return {\n v3PatchConnection: (moduleExports: T) => {\n // patch insert operation\n if (isWrapped(moduleExports.insert)) {\n this._unwrap(moduleExports, 'insert');\n }\n this._wrap(\n moduleExports,\n 'insert',\n this._getV3PatchOperation('insert')\n );\n // patch remove operation\n if (isWrapped(moduleExports.remove)) {\n this._unwrap(moduleExports, 'remove');\n }\n this._wrap(\n moduleExports,\n 'remove',\n this._getV3PatchOperation('remove')\n );\n // patch update operation\n if (isWrapped(moduleExports.update)) {\n this._unwrap(moduleExports, 'update');\n }\n this._wrap(\n moduleExports,\n 'update',\n this._getV3PatchOperation('update')\n );\n // patch other command\n if (isWrapped(moduleExports.command)) {\n this._unwrap(moduleExports, 'command');\n }\n this._wrap(moduleExports, 'command', this._getV3PatchCommand());\n // patch query\n if (isWrapped(moduleExports.query)) {\n this._unwrap(moduleExports, 'query');\n }\n this._wrap(moduleExports, 'query', this._getV3PatchFind());\n // patch get more operation on cursor\n if (isWrapped(moduleExports.getMore)) {\n this._unwrap(moduleExports, 'getMore');\n }\n this._wrap(moduleExports, 'getMore', this._getV3PatchCursor());\n return moduleExports;\n },\n v3UnpatchConnection: (moduleExports?: T) => {\n if (moduleExports === undefined) return;\n this._unwrap(moduleExports, 'insert');\n this._unwrap(moduleExports, 'remove');\n this._unwrap(moduleExports, 'update');\n this._unwrap(moduleExports, 'command');\n this._unwrap(moduleExports, 'query');\n this._unwrap(moduleExports, 'getMore');\n },\n };\n }\n\n private _getV4SessionsPatches<T extends V4Session>() {\n return {\n v4PatchSessions: (moduleExports: any) => {\n if (isWrapped(moduleExports.acquire)) {\n this._unwrap(moduleExports, 'acquire');\n }\n this._wrap(\n moduleExports.ServerSessionPool.prototype,\n 'acquire',\n this._getV4AcquireCommand()\n );\n\n if (isWrapped(moduleExports.release)) {\n this._unwrap(moduleExports, 'release');\n }\n this._wrap(\n moduleExports.ServerSessionPool.prototype,\n 'release',\n this._getV4ReleaseCommand()\n );\n return moduleExports;\n },\n v4UnpatchSessions: (moduleExports?: T) => {\n if (moduleExports === undefined) return;\n if (isWrapped(moduleExports.acquire)) {\n this._unwrap(moduleExports, 'acquire');\n }\n if (isWrapped(moduleExports.release)) {\n this._unwrap(moduleExports, 'release');\n }\n },\n };\n }\n\n private _getV4AcquireCommand() {\n const instrumentation = this;\n return (original: V4Session['acquire']) => {\n return function patchAcquire(this: any) {\n const nSessionsBeforeAcquire = this.sessions.length;\n const session = original.call(this);\n const nSessionsAfterAcquire = this.sessions.length;\n\n if (nSessionsBeforeAcquire === nSessionsAfterAcquire) {\n //no session in the pool. a new session was created and used\n instrumentation._connectionsUsage.add(1, {\n state: 'used',\n 'pool.name': instrumentation._poolName,\n });\n } else if (nSessionsBeforeAcquire - 1 === nSessionsAfterAcquire) {\n //a session was already in the pool. remove it from the pool and use it.\n instrumentation._connectionsUsage.add(-1, {\n state: 'idle',\n 'pool.name': instrumentation._poolName,\n });\n instrumentation._connectionsUsage.add(1, {\n state: 'used',\n 'pool.name': instrumentation._poolName,\n });\n }\n return session;\n };\n };\n }\n\n private _getV4ReleaseCommand() {\n const instrumentation = this;\n return (original: V4Session['release']) => {\n return function patchRelease(this: any, session: ServerSession) {\n const cmdPromise = original.call(this, session);\n\n instrumentation._connectionsUsage.add(-1, {\n state: 'used',\n 'pool.name': instrumentation._poolName,\n });\n instrumentation._connectionsUsage.add(1, {\n state: 'idle',\n 'pool.name': instrumentation._poolName,\n });\n return cmdPromise;\n };\n };\n }\n\n private _getV4ConnectionPoolPatches<T extends V4ConnectionPool>() {\n return {\n v4PatchConnectionPool: (moduleExports: any) => {\n const poolPrototype = moduleExports.ConnectionPool.prototype;\n\n if (isWrapped(poolPrototype.checkOut)) {\n this._unwrap(poolPrototype, 'checkOut');\n }\n\n this._wrap(\n poolPrototype,\n 'checkOut',\n this._getV4ConnectionPoolCheckOut()\n );\n return moduleExports;\n },\n v4UnpatchConnectionPool: (moduleExports?: any) => {\n if (moduleExports === undefined) return;\n\n this._unwrap(moduleExports.ConnectionPool.prototype, 'checkOut');\n },\n };\n }\n\n private _getV4ConnectPatches<T extends V4Connect>() {\n return {\n v4PatchConnect: (moduleExports: any) => {\n if (isWrapped(moduleExports.connect)) {\n this._unwrap(moduleExports, 'connect');\n }\n\n this._wrap(moduleExports, 'connect', this._getV4ConnectCommand());\n return moduleExports;\n },\n v4UnpatchConnect: (moduleExports?: T) => {\n if (moduleExports === undefined) return;\n\n this._unwrap(moduleExports, 'connect');\n },\n };\n }\n\n // This patch will become unnecessary once\n // https://jira.mongodb.org/browse/NODE-5639 is done.\n private _getV4ConnectionPoolCheckOut() {\n return (original: V4ConnectionPool['checkOut']) => {\n return function patchedCheckout(this: unknown, callback: any) {\n const patchedCallback = context.bind(context.active(), callback);\n return original.call(this, patchedCallback);\n };\n };\n }\n\n private _getV4ConnectCommand() {\n const instrumentation = this;\n\n return (\n original: V4Connect['connectCallback'] | V4Connect['connectPromise']\n ) => {\n return function patchedConnect(\n this: unknown,\n options: any,\n callback: any\n ) {\n // from v6.4 `connect` method only accepts an options param and returns a promise\n // with the connection\n if (original.length === 1) {\n const result = (original as V4Connect['connectPromise']).call(\n this,\n options\n );\n if (result && typeof result.then === 'function') {\n result.then(\n () => instrumentation.setPoolName(options),\n // this handler is set to pass the lint rules\n () => undefined\n );\n }\n return result;\n }\n\n // Earlier versions expects a callback param and return void\n const patchedCallback = function (err: any, conn: any) {\n if (err || !conn) {\n callback(err, conn);\n return;\n }\n instrumentation.setPoolName(options);\n callback(err, conn);\n };\n\n return (original as V4Connect['connectCallback']).call(\n this,\n options,\n patchedCallback\n );\n };\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n private _getV4ConnectionPatches<T extends V4Connection>() {\n return {\n v4PatchConnectionCallback: (moduleExports: any) => {\n // patch insert operation\n if (isWrapped(moduleExports.Connection.prototype.command)) {\n this._unwrap(moduleExports.Connection.prototype, 'command');\n }\n\n this._wrap(\n moduleExports.Connection.prototype,\n 'command',\n this._getV4PatchCommandCallback()\n );\n return moduleExports;\n },\n v4PatchConnectionPromise: (moduleExports: any) => {\n // patch insert operation\n if (isWrapped(moduleExports.Connection.prototype.command)) {\n this._unwrap(moduleExports.Connection.prototype, 'command');\n }\n\n this._wrap(\n moduleExports.Connection.prototype,\n 'command',\n this._getV4PatchCommandPromise()\n );\n return moduleExports;\n },\n v4UnpatchConnection: (moduleExports?: any) => {\n if (moduleExports === undefined) return;\n this._unwrap(moduleExports.Connection.prototype, 'command');\n },\n };\n }\n\n /** Creates spans for common operations */\n private _getV3PatchOperation(operationName: 'insert' | 'update' | 'remove') {\n const instrumentation = this;\n return (original: WireProtocolInternal[typeof operationName]) => {\n return function patchedServerCommand(\n this: unknown,\n server: MongoInternalTopology,\n ns: string,\n ops: unknown[],\n options: unknown | Function,\n callback?: Function\n ) {\n const currentSpan = trace.getSpan(context.active());\n const resultHandler =\n typeof options === 'function' ? options : callback;\n if (\n !currentSpan ||\n typeof resultHandler !== 'function' ||\n typeof ops !== 'object'\n ) {\n if (typeof options === 'function') {\n return original.call(this, server, ns, ops, options);\n } else {\n return original.call(this, server, ns, ops, options, callback);\n }\n }\n const span = instrumentation.tracer.startSpan(\n `mongodb.${operationName}`,\n {\n kind: SpanKind.CLIENT,\n }\n );\n\n instrumentation._populateV3Attributes(\n span,\n ns,\n server,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ops[0] as any,\n operationName\n );\n const patchedCallback = instrumentation._patchEnd(span, resultHandler);\n // handle when options is the callback to send the correct number of args\n if (typeof options === 'function') {\n return original.call(this, server, ns, ops, patchedCallback);\n } else {\n return original.call(this, server, ns, ops, options, patchedCallback);\n }\n };\n };\n }\n\n /** Creates spans for command operation */\n private _getV3PatchCommand() {\n const instrumentation = this;\n return (original: WireProtocolInternal['command']) => {\n return function patchedServerCommand(\n this: unknown,\n server: MongoInternalTopology,\n ns: string,\n cmd: MongoInternalCommand,\n options: unknown | Function,\n callback?: Function\n ) {\n const currentSpan = trace.getSpan(context.active());\n const resultHandler =\n typeof options === 'function' ? options : callback;\n if (\n !currentSpan ||\n typeof resultHandler !== 'function' ||\n typeof cmd !== 'object'\n ) {\n if (typeof options === 'function') {\n return original.call(this, server, ns, cmd, options);\n } else {\n return original.call(this, server, ns, cmd, options, callback);\n }\n }\n const commandType = MongoDBInstrumentation._getCommandType(cmd);\n const type =\n commandType === MongodbCommandType.UNKNOWN ? 'command' : commandType;\n const span = instrumentation.tracer.startSpan(`mongodb.${type}`, {\n kind: SpanKind.CLIENT,\n });\n const operation =\n commandType === MongodbCommandType.UNKNOWN ? undefined : commandType;\n instrumentation._populateV3Attributes(span, ns, server, cmd, operation);\n const patchedCallback = instrumentation._patchEnd(span, resultHandler);\n // handle when options is the callback to send the correct number of args\n if (typeof options === 'function') {\n return original.call(this, server, ns, cmd, patchedCallback);\n } else {\n return original.call(this, server, ns, cmd, options, patchedCallback);\n }\n };\n };\n }\n\n /** Creates spans for command operation */\n private _getV4PatchCommandCallback() {\n const instrumentation = this;\n return (original: V4Connection['commandCallback']) => {\n return function patchedV4ServerCommand(\n this: any,\n ns: MongodbNamespace,\n cmd: any,\n options: undefined | unknown,\n callback: any\n ) {\n const currentSpan = trace.getSpan(context.active());\n const resultHandler = callback;\n const commandType = Object.keys(cmd)[0];\n\n if (\n typeof resultHandler !== 'function' ||\n typeof cmd !== 'object' ||\n cmd.ismaster ||\n cmd.hello\n ) {\n return original.call(this, ns, cmd, options, callback);\n }\n\n let span = undefined;\n if (currentSpan) {\n span = instrumentation.tracer.startSpan(`mongodb.${commandType}`, {\n kind: SpanKind.CLIENT,\n });\n instrumentation._populateV4Attributes(\n span,\n this,\n ns,\n cmd,\n commandType\n );\n }\n const patchedCallback = instrumentation._patchEnd(\n span,\n resultHandler,\n this.id,\n commandType\n );\n\n return original.call(this, ns, cmd, options, patchedCallback);\n };\n };\n }\n\n private _getV4PatchCommandPromise() {\n const instrumentation = this;\n return (original: V4Connection['commandPromise']) => {\n return function patchedV4ServerCommand(\n this: any,\n ...args: Parameters<V4Connection['commandPromise']>\n ) {\n const [ns, cmd] = args;\n const currentSpan = trace.getSpan(context.active());\n const commandType = Object.keys(cmd)[0];\n const resultHandler = () => undefined;\n\n if (typeof cmd !== 'object' || cmd.ismaster || cmd.hello) {\n return original.apply(this, args);\n }\n\n let span = undefined;\n if (currentSpan) {\n span = instrumentation.tracer.startSpan(`mongodb.${commandType}`, {\n kind: SpanKind.CLIENT,\n });\n instrumentation._populateV4Attributes(\n span,\n this,\n ns,\n cmd,\n commandType\n );\n }\n\n const patchedCallback = instrumentation._patchEnd(\n span,\n resultHandler,\n this.id,\n commandType\n );\n\n const result = original.apply(this, args);\n result.then(\n (res: any) => patchedCallback(null, res),\n (err: any) => patchedCallback(err)\n );\n\n return result;\n };\n };\n }\n\n /** Creates spans for find operation */\n private _getV3PatchFind() {\n const instrumentation = this;\n return (original: WireProtocolInternal['query']) => {\n return function patchedServerCommand(\n this: unknown,\n server: MongoInternalTopology,\n ns: string,\n cmd: MongoInternalCommand,\n cursorState: CursorState,\n options: unknown | Function,\n callback?: Function\n ) {\n const currentSpan = trace.getSpan(context.active());\n const resultHandler =\n typeof options === 'function' ? options : callback;\n if (\n !currentSpan ||\n typeof resultHandler !== 'function' ||\n typeof cmd !== 'object'\n ) {\n if (typeof options === 'function') {\n return original.call(this, server, ns, cmd, cursorState, options);\n } else {\n return original.call(\n this,\n server,\n ns,\n cmd,\n cursorState,\n options,\n callback\n );\n }\n }\n const span = instrumentation.tracer.startSpan('mongodb.find', {\n kind: SpanKind.CLIENT,\n });\n instrumentation._populateV3Attributes(span, ns, server, cmd, 'find');\n const patchedCallback = instrumentation._patchEnd(span, resultHandler);\n // handle when options is the callback to send the correct number of args\n if (typeof options === 'function') {\n return original.call(\n this,\n server,\n ns,\n cmd,\n cursorState,\n patchedCallback\n );\n } else {\n return original.call(\n this,\n server,\n ns,\n cmd,\n cursorState,\n options,\n patchedCallback\n );\n }\n };\n };\n }\n\n /** Creates spans for find operation */\n private _getV3PatchCursor() {\n const instrumentation = this;\n return (original: WireProtocolInternal['getMore']) => {\n return function patchedServerCommand(\n this: unknown,\n server: MongoInternalTopology,\n ns: string,\n cursorState: CursorState,\n batchSize: number,\n options: unknown | Function,\n callback?: Function\n ) {\n const currentSpan = trace.getSpan(context.active());\n const resultHandler =\n typeof options === 'function' ? options : callback;\n if (!currentSpan || typeof resultHandler !== 'function') {\n if (typeof options === 'function') {\n return original.call(\n this,\n server,\n ns,\n cursorState,\n batchSize,\n options\n );\n } else {\n return original.call(\n this,\n server,\n ns,\n cursorState,\n batchSize,\n options,\n callback\n );\n }\n }\n const span = instrumentation.tracer.startSpan('mongodb.getMore', {\n kind: SpanKind.CLIENT,\n });\n instrumentation._populateV3Attributes(\n span,\n ns,\n server,\n cursorState.cmd,\n 'getMore'\n );\n const patchedCallback = instrumentation._patchEnd(span, resultHandler);\n // handle when options is the callback to send the correct number of args\n if (typeof options === 'function') {\n return original.call(\n this,\n server,\n ns,\n cursorState,\n batchSize,\n patchedCallback\n );\n } else {\n return original.call(\n this,\n server,\n ns,\n cursorState,\n batchSize,\n options,\n patchedCallback\n );\n }\n };\n };\n }\n\n /**\n * Get the mongodb command type from the object.\n * @param command Internal mongodb command object\n */\n private static _getCommandType(\n command: MongoInternalCommand\n ): MongodbCommandType {\n if (command.createIndexes !== undefined) {\n return MongodbCommandType.CREATE_INDEXES;\n } else if (command.findandmodify !== undefined) {\n return MongodbCommandType.FIND_AND_MODIFY;\n } else if (command.ismaster !== undefined) {\n return MongodbCommandType.IS_MASTER;\n } else if (command.count !== undefined) {\n return MongodbCommandType.COUNT;\n } else if (command.aggregate !== undefined) {\n return MongodbCommandType.AGGREGATE;\n } else {\n return MongodbCommandType.UNKNOWN;\n }\n }\n\n /**\n * Populate span's attributes by fetching related metadata from the context\n * @param span span to add attributes to\n * @param connectionCtx mongodb internal connection context\n * @param ns mongodb namespace\n * @param command mongodb internal representation of a command\n */\n private _populateV4Attributes(\n span: Span,\n connectionCtx: any,\n ns: MongodbNamespace,\n command?: any,\n operation?: string\n ) {\n let host, port: undefined | string;\n if (connectionCtx) {\n const hostParts =\n typeof connectionCtx.address === 'string'\n ? connectionCtx.address.split(':')\n : '';\n if (hostParts.length === 2) {\n host = hostParts[0];\n port = hostParts[1];\n }\n }\n // capture parameters within the query as well if enhancedDatabaseReporting is enabled.\n let commandObj: Record<string, unknown>;\n if (command?.documents && command.documents[0]) {\n commandObj = command.documents[0];\n } else if (command?.cursors) {\n commandObj = command.cursors;\n } else {\n commandObj = command;\n }\n\n this._addAllSpanAttributes(\n span,\n ns.db,\n ns.collection,\n host,\n port,\n commandObj,\n operation\n );\n }\n\n /**\n * Populate span's attributes by fetching related metadata from the context\n * @param span span to add attributes to\n * @param ns mongodb namespace\n * @param topology mongodb internal representation of the network topology\n * @param command mongodb internal representation of a command\n */\n private _populateV3Attributes(\n span: Span,\n ns: string,\n topology: MongoInternalTopology,\n command?: MongoInternalCommand,\n operation?: string | undefined\n ) {\n // add network attributes to determine the remote server\n let host: undefined | string;\n let port: undefined | string;\n if (topology && topology.s) {\n host = topology.s.options?.host ?? topology.s.host;\n port = (topology.s.options?.port ?? topology.s.port)?.toString();\n if (host == null || port == null) {\n const address = topology.description?.address;\n if (address) {\n const addressSegments = address.split(':');\n host = addressSegments[0];\n port = addressSegments[1];\n }\n }\n }\n\n // The namespace is a combination of the database name and the name of the\n // collection or index, like so: [database-name].[collection-or-index-name].\n // It could be a string or an instance of MongoDBNamespace, as such we\n // always coerce to a string to extract db and collection.\n const [dbName, dbCollection] = ns.toString().split('.');\n // capture parameters within the query as well if enhancedDatabaseReporting is enabled.\n const commandObj = command?.query ?? command?.q ?? command;\n\n this._addAllSpanAttributes(\n span,\n dbName,\n dbCollection,\n host,\n port,\n commandObj,\n operation\n );\n }\n\n private _addAllSpanAttributes(\n span: Span,\n dbName?: string,\n dbCollection?: string,\n host?: undefined | string,\n port?: undefined | string,\n commandObj?: any,\n operation?: string | undefined\n ) {\n // add database related attributes\n span.setAttributes({\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_MONGODB,\n [SEMATTRS_DB_NAME]: dbName,\n [SEMATTRS_DB_MONGODB_COLLECTION]: dbCollection,\n [SEMATTRS_DB_OPERATION]: operation,\n [SEMATTRS_DB_CONNECTION_STRING]: `mongodb://${host}:${port}/${dbName}`,\n });\n\n if (host && port) {\n span.setAttribute(SEMATTRS_NET_PEER_NAME, host);\n const portNumber = parseInt(port, 10);\n if (!isNaN(portNumber)) {\n span.setAttribute(SEMATTRS_NET_PEER_PORT, portNumber);\n }\n }\n if (!commandObj) return;\n const dbStatementSerializer =\n typeof this._config.dbStatementSerializer === 'function'\n ? this._config.dbStatementSerializer\n : this._defaultDbStatementSerializer.bind(this);\n\n safeExecuteInTheMiddle(\n () => {\n const query = dbStatementSerializer(commandObj);\n span.setAttribute(SEMATTRS_DB_STATEMENT, query);\n },\n err => {\n if (err) {\n this._diag.error('Error running dbStatementSerializer hook', err);\n }\n },\n true\n );\n }\n\n private _defaultDbStatementSerializer(commandObj: Record<string, unknown>) {\n const enhancedDbReporting = !!this._config?.enhancedDatabaseReporting;\n const resultObj = enhancedDbReporting\n ? commandObj\n : this._scrubStatement(commandObj);\n return JSON.stringify(resultObj);\n }\n\n private _scrubStatement(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(element => this._scrubStatement(element));\n }\n\n if (typeof value === 'object' && value !== null) {\n return Object.fromEntries(\n Object.entries(value).map(([key, element]) => [\n key,\n this._scrubStatement(element),\n ])\n );\n }\n\n // A value like string or number, possible contains PII, scrub it\n return '?';\n }\n\n /**\n * Triggers the response hook in case it is defined.\n * @param span The span to add the results to.\n * @param result The command result\n */\n private _handleExecutionResult(span: Span, result: CommandResult) {\n const config: MongoDBInstrumentationConfig = this.getConfig();\n if (typeof config.responseHook === 'function') {\n safeExecuteInTheMiddle(\n () => {\n config.responseHook!(span, { data: result });\n },\n err => {\n if (err) {\n this._diag.error('Error running response hook', err);\n }\n },\n true\n );\n }\n }\n\n /**\n * Ends a created span.\n * @param span The created span to end.\n * @param resultHandler A callback function.\n * @param connectionId: The connection ID of the Command response.\n */\n private _patchEnd(\n span: Span | undefined,\n resultHandler: Function,\n connectionId?: number,\n commandType?: string\n ): Function {\n // mongodb is using \"tick\" when calling a callback, this way the context\n // in final callback (resultHandler) is lost\n const activeContext = context.active();\n const instrumentation = this;\n return function patchedEnd(this: {}, ...args: unknown[]) {\n const error = args[0];\n if (span) {\n if (error instanceof Error) {\n span?.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n } else {\n const result = args[1] as CommandResult;\n instrumentation._handleExecutionResult(span, result);\n }\n span.end();\n }\n\n return context.with(activeContext, () => {\n if (commandType === 'endSessions') {\n instrumentation._connectionsUsage.add(-1, {\n state: 'idle',\n 'pool.name': instrumentation._poolName,\n });\n }\n return resultHandler.apply(this, args);\n });\n };\n }\n private setPoolName(options: any) {\n const host = options.hostAddress?.host;\n const port = options.hostAddress?.port;\n const database = options.dbName;\n const poolName = `mongodb://${host}:${port}/${database}`;\n this._poolName = poolName;\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 { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { Span } from '@opentelemetry/api';\n\nexport interface MongoDBInstrumentationExecutionResponseHook {\n (span: Span, responseInfo: MongoResponseHookInformation): void;\n}\n\n/**\n * Function that can be used to serialize db.statement tag\n * @param cmd - MongoDB command object\n *\n * @returns serialized string that will be used as the db.statement attribute.\n */\nexport type DbStatementSerializer = (cmd: Record<string, unknown>) => string;\n\nexport interface MongoDBInstrumentationConfig extends InstrumentationConfig {\n /**\n * If true, additional information about query parameters and\n * results will be attached (as `attributes`) to spans representing\n * database operations.\n */\n enhancedDatabaseReporting?: boolean;\n\n /**\n * Hook that allows adding custom span attributes based on the data\n * returned from MongoDB actions.\n *\n * @default undefined\n */\n responseHook?: MongoDBInstrumentationExecutionResponseHook;\n\n /**\n * Custom serializer function for the db.statement tag\n */\n dbStatementSerializer?: DbStatementSerializer;\n}\n\nexport interface MongoResponseHookInformation {\n data: CommandResult;\n}\n\n// https://github.com/mongodb/node-mongodb-native/blob/3.6/lib/core/connection/command_result.js\nexport type CommandResult = {\n result?: unknown;\n connection?: unknown;\n message?: unknown;\n};\n\nexport enum MongodbCommandType {\n CREATE_INDEXES = 'createIndexes',\n FIND_AND_MODIFY = 'findAndModify',\n IS_MASTER = 'isMaster',\n COUNT = 'count',\n UNKNOWN = 'unknown',\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 './instrumentation';\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 */\nimport { Attributes, SpanStatusCode, diag, Span } from '@opentelemetry/api';\nimport type { Collection } from 'mongoose';\nimport { MongooseResponseCustomAttributesFunction } from './types';\nimport { safeExecuteInTheMiddle } from '@opentelemetry/instrumentation';\nimport {\n SEMATTRS_DB_MONGODB_COLLECTION,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_USER,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n} from '@opentelemetry/semantic-conventions';\n\nexport function getAttributesFromCollection(\n collection: Collection\n): Attributes {\n return {\n [SEMATTRS_DB_MONGODB_COLLECTION]: collection.name,\n [SEMATTRS_DB_NAME]: collection.conn.name,\n [SEMATTRS_DB_USER]: collection.conn.user,\n [SEMATTRS_NET_PEER_NAME]: collection.conn.host,\n [SEMATTRS_NET_PEER_PORT]: collection.conn.port,\n };\n}\n\nfunction setErrorStatus(span: Span, error: any = {}) {\n span.recordException(error);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `${error.message} ${\n error.code ? `\\nMongoose Error Code: ${error.code}` : ''\n }`,\n });\n}\n\nfunction applyResponseHook(\n span: Span,\n response: any,\n responseHook?: MongooseResponseCustomAttributesFunction,\n moduleVersion: string | undefined = undefined\n) {\n if (!responseHook) {\n return;\n }\n\n safeExecuteInTheMiddle(\n () => responseHook(span, { moduleVersion, response }),\n e => {\n if (e) {\n diag.error('mongoose instrumentation: responseHook error', e);\n }\n },\n true\n );\n}\n\nexport function handlePromiseResponse(\n execResponse: any,\n span: Span,\n responseHook?: MongooseResponseCustomAttributesFunction,\n moduleVersion: string | undefined = undefined\n): any {\n if (!(execResponse instanceof Promise)) {\n applyResponseHook(span, execResponse, responseHook, moduleVersion);\n span.end();\n return execResponse;\n }\n\n return execResponse\n .then(response => {\n applyResponseHook(span, response, responseHook, moduleVersion);\n return response;\n })\n .catch(err => {\n setErrorStatus(span, err);\n throw err;\n })\n .finally(() => span.end());\n}\n\nexport function handleCallbackResponse(\n callback: Function,\n exec: Function,\n originalThis: any,\n span: Span,\n args: IArguments,\n responseHook?: MongooseResponseCustomAttributesFunction,\n moduleVersion: string | undefined = undefined\n) {\n let callbackArgumentIndex = 0;\n if (args.length === 2) {\n callbackArgumentIndex = 1;\n }\n\n args[callbackArgumentIndex] = (err: Error, response: any): any => {\n err\n ? setErrorStatus(span, err)\n : applyResponseHook(span, response, responseHook, moduleVersion);\n\n span.end();\n return callback!(err, response);\n };\n\n return exec.apply(originalThis, args);\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.40.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-mongoose';\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 { context, Span, trace, Attributes, SpanKind } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport type * as mongoose from 'mongoose';\nimport { MongooseInstrumentationConfig, SerializerPayload } from './types';\nimport {\n handleCallbackResponse,\n handlePromiseResponse,\n getAttributesFromCollection,\n} from './utils';\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n} from '@opentelemetry/instrumentation';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n SEMATTRS_DB_OPERATION,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\n\nconst contextCaptureFunctions = [\n 'remove',\n 'deleteOne',\n 'deleteMany',\n 'find',\n 'findOne',\n 'estimatedDocumentCount',\n 'countDocuments',\n 'count',\n 'distinct',\n 'where',\n '$where',\n 'findOneAndUpdate',\n 'findOneAndDelete',\n 'findOneAndReplace',\n 'findOneAndRemove',\n];\n\n// when mongoose functions are called, we store the original call context\n// and then set it as the parent for the spans created by Query/Aggregate exec()\n// calls. this bypass the unlinked spans issue on thenables await operations.\nexport const _STORED_PARENT_SPAN: unique symbol = Symbol('stored-parent-span');\n\nexport class MongooseInstrumentation extends InstrumentationBase {\n protected override _config!: MongooseInstrumentationConfig;\n\n constructor(config: MongooseInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override setConfig(config: MongooseInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n protected init(): InstrumentationModuleDefinition {\n const module = new InstrumentationNodeModuleDefinition(\n 'mongoose',\n ['>=5.9.7 <7'],\n this.patch.bind(this),\n this.unpatch.bind(this)\n );\n return module;\n }\n\n private patch(\n moduleExports: typeof mongoose,\n moduleVersion: string | undefined\n ) {\n this._wrap(\n moduleExports.Model.prototype,\n 'save',\n this.patchOnModelMethods('save', moduleVersion)\n );\n // mongoose applies this code on module require:\n // Model.prototype.$save = Model.prototype.save;\n // which captures the save function before it is patched.\n // so we need to apply the same logic after instrumenting the save function.\n moduleExports.Model.prototype.$save = moduleExports.Model.prototype.save;\n\n this._wrap(\n moduleExports.Model.prototype,\n 'remove',\n this.patchOnModelMethods('remove', moduleVersion)\n );\n this._wrap(\n moduleExports.Query.prototype,\n 'exec',\n this.patchQueryExec(moduleVersion)\n );\n this._wrap(\n moduleExports.Aggregate.prototype,\n 'exec',\n this.patchAggregateExec(moduleVersion)\n );\n\n contextCaptureFunctions.forEach((funcName: string) => {\n this._wrap(\n moduleExports.Query.prototype,\n funcName as any,\n this.patchAndCaptureSpanContext(funcName)\n );\n });\n this._wrap(moduleExports.Model, 'aggregate', this.patchModelAggregate());\n\n return moduleExports;\n }\n\n private unpatch(moduleExports: typeof mongoose): void {\n this._unwrap(moduleExports.Model.prototype, 'save');\n // revert the patch for $save which we applied by aliasing it to patched `save`\n moduleExports.Model.prototype.$save = moduleExports.Model.prototype.save;\n this._unwrap(moduleExports.Model.prototype, 'remove');\n this._unwrap(moduleExports.Query.prototype, 'exec');\n this._unwrap(moduleExports.Aggregate.prototype, 'exec');\n\n contextCaptureFunctions.forEach((funcName: string) => {\n this._unwrap(moduleExports.Query.prototype, funcName as any);\n });\n this._unwrap(moduleExports.Model, 'aggregate');\n }\n\n private patchAggregateExec(moduleVersion: string | undefined) {\n const self = this;\n return (originalAggregate: Function) => {\n return function exec(this: any, callback?: Function) {\n if (\n self._config.requireParentSpan &&\n trace.getSpan(context.active()) === undefined\n ) {\n return originalAggregate.apply(this, arguments);\n }\n\n const parentSpan = this[_STORED_PARENT_SPAN];\n const attributes: Attributes = {};\n if (self._config.dbStatementSerializer) {\n attributes[SEMATTRS_DB_STATEMENT] =\n self._config.dbStatementSerializer('aggregate', {\n options: this.options,\n aggregatePipeline: this._pipeline,\n });\n }\n\n const span = self._startSpan(\n this._model.collection,\n this._model?.modelName,\n 'aggregate',\n attributes,\n parentSpan\n );\n\n return self._handleResponse(\n span,\n originalAggregate,\n this,\n arguments,\n callback,\n moduleVersion\n );\n };\n };\n }\n\n private patchQueryExec(moduleVersion: string | undefined) {\n const self = this;\n return (originalExec: Function) => {\n return function exec(this: any, callback?: Function) {\n if (\n self._config.requireParentSpan &&\n trace.getSpan(context.active()) === undefined\n ) {\n return originalExec.apply(this, arguments);\n }\n\n const parentSpan = this[_STORED_PARENT_SPAN];\n const attributes: Attributes = {};\n if (self._config.dbStatementSerializer) {\n attributes[SEMATTRS_DB_STATEMENT] =\n self._config.dbStatementSerializer(this.op, {\n condition: this._conditions,\n updates: this._update,\n options: this.options,\n fields: this._fields,\n });\n }\n const span = self._startSpan(\n this.mongooseCollection,\n this.model.modelName,\n this.op,\n attributes,\n parentSpan\n );\n\n return self._handleResponse(\n span,\n originalExec,\n this,\n arguments,\n callback,\n moduleVersion\n );\n };\n };\n }\n\n private patchOnModelMethods(op: string, moduleVersion: string | undefined) {\n const self = this;\n return (originalOnModelFunction: Function) => {\n return function method(this: any, options?: any, callback?: Function) {\n if (\n self._config.requireParentSpan &&\n trace.getSpan(context.active()) === undefined\n ) {\n return originalOnModelFunction.apply(this, arguments);\n }\n\n const serializePayload: SerializerPayload = { document: this };\n if (options && !(options instanceof Function)) {\n serializePayload.options = options;\n }\n const attributes: Attributes = {};\n if (self._config.dbStatementSerializer) {\n attributes[SEMATTRS_DB_STATEMENT] =\n self._config.dbStatementSerializer(op, serializePayload);\n }\n const span = self._startSpan(\n this.constructor.collection,\n this.constructor.modelName,\n op,\n attributes\n );\n\n if (options instanceof Function) {\n callback = options;\n options = undefined;\n }\n\n return self._handleResponse(\n span,\n originalOnModelFunction,\n this,\n arguments,\n callback,\n moduleVersion\n );\n };\n };\n }\n\n // we want to capture the otel span on the object which is calling exec.\n // in the special case of aggregate, we need have no function to path\n // on the Aggregate object to capture the context on, so we patch\n // the aggregate of Model, and set the context on the Aggregate object\n private patchModelAggregate() {\n const self = this;\n return (original: Function) => {\n return function captureSpanContext(this: any) {\n const currentSpan = trace.getSpan(context.active());\n const aggregate = self._callOriginalFunction(() =>\n original.apply(this, arguments)\n );\n if (aggregate) aggregate[_STORED_PARENT_SPAN] = currentSpan;\n return aggregate;\n };\n };\n }\n\n private patchAndCaptureSpanContext(funcName: string) {\n const self = this;\n return (original: Function) => {\n return function captureSpanContext(this: any) {\n this[_STORED_PARENT_SPAN] = trace.getSpan(context.active());\n return self._callOriginalFunction(() =>\n original.apply(this, arguments)\n );\n };\n };\n }\n\n private _startSpan(\n collection: mongoose.Collection,\n modelName: string,\n operation: string,\n attributes: Attributes,\n parentSpan?: Span\n ): Span {\n return this.tracer.startSpan(\n `mongoose.${modelName}.${operation}`,\n {\n kind: SpanKind.CLIENT,\n attributes: {\n ...attributes,\n ...getAttributesFromCollection(collection),\n [SEMATTRS_DB_OPERATION]: operation,\n [SEMATTRS_DB_SYSTEM]: 'mongoose',\n },\n },\n parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined\n );\n }\n\n private _handleResponse(\n span: Span,\n exec: Function,\n originalThis: any,\n args: IArguments,\n callback?: Function,\n moduleVersion: string | undefined = undefined\n ) {\n const self = this;\n if (callback instanceof Function) {\n return self._callOriginalFunction(() =>\n handleCallbackResponse(\n callback,\n exec,\n originalThis,\n span,\n args,\n self._config.responseHook,\n moduleVersion\n )\n );\n } else {\n const response = self._callOriginalFunction(() =>\n exec.apply(originalThis, args)\n );\n return handlePromiseResponse(\n response,\n span,\n self._config.responseHook,\n moduleVersion\n );\n }\n }\n\n private _callOriginalFunction<T>(originalFunction: (...args: any[]) => T): T {\n if (this._config?.suppressInternalInstrumentation) {\n return context.with(suppressTracing(context.active()), originalFunction);\n } else {\n return originalFunction();\n }\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","/*\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 './mongoose';\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// Mysql specific attributes not covered by semantic conventions\nexport enum AttributeNames {\n MYSQL_VALUES = 'db.mysql.values',\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 { Attributes } from '@opentelemetry/api';\nimport {\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_USER,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n} from '@opentelemetry/semantic-conventions';\nimport type {\n ConnectionConfig,\n PoolActualConfig,\n Query,\n QueryOptions,\n} from 'mysql';\nimport type * as mysqlTypes from 'mysql';\n\n/**\n * Get an Attributes map from a mysql connection config object\n *\n * @param config ConnectionConfig\n */\nexport function getConnectionAttributes(\n config: ConnectionConfig | PoolActualConfig\n): Attributes {\n const { host, port, database, user } = getConfig(config);\n const portNumber = parseInt(port, 10);\n if (!isNaN(portNumber)) {\n return {\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_NET_PEER_PORT]: portNumber,\n [SEMATTRS_DB_CONNECTION_STRING]: getJDBCString(host, port, database),\n [SEMATTRS_DB_NAME]: database,\n [SEMATTRS_DB_USER]: user,\n };\n }\n return {\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_DB_CONNECTION_STRING]: getJDBCString(host, port, database),\n [SEMATTRS_DB_NAME]: database,\n [SEMATTRS_DB_USER]: user,\n };\n}\n\nfunction getConfig(config: any) {\n const { host, port, database, user } =\n (config && config.connectionConfig) || config || {};\n return { host, port, database, user };\n}\n\nfunction getJDBCString(\n host: string | undefined,\n port: number | undefined,\n database: string | undefined\n) {\n let jdbcString = `jdbc:mysql://${host || 'localhost'}`;\n\n if (typeof port === 'number') {\n jdbcString += `:${port}`;\n }\n\n if (typeof database === 'string') {\n jdbcString += `/${database}`;\n }\n\n return jdbcString;\n}\n\n/**\n * @returns the database statement being executed.\n */\nexport function getDbStatement(query: string | Query | QueryOptions): string {\n if (typeof query === 'string') {\n return query;\n } else {\n return query.sql;\n }\n}\n\nexport function getDbValues(\n query: string | Query | QueryOptions,\n values?: any[]\n): string {\n if (typeof query === 'string') {\n return arrayStringifyHelper(values);\n } else {\n // According to https://github.com/mysqljs/mysql#performing-queries\n // The values argument will override the values in the option object.\n return arrayStringifyHelper(values || query.values);\n }\n}\n\n/**\n * The span name SHOULD be set to a low cardinality value\n * representing the statement executed on the database.\n *\n * @returns SQL statement without variable arguments or SQL verb\n */\nexport function getSpanName(query: string | Query | QueryOptions): string {\n if (typeof query === 'object') {\n return query.sql;\n }\n return query.split(' ')[0];\n}\n\nexport function arrayStringifyHelper(arr: Array<unknown> | undefined): string {\n if (arr) return `[${arr.toString()}]`;\n return '';\n}\n\nexport function getPoolName(pool: mysqlTypes.Pool): string {\n const c = pool.config.connectionConfig;\n let poolName = '';\n poolName += c.host ? `host: '${c.host}', ` : '';\n poolName += c.port ? `port: ${c.port}, ` : '';\n poolName += c.database ? `database: '${c.database}', ` : '';\n poolName += c.user ? `user: '${c.user}'` : '';\n if (!c.user) {\n poolName = poolName.substring(0, poolName.length - 2); //omit last comma\n }\n return poolName.trim();\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.40.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-mysql';\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 Context,\n trace,\n Span,\n SpanKind,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n} from '@opentelemetry/instrumentation';\nimport {\n DBSYSTEMVALUES_MYSQL,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport type * as mysqlTypes from 'mysql';\nimport { AttributeNames } from './AttributeNames';\nimport { MySQLInstrumentationConfig } from './types';\nimport {\n getConnectionAttributes,\n getDbStatement,\n getDbValues,\n getSpanName,\n getPoolName,\n} from './utils';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { UpDownCounter, MeterProvider } from '@opentelemetry/api';\n\ntype getConnectionCallbackType = (\n err: mysqlTypes.MysqlError,\n connection: mysqlTypes.PoolConnection\n) => void;\n\nexport class MySQLInstrumentation extends InstrumentationBase {\n static readonly COMMON_ATTRIBUTES = {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_MYSQL,\n };\n private _connectionsUsage!: UpDownCounter;\n\n constructor(config: MySQLInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n this._setMetricInstruments();\n }\n\n override setMeterProvider(meterProvider: MeterProvider) {\n super.setMeterProvider(meterProvider);\n this._setMetricInstruments();\n }\n\n private _setMetricInstruments() {\n this._connectionsUsage = this.meter.createUpDownCounter(\n 'db.client.connections.usage', //TODO:: use semantic convention\n {\n description:\n 'The number of connections that are currently in state described by the state attribute.',\n unit: '{connection}',\n }\n );\n }\n\n protected init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'mysql',\n ['>=2.0.0 <3'],\n (moduleExports: typeof mysqlTypes) => {\n if (isWrapped(moduleExports.createConnection)) {\n this._unwrap(moduleExports, 'createConnection');\n }\n this._wrap(\n moduleExports,\n 'createConnection',\n this._patchCreateConnection() as any\n );\n\n if (isWrapped(moduleExports.createPool)) {\n this._unwrap(moduleExports, 'createPool');\n }\n this._wrap(\n moduleExports,\n 'createPool',\n this._patchCreatePool() as any\n );\n\n if (isWrapped(moduleExports.createPoolCluster)) {\n this._unwrap(moduleExports, 'createPoolCluster');\n }\n this._wrap(\n moduleExports,\n 'createPoolCluster',\n this._patchCreatePoolCluster() as any\n );\n\n return moduleExports;\n },\n (moduleExports: typeof mysqlTypes) => {\n if (moduleExports === undefined) return;\n this._unwrap(moduleExports, 'createConnection');\n this._unwrap(moduleExports, 'createPool');\n this._unwrap(moduleExports, 'createPoolCluster');\n }\n ),\n ];\n }\n\n // global export function\n private _patchCreateConnection() {\n return (originalCreateConnection: Function) => {\n const thisPlugin = this;\n\n return function createConnection(\n _connectionUri: string | mysqlTypes.ConnectionConfig\n ) {\n const originalResult = originalCreateConnection(...arguments);\n\n // This is unwrapped on next call after unpatch\n thisPlugin._wrap(\n originalResult,\n 'query',\n thisPlugin._patchQuery(originalResult) as any\n );\n\n return originalResult;\n };\n };\n }\n\n // global export function\n private _patchCreatePool() {\n return (originalCreatePool: Function) => {\n const thisPlugin = this;\n return function createPool(_config: string | mysqlTypes.PoolConfig) {\n const pool = originalCreatePool(...arguments);\n\n thisPlugin._wrap(pool, 'query', thisPlugin._patchQuery(pool));\n thisPlugin._wrap(\n pool,\n 'getConnection',\n thisPlugin._patchGetConnection(pool)\n );\n thisPlugin._wrap(pool, 'end', thisPlugin._patchPoolEnd(pool));\n thisPlugin._setPoolcallbacks(pool, thisPlugin, '');\n\n return pool;\n };\n };\n }\n private _patchPoolEnd(pool: any) {\n return (originalPoolEnd: Function) => {\n const thisPlugin = this;\n return function end(callback?: unknown) {\n const nAll = (pool as any)._allConnections.length;\n const nFree = (pool as any)._freeConnections.length;\n const nUsed = nAll - nFree;\n const poolName = getPoolName(pool);\n thisPlugin._connectionsUsage.add(-nUsed, {\n state: 'used',\n name: poolName,\n });\n thisPlugin._connectionsUsage.add(-nFree, {\n state: 'idle',\n name: poolName,\n });\n originalPoolEnd.apply(pool, arguments);\n };\n };\n }\n\n // global export function\n private _patchCreatePoolCluster() {\n return (originalCreatePoolCluster: Function) => {\n const thisPlugin = this;\n return function createPool(_config: string | mysqlTypes.PoolConfig) {\n const cluster = originalCreatePoolCluster(...arguments);\n\n // This is unwrapped on next call after unpatch\n thisPlugin._wrap(\n cluster,\n 'getConnection',\n thisPlugin._patchGetConnection(cluster)\n );\n thisPlugin._wrap(cluster, 'add', thisPlugin._patchAdd(cluster));\n\n return cluster;\n };\n };\n }\n private _patchAdd(cluster: mysqlTypes.PoolCluster) {\n return (originalAdd: Function) => {\n const thisPlugin = this;\n return function add(id: string, config: unknown) {\n // Unwrap if unpatch has been called\n if (!thisPlugin['_enabled']) {\n thisPlugin._unwrap(cluster, 'add');\n return originalAdd.apply(cluster, arguments);\n }\n originalAdd.apply(cluster, arguments);\n const nodes = cluster['_nodes' as keyof mysqlTypes.PoolCluster] as any;\n if (nodes) {\n const nodeId =\n typeof id === 'object'\n ? 'CLUSTER::' + (cluster as any)._lastId\n : String(id);\n\n const pool = nodes[nodeId].pool;\n thisPlugin._setPoolcallbacks(pool, thisPlugin, id);\n }\n };\n };\n }\n\n // method on cluster or pool\n private _patchGetConnection(pool: mysqlTypes.Pool | mysqlTypes.PoolCluster) {\n return (originalGetConnection: Function) => {\n const thisPlugin = this;\n\n return function getConnection(\n arg1?: unknown,\n arg2?: unknown,\n arg3?: unknown\n ) {\n // Unwrap if unpatch has been called\n if (!thisPlugin['_enabled']) {\n thisPlugin._unwrap(pool, 'getConnection');\n return originalGetConnection.apply(pool, arguments);\n }\n\n if (arguments.length === 1 && typeof arg1 === 'function') {\n const patchFn = thisPlugin._getConnectionCallbackPatchFn(\n arg1 as getConnectionCallbackType\n );\n return originalGetConnection.call(pool, patchFn);\n }\n if (arguments.length === 2 && typeof arg2 === 'function') {\n const patchFn = thisPlugin._getConnectionCallbackPatchFn(\n arg2 as getConnectionCallbackType\n );\n return originalGetConnection.call(pool, arg1, patchFn);\n }\n if (arguments.length === 3 && typeof arg3 === 'function') {\n const patchFn = thisPlugin._getConnectionCallbackPatchFn(\n arg3 as getConnectionCallbackType\n );\n return originalGetConnection.call(pool, arg1, arg2, patchFn);\n }\n\n return originalGetConnection.apply(pool, arguments);\n };\n };\n }\n\n private _getConnectionCallbackPatchFn(cb: getConnectionCallbackType) {\n const thisPlugin = this;\n const activeContext = context.active();\n return function (\n this: any,\n err: mysqlTypes.MysqlError,\n connection: mysqlTypes.PoolConnection\n ) {\n if (connection) {\n // this is the callback passed into a query\n // no need to unwrap\n if (!isWrapped(connection.query)) {\n thisPlugin._wrap(\n connection,\n 'query',\n thisPlugin._patchQuery(connection)\n );\n }\n }\n if (typeof cb === 'function') {\n context.with(activeContext, cb, this, err, connection);\n }\n };\n }\n\n private _patchQuery(connection: mysqlTypes.Connection | mysqlTypes.Pool) {\n return (originalQuery: Function): mysqlTypes.QueryFunction => {\n const thisPlugin = this;\n\n return function query(\n query: string | mysqlTypes.Query | mysqlTypes.QueryOptions,\n _valuesOrCallback?: unknown[] | mysqlTypes.queryCallback,\n _callback?: mysqlTypes.queryCallback\n ) {\n if (!thisPlugin['_enabled']) {\n thisPlugin._unwrap(connection, 'query');\n return originalQuery.apply(connection, arguments);\n }\n\n const span = thisPlugin.tracer.startSpan(getSpanName(query), {\n kind: SpanKind.CLIENT,\n attributes: {\n ...MySQLInstrumentation.COMMON_ATTRIBUTES,\n ...getConnectionAttributes(connection.config),\n },\n });\n\n span.setAttribute(SEMATTRS_DB_STATEMENT, getDbStatement(query));\n\n const instrumentationConfig: MySQLInstrumentationConfig =\n thisPlugin.getConfig();\n\n if (instrumentationConfig.enhancedDatabaseReporting) {\n let values;\n\n if (Array.isArray(_valuesOrCallback)) {\n values = _valuesOrCallback;\n } else if (arguments[2]) {\n values = [_valuesOrCallback];\n }\n\n span.setAttribute(\n AttributeNames.MYSQL_VALUES,\n getDbValues(query, values)\n );\n }\n\n const cbIndex = Array.from(arguments).findIndex(\n arg => typeof arg === 'function'\n );\n\n const parentContext = context.active();\n\n if (cbIndex === -1) {\n const streamableQuery: mysqlTypes.Query = context.with(\n trace.setSpan(context.active(), span),\n () => {\n return originalQuery.apply(connection, arguments);\n }\n );\n context.bind(parentContext, streamableQuery);\n\n return streamableQuery\n .on('error', err =>\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n })\n )\n .on('end', () => {\n span.end();\n });\n } else {\n thisPlugin._wrap(\n arguments,\n cbIndex,\n thisPlugin._patchCallbackQuery(span, parentContext)\n );\n\n return context.with(trace.setSpan(context.active(), span), () => {\n return originalQuery.apply(connection, arguments);\n });\n }\n };\n };\n }\n\n private _patchCallbackQuery(span: Span, parentContext: Context) {\n return (originalCallback: Function) => {\n return function (\n err: mysqlTypes.MysqlError | null,\n results?: any,\n fields?: mysqlTypes.FieldInfo[]\n ) {\n if (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n }\n span.end();\n return context.with(parentContext, () =>\n originalCallback(...arguments)\n );\n };\n };\n }\n private _setPoolcallbacks(\n pool: mysqlTypes.Pool,\n thisPlugin: MySQLInstrumentation,\n id: string\n ) {\n //TODO:: use semantic convention\n const poolName = id || getPoolName(pool);\n\n pool.on('connection', connection => {\n thisPlugin._connectionsUsage.add(1, {\n state: 'idle',\n name: poolName,\n });\n });\n\n pool.on('acquire', connection => {\n thisPlugin._connectionsUsage.add(-1, {\n state: 'idle',\n name: poolName,\n });\n thisPlugin._connectionsUsage.add(1, {\n state: 'used',\n name: poolName,\n });\n });\n\n pool.on('release', connection => {\n thisPlugin._connectionsUsage.add(-1, {\n state: 'used',\n name: poolName,\n });\n thisPlugin._connectionsUsage.add(1, {\n state: 'idle',\n name: poolName,\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 './instrumentation';\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 {\n trace,\n Span,\n ROOT_CONTEXT,\n defaultTextMapSetter,\n} from '@opentelemetry/api';\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\n\n// NOTE: This function currently is returning false-positives\n// in cases where comment characters appear in string literals\n// (\"SELECT '-- not a comment';\" would return true, although has no comment)\nfunction hasValidSqlComment(query: string): boolean {\n const indexOpeningDashDashComment = query.indexOf('--');\n if (indexOpeningDashDashComment >= 0) {\n return true;\n }\n\n const indexOpeningSlashComment = query.indexOf('/*');\n if (indexOpeningSlashComment < 0) {\n return false;\n }\n\n const indexClosingSlashComment = query.indexOf('*/');\n return indexOpeningDashDashComment < indexClosingSlashComment;\n}\n\n// sqlcommenter specification (https://google.github.io/sqlcommenter/spec/#value-serialization)\n// expects us to URL encode based on the RFC 3986 spec (https://en.wikipedia.org/wiki/Percent-encoding),\n// but encodeURIComponent does not handle some characters correctly (! ' ( ) *),\n// which means we need special handling for this\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\nfunction fixedEncodeURIComponent(str: string) {\n return encodeURIComponent(str).replace(\n /[!'()*]/g,\n c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n );\n}\n\nexport function addSqlCommenterComment(span: Span, query: string): string {\n if (typeof query !== 'string' || query.length === 0) {\n return query;\n }\n\n // As per sqlcommenter spec we shall not add a comment if there already is a comment\n // in the query\n if (hasValidSqlComment(query)) {\n return query;\n }\n\n const propagator = new W3CTraceContextPropagator();\n const headers: { [key: string]: string } = {};\n propagator.inject(\n trace.setSpan(ROOT_CONTEXT, span),\n headers,\n defaultTextMapSetter\n );\n\n // sqlcommenter spec requires keys in the comment to be sorted lexicographically\n const sortedKeys = Object.keys(headers).sort();\n\n if (sortedKeys.length === 0) {\n return query;\n }\n\n const commentString = sortedKeys\n .map(key => {\n const encodedValue = fixedEncodeURIComponent(headers[key]);\n return `${key}='${encodedValue}'`;\n })\n .join(',');\n\n return `${query} /*${commentString}*/`;\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 { Attributes } from '@opentelemetry/api';\nimport {\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_USER,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n} from '@opentelemetry/semantic-conventions';\n\n/*\n Following types declare an expectation on mysql2 types and define a subset we\n use in the instrumentation of the types actually defined in mysql2 package\n\n We need to import them here so that the installing party of the instrumentation\n doesn't have to absolutely install the mysql2 package as well - specially\n important for auto-loaders and meta-packages.\n*/\ninterface QueryOptions {\n sql: string;\n values?: any | any[] | { [param: string]: any };\n}\n\ninterface Query {\n sql: string;\n}\n\ninterface Config {\n host?: string;\n port?: number;\n database?: string;\n user?: string;\n connectionConfig?: Config;\n}\n/**\n * Get an Attributes map from a mysql connection config object\n *\n * @param config ConnectionConfig\n */\nexport function getConnectionAttributes(config: Config): Attributes {\n const { host, port, database, user } = getConfig(config);\n const portNumber = parseInt(port, 10);\n if (!isNaN(portNumber)) {\n return {\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_NET_PEER_PORT]: portNumber,\n [SEMATTRS_DB_CONNECTION_STRING]: getJDBCString(host, port, database),\n [SEMATTRS_DB_NAME]: database,\n [SEMATTRS_DB_USER]: user,\n };\n }\n return {\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_DB_CONNECTION_STRING]: getJDBCString(host, port, database),\n [SEMATTRS_DB_NAME]: database,\n [SEMATTRS_DB_USER]: user,\n };\n}\n\nfunction getConfig(config: any) {\n const { host, port, database, user } =\n (config && config.connectionConfig) || config || {};\n return { host, port, database, user };\n}\n\nfunction getJDBCString(\n host: string | undefined,\n port: number | undefined,\n database: string | undefined\n) {\n let jdbcString = `jdbc:mysql://${host || 'localhost'}`;\n\n if (typeof port === 'number') {\n jdbcString += `:${port}`;\n }\n\n if (typeof database === 'string') {\n jdbcString += `/${database}`;\n }\n\n return jdbcString;\n}\n\n/**\n * Conjures up the value for the db.statement attribute by formatting a SQL query.\n *\n * @returns the database statement being executed.\n */\nexport function getDbStatement(\n query: string | Query | QueryOptions,\n format: (\n sql: string,\n values: any[],\n stringifyObjects?: boolean,\n timeZone?: string\n ) => string,\n values?: any[]\n): string {\n if (typeof query === 'string') {\n return values ? format(query, values) : query;\n } else {\n // According to https://github.com/mysqljs/mysql#performing-queries\n // The values argument will override the values in the option object.\n return values || (query as QueryOptions).values\n ? format(query.sql, values || (query as QueryOptions).values)\n : query.sql;\n }\n}\n\n/**\n * The span name SHOULD be set to a low cardinality value\n * representing the statement executed on the database.\n *\n * @returns SQL statement without variable arguments or SQL verb\n */\nexport function getSpanName(query: string | Query | QueryOptions): string {\n const rawQuery = typeof query === 'object' ? query.sql : query;\n // Extract the SQL verb\n return rawQuery?.split(' ')?.[0];\n}\n\nexport const once = (fn: Function) => {\n let called = false;\n return (...args: unknown[]) => {\n if (called) return;\n called = true;\n return fn(...args);\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.40.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-mysql2';\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 InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport {\n DBSYSTEMVALUES_MYSQL,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n} from '@opentelemetry/semantic-conventions';\nimport { addSqlCommenterComment } from '@opentelemetry/sql-common';\nimport type * as mysqlTypes from 'mysql2';\nimport { MySQL2InstrumentationConfig } from './types';\nimport {\n getConnectionAttributes,\n getDbStatement,\n getSpanName,\n once,\n} from './utils';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\ntype formatType = typeof mysqlTypes.format;\n\nexport class MySQL2Instrumentation extends InstrumentationBase {\n static readonly COMMON_ATTRIBUTES = {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_MYSQL,\n };\n\n constructor(config: MySQL2InstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n protected init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'mysql2',\n ['>=1.4.2 <4'],\n (moduleExports: any) => {\n const ConnectionPrototype: mysqlTypes.Connection =\n moduleExports.Connection.prototype;\n if (isWrapped(ConnectionPrototype.query)) {\n this._unwrap(ConnectionPrototype, 'query');\n }\n this._wrap(\n ConnectionPrototype,\n 'query',\n this._patchQuery(moduleExports.format, false) as any\n );\n\n if (isWrapped(ConnectionPrototype.execute)) {\n this._unwrap(ConnectionPrototype, 'execute');\n }\n this._wrap(\n ConnectionPrototype,\n 'execute',\n this._patchQuery(moduleExports.format, true) as any\n );\n\n return moduleExports;\n },\n (moduleExports: any) => {\n if (moduleExports === undefined) return;\n const ConnectionPrototype: mysqlTypes.Connection =\n moduleExports.Connection.prototype;\n this._unwrap(ConnectionPrototype, 'query');\n this._unwrap(ConnectionPrototype, 'execute');\n }\n ),\n ];\n }\n\n private _patchQuery(format: formatType, isPrepared: boolean) {\n return (originalQuery: Function): Function => {\n const thisPlugin = this;\n return function query(\n this: mysqlTypes.Connection,\n query: string | mysqlTypes.Query | mysqlTypes.QueryOptions,\n _valuesOrCallback?: unknown[] | Function,\n _callback?: Function\n ) {\n const thisPluginConfig: MySQL2InstrumentationConfig =\n thisPlugin._config;\n\n let values;\n if (Array.isArray(_valuesOrCallback)) {\n values = _valuesOrCallback;\n } else if (arguments[2]) {\n values = [_valuesOrCallback];\n }\n\n const span = thisPlugin.tracer.startSpan(getSpanName(query), {\n kind: api.SpanKind.CLIENT,\n attributes: {\n ...MySQL2Instrumentation.COMMON_ATTRIBUTES,\n ...getConnectionAttributes(this.config),\n [SEMATTRS_DB_STATEMENT]: getDbStatement(query, format, values),\n },\n });\n\n if (!isPrepared && thisPluginConfig.addSqlCommenterCommentToQueries) {\n arguments[0] = query =\n typeof query === 'string'\n ? addSqlCommenterComment(span, query)\n : Object.assign(query, {\n sql: addSqlCommenterComment(span, query.sql),\n });\n }\n\n const endSpan = once((err?: any, results?: any) => {\n if (err) {\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n } else {\n if (typeof thisPluginConfig.responseHook === 'function') {\n safeExecuteInTheMiddle(\n () => {\n thisPluginConfig.responseHook!(span, {\n queryResults: results,\n });\n },\n err => {\n if (err) {\n thisPlugin._diag.warn('Failed executing responseHook', err);\n }\n },\n true\n );\n }\n }\n\n span.end();\n });\n\n if (arguments.length === 1) {\n if (typeof (query as any).onResult === 'function') {\n thisPlugin._wrap(\n query as any,\n 'onResult',\n thisPlugin._patchCallbackQuery(endSpan)\n );\n }\n\n const streamableQuery: mysqlTypes.Query = originalQuery.apply(\n this,\n arguments\n );\n\n // `end` in mysql behaves similarly to `result` in mysql2.\n streamableQuery\n .once('error', err => {\n endSpan(err);\n })\n .once('result', results => {\n endSpan(undefined, results);\n });\n\n return streamableQuery;\n }\n\n if (typeof arguments[1] === 'function') {\n thisPlugin._wrap(\n arguments,\n 1,\n thisPlugin._patchCallbackQuery(endSpan)\n );\n } else if (typeof arguments[2] === 'function') {\n thisPlugin._wrap(\n arguments,\n 2,\n thisPlugin._patchCallbackQuery(endSpan)\n );\n }\n\n return originalQuery.apply(this, arguments);\n };\n };\n }\n\n private _patchCallbackQuery(endSpan: Function) {\n return (originalCallback: Function) => {\n return function (\n err: mysqlTypes.QueryError | null,\n results?: any,\n fields?: mysqlTypes.FieldPacket[]\n ) {\n endSpan(err, results);\n return originalCallback(...arguments);\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 './instrumentation';\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 { Span, SpanStatusCode } from '@opentelemetry/api';\n\nexport const endSpan = (\n span: Span,\n err: NodeJS.ErrnoException | null | undefined\n) => {\n if (err) {\n span.recordException(err);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n }\n span.end();\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 * List of regexes and the number of arguments that should be serialized for matching commands.\n * For example, HSET should serialize which key and field it's operating on, but not its value.\n * Setting the subset to -1 will serialize all arguments.\n * Commands without a match will have their first argument serialized.\n *\n * Refer to https://redis.io/commands/ for the full list.\n */\nconst serializationSubsets = [\n {\n regex: /^ECHO/i,\n args: 0,\n },\n {\n regex: /^(LPUSH|MSET|PFA|PUBLISH|RPUSH|SADD|SET|SPUBLISH|XADD|ZADD)/i,\n args: 1,\n },\n {\n regex: /^(HSET|HMSET|LSET|LINSERT)/i,\n args: 2,\n },\n {\n regex:\n /^(ACL|BIT|B[LRZ]|CLIENT|CLUSTER|CONFIG|COMMAND|DECR|DEL|EVAL|EX|FUNCTION|GEO|GET|HINCR|HMGET|HSCAN|INCR|L[TRLM]|MEMORY|P[EFISTU]|RPOP|S[CDIMORSU]|XACK|X[CDGILPRT]|Z[CDILMPRS])/i,\n args: -1,\n },\n];\n\nexport type DbStatementSerializer = (\n cmdName: string,\n cmdArgs: Array<string | Buffer | number | any[]>\n) => string;\n\n/**\n * Given the redis command name and arguments, return a combination of the\n * command name + the allowed arguments according to `serializationSubsets`.\n * @param cmdName The redis command name\n * @param cmdArgs The redis command arguments\n * @returns a combination of the command name + args according to `serializationSubsets`.\n */\nexport const defaultDbStatementSerializer: DbStatementSerializer = (\n cmdName,\n cmdArgs\n) => {\n if (Array.isArray(cmdArgs) && cmdArgs.length) {\n const nArgsToSerialize =\n serializationSubsets.find(({ regex }) => {\n return regex.test(cmdName);\n })?.args ?? 0;\n const argsToSerialize =\n nArgsToSerialize >= 0 ? cmdArgs.slice(0, nArgsToSerialize) : cmdArgs;\n if (cmdArgs.length > argsToSerialize.length) {\n argsToSerialize.push(\n `[${cmdArgs.length - nArgsToSerialize} other arguments]`\n );\n }\n return `${cmdName} ${argsToSerialize.join(' ')}`;\n }\n return cmdName;\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.42.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-ioredis';\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, trace, context, SpanKind } from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n} from '@opentelemetry/instrumentation';\nimport { IORedisInstrumentationConfig } from './types';\nimport { IORedisCommand, RedisInterface } from './internal-types';\nimport {\n DBSYSTEMVALUES_REDIS,\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n} from '@opentelemetry/semantic-conventions';\nimport { safeExecuteInTheMiddle } from '@opentelemetry/instrumentation';\nimport { endSpan } from './utils';\nimport { defaultDbStatementSerializer } from '@opentelemetry/redis-common';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\nconst DEFAULT_CONFIG: IORedisInstrumentationConfig = {\n requireParentSpan: true,\n};\n\nexport class IORedisInstrumentation extends InstrumentationBase {\n protected override _config!: IORedisInstrumentationConfig;\n\n constructor(config: IORedisInstrumentationConfig = {}) {\n super(\n PACKAGE_NAME,\n PACKAGE_VERSION,\n Object.assign({}, DEFAULT_CONFIG, config)\n );\n }\n\n init(): InstrumentationNodeModuleDefinition[] {\n return [\n new InstrumentationNodeModuleDefinition(\n 'ioredis',\n ['>=2.0.0 <6'],\n (module, moduleVersion?: string) => {\n const moduleExports =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.prototype.sendCommand)) {\n this._unwrap(moduleExports.prototype, 'sendCommand');\n }\n this._wrap(\n moduleExports.prototype,\n 'sendCommand',\n this._patchSendCommand(moduleVersion)\n );\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n this._wrap(\n moduleExports.prototype,\n 'connect',\n this._patchConnection()\n );\n return module;\n },\n module => {\n if (module === undefined) return;\n const moduleExports =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n this._unwrap(moduleExports.prototype, 'sendCommand');\n this._unwrap(moduleExports.prototype, 'connect');\n }\n ),\n ];\n }\n\n /**\n * Patch send command internal to trace requests\n */\n private _patchSendCommand(moduleVersion?: string) {\n return (original: Function) => {\n return this._traceSendCommand(original, moduleVersion);\n };\n }\n\n private _patchConnection() {\n return (original: Function) => {\n return this._traceConnection(original);\n };\n }\n\n private _traceSendCommand(original: Function, moduleVersion?: string) {\n const instrumentation = this;\n return function (this: RedisInterface, cmd?: IORedisCommand) {\n if (arguments.length < 1 || typeof cmd !== 'object') {\n return original.apply(this, arguments);\n }\n const config =\n instrumentation.getConfig() as IORedisInstrumentationConfig;\n const dbStatementSerializer =\n config?.dbStatementSerializer || defaultDbStatementSerializer;\n\n const hasNoParentSpan = trace.getSpan(context.active()) === undefined;\n if (config?.requireParentSpan === true && hasNoParentSpan) {\n return original.apply(this, arguments);\n }\n\n const span = instrumentation.tracer.startSpan(cmd.name, {\n kind: SpanKind.CLIENT,\n attributes: {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_REDIS,\n [SEMATTRS_DB_STATEMENT]: dbStatementSerializer(cmd.name, cmd.args),\n },\n });\n\n if (config?.requestHook) {\n safeExecuteInTheMiddle(\n () =>\n config?.requestHook!(span, {\n moduleVersion,\n cmdName: cmd.name,\n cmdArgs: cmd.args,\n }),\n e => {\n if (e) {\n diag.error('ioredis instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n const { host, port } = this.options;\n\n span.setAttributes({\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_NET_PEER_PORT]: port,\n [SEMATTRS_DB_CONNECTION_STRING]: `redis://${host}:${port}`,\n });\n\n try {\n const result = original.apply(this, arguments);\n\n const origResolve = cmd.resolve;\n /* eslint-disable @typescript-eslint/no-explicit-any */\n cmd.resolve = function (result: any) {\n safeExecuteInTheMiddle(\n () => config?.responseHook?.(span, cmd.name, cmd.args, result),\n e => {\n if (e) {\n diag.error('ioredis instrumentation: response hook failed', e);\n }\n },\n true\n );\n\n endSpan(span, null);\n origResolve(result);\n };\n\n const origReject = cmd.reject;\n cmd.reject = function (err: Error) {\n endSpan(span, err);\n origReject(err);\n };\n\n return result;\n } catch (error: any) {\n endSpan(span, error);\n throw error;\n }\n };\n }\n\n private _traceConnection(original: Function) {\n const instrumentation = this;\n return function (this: RedisInterface) {\n const config =\n instrumentation.getConfig() as IORedisInstrumentationConfig;\n const hasNoParentSpan = trace.getSpan(context.active()) === undefined;\n if (config?.requireParentSpan === true && hasNoParentSpan) {\n return original.apply(this, arguments);\n }\n\n const span = instrumentation.tracer.startSpan('connect', {\n kind: SpanKind.CLIENT,\n attributes: {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_REDIS,\n [SEMATTRS_DB_STATEMENT]: 'connect',\n },\n });\n const { host, port } = this.options;\n\n span.setAttributes({\n [SEMATTRS_NET_PEER_NAME]: host,\n [SEMATTRS_NET_PEER_PORT]: port,\n [SEMATTRS_DB_CONNECTION_STRING]: `redis://${host}:${port}`,\n });\n try {\n const client = original.apply(this, arguments);\n endSpan(span, null);\n return client;\n } catch (error: any) {\n endSpan(span, error);\n throw error;\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 './instrumentation';\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 */\nimport { Attributes, DiagLogger } from '@opentelemetry/api';\nimport {\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n DBSYSTEMVALUES_REDIS,\n} from '@opentelemetry/semantic-conventions';\n\nexport function getClientAttributes(\n diag: DiagLogger,\n options: any\n): Attributes {\n return {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_REDIS,\n [SEMATTRS_NET_PEER_NAME]: options?.socket?.host,\n [SEMATTRS_NET_PEER_PORT]: options?.socket?.port,\n [SEMATTRS_DB_CONNECTION_STRING]:\n removeCredentialsFromDBConnectionStringAttribute(diag, options?.url),\n };\n}\n\n/**\n * removeCredentialsFromDBConnectionStringAttribute removes basic auth from url and user_pwd from query string\n *\n * Examples:\n * redis://user:pass@localhost:6379/mydb => redis://localhost:6379/mydb\n * redis://localhost:6379?db=mydb&user_pwd=pass => redis://localhost:6379?db=mydb\n */\nfunction removeCredentialsFromDBConnectionStringAttribute(\n diag: DiagLogger,\n url?: unknown\n): string | undefined {\n if (typeof url !== 'string') {\n return;\n }\n\n try {\n const u = new URL(url);\n u.searchParams.delete('user_pwd');\n u.username = '';\n u.password = '';\n return u.href;\n } catch (err) {\n diag.error('failed to sanitize redis connection url', err);\n }\n return;\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.41.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-redis-4';\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 trace,\n context,\n SpanKind,\n Span,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n} from '@opentelemetry/instrumentation';\nimport { getClientAttributes } from './utils';\nimport { defaultDbStatementSerializer } from '@opentelemetry/redis-common';\nimport { RedisInstrumentationConfig } from './types';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { SEMATTRS_DB_STATEMENT } from '@opentelemetry/semantic-conventions';\nimport type { MultiErrorReply } from './internal-types';\n\nconst OTEL_OPEN_SPANS = Symbol(\n 'opentelemetry.instrumentation.redis.open_spans'\n);\nconst MULTI_COMMAND_OPTIONS = Symbol(\n 'opentelemetry.instrumentation.redis.multi_command_options'\n);\n\ninterface MutliCommandInfo {\n span: Span;\n commandName: string;\n commandArgs: Array<string | Buffer>;\n}\n\nconst DEFAULT_CONFIG: RedisInstrumentationConfig = {\n requireParentSpan: false,\n};\n\nexport class RedisInstrumentation extends InstrumentationBase {\n static readonly COMPONENT = 'redis';\n\n protected override _config!: RedisInstrumentationConfig;\n\n constructor(config: RedisInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override setConfig(config: RedisInstrumentationConfig = {}) {\n this._config = Object.assign({}, DEFAULT_CONFIG, config);\n }\n\n protected init() {\n // @node-redis/client is a new package introduced and consumed by 'redis 4.0.x'\n // on redis@4.1.0 it was changed to @redis/client.\n // we will instrument both packages\n return [\n this._getInstrumentationNodeModuleDefinition('@redis/client'),\n this._getInstrumentationNodeModuleDefinition('@node-redis/client'),\n ];\n }\n\n private _getInstrumentationNodeModuleDefinition(\n basePackageName: string\n ): InstrumentationNodeModuleDefinition {\n const commanderModuleFile = new InstrumentationNodeModuleFile(\n `${basePackageName}/dist/lib/commander.js`,\n ['^1.0.0'],\n (moduleExports: any, moduleVersion?: string) => {\n const transformCommandArguments =\n moduleExports.transformCommandArguments;\n if (!transformCommandArguments) {\n this._diag.error(\n 'internal instrumentation error, missing transformCommandArguments function'\n );\n return moduleExports;\n }\n\n // function name and signature changed in redis 4.1.0 from 'extendWithCommands' to 'attachCommands'\n // the matching internal package names starts with 1.0.x (for redis 4.0.x)\n const functionToPatch = moduleVersion?.startsWith('1.0.')\n ? 'extendWithCommands'\n : 'attachCommands';\n // this is the function that extend a redis client with a list of commands.\n // the function patches the commandExecutor to record a span\n if (isWrapped(moduleExports?.[functionToPatch])) {\n this._unwrap(moduleExports, functionToPatch);\n }\n this._wrap(\n moduleExports,\n functionToPatch,\n this._getPatchExtendWithCommands(transformCommandArguments)\n );\n\n return moduleExports;\n },\n (moduleExports: any) => {\n if (isWrapped(moduleExports?.extendWithCommands)) {\n this._unwrap(moduleExports, 'extendWithCommands');\n }\n if (isWrapped(moduleExports?.attachCommands)) {\n this._unwrap(moduleExports, 'attachCommands');\n }\n }\n );\n\n const multiCommanderModule = new InstrumentationNodeModuleFile(\n `${basePackageName}/dist/lib/client/multi-command.js`,\n ['^1.0.0'],\n (moduleExports: any) => {\n const redisClientMultiCommandPrototype =\n moduleExports?.default?.prototype;\n\n if (isWrapped(redisClientMultiCommandPrototype?.exec)) {\n this._unwrap(redisClientMultiCommandPrototype, 'exec');\n }\n this._wrap(\n redisClientMultiCommandPrototype,\n 'exec',\n this._getPatchMultiCommandsExec()\n );\n\n if (isWrapped(redisClientMultiCommandPrototype?.addCommand)) {\n this._unwrap(redisClientMultiCommandPrototype, 'addCommand');\n }\n this._wrap(\n redisClientMultiCommandPrototype,\n 'addCommand',\n this._getPatchMultiCommandsAddCommand()\n );\n\n return moduleExports;\n },\n (moduleExports: any) => {\n const redisClientMultiCommandPrototype =\n moduleExports?.default?.prototype;\n if (isWrapped(redisClientMultiCommandPrototype?.exec)) {\n this._unwrap(redisClientMultiCommandPrototype, 'exec');\n }\n if (isWrapped(redisClientMultiCommandPrototype?.addCommand)) {\n this._unwrap(redisClientMultiCommandPrototype, 'addCommand');\n }\n }\n );\n\n const clientIndexModule = new InstrumentationNodeModuleFile(\n `${basePackageName}/dist/lib/client/index.js`,\n ['^1.0.0'],\n (moduleExports: any) => {\n const redisClientPrototype = moduleExports?.default?.prototype;\n\n // In some @redis/client versions 'multi' is a method. In later\n // versions, as of https://github.com/redis/node-redis/pull/2324,\n // 'MULTI' is a method and 'multi' is a property defined in the\n // constructor that points to 'MULTI', and therefore it will not\n // be defined on the prototype.\n if (redisClientPrototype?.multi) {\n if (isWrapped(redisClientPrototype?.multi)) {\n this._unwrap(redisClientPrototype, 'multi');\n }\n this._wrap(\n redisClientPrototype,\n 'multi',\n this._getPatchRedisClientMulti()\n );\n }\n if (redisClientPrototype?.MULTI) {\n if (isWrapped(redisClientPrototype?.MULTI)) {\n this._unwrap(redisClientPrototype, 'MULTI');\n }\n this._wrap(\n redisClientPrototype,\n 'MULTI',\n this._getPatchRedisClientMulti()\n );\n }\n\n if (isWrapped(redisClientPrototype?.sendCommand)) {\n this._unwrap(redisClientPrototype, 'sendCommand');\n }\n this._wrap(\n redisClientPrototype,\n 'sendCommand',\n this._getPatchRedisClientSendCommand()\n );\n\n this._wrap(\n redisClientPrototype,\n 'connect',\n this._getPatchedClientConnect()\n );\n\n return moduleExports;\n },\n (moduleExports: any) => {\n const redisClientPrototype = moduleExports?.default?.prototype;\n if (isWrapped(redisClientPrototype?.multi)) {\n this._unwrap(redisClientPrototype, 'multi');\n }\n if (isWrapped(redisClientPrototype?.MULTI)) {\n this._unwrap(redisClientPrototype, 'MULTI');\n }\n if (isWrapped(redisClientPrototype?.sendCommand)) {\n this._unwrap(redisClientPrototype, 'sendCommand');\n }\n }\n );\n\n return new InstrumentationNodeModuleDefinition(\n basePackageName,\n ['^1.0.0'],\n (moduleExports: any) => {\n return moduleExports;\n },\n () => {},\n [commanderModuleFile, multiCommanderModule, clientIndexModule]\n );\n }\n\n // serves both for redis 4.0.x where function name is extendWithCommands\n // and redis ^4.1.0 where function name is attachCommands\n private _getPatchExtendWithCommands(transformCommandArguments: Function) {\n const plugin = this;\n return function extendWithCommandsPatchWrapper(original: Function) {\n return function extendWithCommandsPatch(this: any, config: any) {\n if (config?.BaseClass?.name !== 'RedisClient') {\n return original.apply(this, arguments);\n }\n\n const origExecutor = config.executor;\n config.executor = function (\n this: any,\n command: any,\n args: Array<string | Buffer>\n ) {\n const redisCommandArguments = transformCommandArguments(\n command,\n args\n ).args;\n return plugin._traceClientCommand(\n origExecutor,\n this,\n arguments,\n redisCommandArguments\n );\n };\n return original.apply(this, arguments);\n };\n };\n }\n\n private _getPatchMultiCommandsExec() {\n const plugin = this;\n return function execPatchWrapper(original: Function) {\n return function execPatch(this: any) {\n const execRes = original.apply(this, arguments);\n if (typeof execRes?.then !== 'function') {\n plugin._diag.error(\n 'got non promise result when patching RedisClientMultiCommand.exec'\n );\n return execRes;\n }\n\n return execRes\n .then((redisRes: unknown[]) => {\n const openSpans = this[OTEL_OPEN_SPANS];\n plugin._endSpansWithRedisReplies(openSpans, redisRes);\n return redisRes;\n })\n .catch((err: Error) => {\n const openSpans = this[OTEL_OPEN_SPANS];\n if (!openSpans) {\n plugin._diag.error(\n 'cannot find open spans to end for redis multi command'\n );\n } else {\n const replies =\n err.constructor.name === 'MultiErrorReply'\n ? (err as MultiErrorReply).replies\n : new Array(openSpans.length).fill(err);\n plugin._endSpansWithRedisReplies(openSpans, replies);\n }\n return Promise.reject(err);\n });\n };\n };\n }\n\n private _getPatchMultiCommandsAddCommand() {\n const plugin = this;\n return function addCommandWrapper(original: Function) {\n return function addCommandPatch(this: any, args: Array<string | Buffer>) {\n return plugin._traceClientCommand(original, this, arguments, args);\n };\n };\n }\n\n private _getPatchRedisClientMulti() {\n return function multiPatchWrapper(original: Function) {\n return function multiPatch(this: any) {\n const multiRes = original.apply(this, arguments);\n multiRes[MULTI_COMMAND_OPTIONS] = this.options;\n return multiRes;\n };\n };\n }\n\n private _getPatchRedisClientSendCommand() {\n const plugin = this;\n return function sendCommandWrapper(original: Function) {\n return function sendCommandPatch(\n this: any,\n args: Array<string | Buffer>\n ) {\n return plugin._traceClientCommand(original, this, arguments, args);\n };\n };\n }\n\n private _getPatchedClientConnect() {\n const plugin = this;\n return function connectWrapper(original: Function) {\n return function patchedConnect(this: any): Promise<void> {\n const options = this.options;\n\n const attributes = getClientAttributes(this._diag, options);\n\n const span = plugin.tracer.startSpan(\n `${RedisInstrumentation.COMPONENT}-connect`,\n {\n kind: SpanKind.CLIENT,\n attributes,\n }\n );\n\n const res = context.with(trace.setSpan(context.active(), span), () => {\n return original.apply(this);\n });\n\n return res\n .then((result: unknown) => {\n span.end();\n return result;\n })\n .catch((error: Error) => {\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.end();\n return Promise.reject(error);\n });\n };\n };\n }\n\n private _traceClientCommand(\n origFunction: Function,\n origThis: any,\n origArguments: IArguments,\n redisCommandArguments: Array<string | Buffer>\n ) {\n const hasNoParentSpan = trace.getSpan(context.active()) === undefined;\n if (hasNoParentSpan && this._config?.requireParentSpan) {\n return origFunction.apply(origThis, origArguments);\n }\n\n const clientOptions = origThis.options || origThis[MULTI_COMMAND_OPTIONS];\n\n const commandName = redisCommandArguments[0] as string; // types also allows it to be a Buffer, but in practice it only string\n const commandArgs = redisCommandArguments.slice(1);\n\n const dbStatementSerializer =\n this._config?.dbStatementSerializer || defaultDbStatementSerializer;\n\n const attributes = getClientAttributes(this._diag, clientOptions);\n\n try {\n const dbStatement = dbStatementSerializer(commandName, commandArgs);\n if (dbStatement != null) {\n attributes[SEMATTRS_DB_STATEMENT] = dbStatement;\n }\n } catch (e) {\n this._diag.error('dbStatementSerializer throw an exception', e, {\n commandName,\n });\n }\n\n const span = this.tracer.startSpan(\n `${RedisInstrumentation.COMPONENT}-${commandName}`,\n {\n kind: SpanKind.CLIENT,\n attributes,\n }\n );\n\n const res = context.with(trace.setSpan(context.active(), span), () => {\n return origFunction.apply(origThis, origArguments);\n });\n if (typeof res?.then === 'function') {\n res.then(\n (redisRes: unknown) => {\n this._endSpanWithResponse(\n span,\n commandName,\n commandArgs,\n redisRes,\n undefined\n );\n },\n (err: any) => {\n this._endSpanWithResponse(span, commandName, commandArgs, null, err);\n }\n );\n } else {\n const redisClientMultiCommand = res as {\n [OTEL_OPEN_SPANS]?: Array<MutliCommandInfo>;\n };\n redisClientMultiCommand[OTEL_OPEN_SPANS] =\n redisClientMultiCommand[OTEL_OPEN_SPANS] || [];\n redisClientMultiCommand[OTEL_OPEN_SPANS]!.push({\n span,\n commandName,\n commandArgs,\n });\n }\n return res;\n }\n\n private _endSpansWithRedisReplies(\n openSpans: Array<MutliCommandInfo>,\n replies: unknown[]\n ) {\n if (!openSpans) {\n return this._diag.error(\n 'cannot find open spans to end for redis multi command'\n );\n }\n if (replies.length !== openSpans.length) {\n return this._diag.error(\n 'number of multi command spans does not match response from redis'\n );\n }\n for (let i = 0; i < openSpans.length; i++) {\n const { span, commandName, commandArgs } = openSpans[i];\n const currCommandRes = replies[i];\n const [res, err] =\n currCommandRes instanceof Error\n ? [null, currCommandRes]\n : [currCommandRes, undefined];\n this._endSpanWithResponse(span, commandName, commandArgs, res, err);\n }\n }\n\n private _endSpanWithResponse(\n span: Span,\n commandName: string,\n commandArgs: Array<string | Buffer>,\n response: unknown,\n error: Error | undefined\n ) {\n if (!error && this._config.responseHook) {\n try {\n this._config.responseHook(span, commandName, commandArgs, response);\n } catch (err) {\n this._diag.error('responseHook throw an exception', err);\n }\n }\n if (error) {\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message });\n }\n span.end();\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 './instrumentation';\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\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.39.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-nestjs-core';\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 AttributeNames {\n VERSION = 'nestjs.version',\n TYPE = 'nestjs.type',\n MODULE = 'nestjs.module',\n CONTROLLER = 'nestjs.controller',\n CALLBACK = 'nestjs.callback',\n PIPES = 'nestjs.pipes',\n INTERCEPTORS = 'nestjs.interceptors',\n GUARDS = 'nestjs.guards',\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 NestType {\n APP_CREATION = 'app_creation',\n REQUEST_CONTEXT = 'request_context',\n REQUEST_HANDLER = 'handler',\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 { AttributeNames } from './AttributeNames';\nexport { NestType } from './NestType';\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 InstrumentationBase,\n InstrumentationConfig,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n} from '@opentelemetry/instrumentation';\nimport type { NestFactory } from '@nestjs/core/nest-factory.js';\nimport type { RouterExecutionContext } from '@nestjs/core/router/router-execution-context.js';\nimport type { Controller } from '@nestjs/common/interfaces';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_ROUTE,\n SEMATTRS_HTTP_URL,\n} from '@opentelemetry/semantic-conventions';\nimport { AttributeNames, NestType } from './enums';\n\nconst supportedVersions = ['>=4.0.0 <11'];\n\nexport class NestInstrumentation extends InstrumentationBase {\n static readonly COMPONENT = '@nestjs/core';\n static readonly COMMON_ATTRIBUTES = {\n component: NestInstrumentation.COMPONENT,\n };\n\n constructor(config: InstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n const module = new InstrumentationNodeModuleDefinition(\n NestInstrumentation.COMPONENT,\n supportedVersions\n );\n\n module.files.push(\n this.getNestFactoryFileInstrumentation(supportedVersions),\n this.getRouterExecutionContextFileInstrumentation(supportedVersions)\n );\n\n return module;\n }\n\n getNestFactoryFileInstrumentation(versions: string[]) {\n return new InstrumentationNodeModuleFile(\n '@nestjs/core/nest-factory.js',\n versions,\n (NestFactoryStatic: any, moduleVersion?: string) => {\n this.ensureWrapped(\n NestFactoryStatic.NestFactoryStatic.prototype,\n 'create',\n createWrapNestFactoryCreate(this.tracer, moduleVersion)\n );\n return NestFactoryStatic;\n },\n (NestFactoryStatic: any) => {\n this._unwrap(NestFactoryStatic.NestFactoryStatic.prototype, 'create');\n }\n );\n }\n\n getRouterExecutionContextFileInstrumentation(versions: string[]) {\n return new InstrumentationNodeModuleFile(\n '@nestjs/core/router/router-execution-context.js',\n versions,\n (RouterExecutionContext: any, moduleVersion?: string) => {\n this.ensureWrapped(\n RouterExecutionContext.RouterExecutionContext.prototype,\n 'create',\n createWrapCreateHandler(this.tracer, moduleVersion)\n );\n return RouterExecutionContext;\n },\n (RouterExecutionContext: any) => {\n this._unwrap(\n RouterExecutionContext.RouterExecutionContext.prototype,\n 'create'\n );\n }\n );\n }\n\n private ensureWrapped(\n obj: any,\n methodName: string,\n wrapper: (original: any) => any\n ) {\n if (isWrapped(obj[methodName])) {\n this._unwrap(obj, methodName);\n }\n this._wrap(obj, methodName, wrapper);\n }\n}\n\nfunction createWrapNestFactoryCreate(\n tracer: api.Tracer,\n moduleVersion?: string\n) {\n return function wrapCreate(original: typeof NestFactory.create) {\n return function createWithTrace(\n this: typeof NestFactory,\n nestModule: any\n /* serverOrOptions */\n ) {\n const span = tracer.startSpan('Create Nest App', {\n attributes: {\n ...NestInstrumentation.COMMON_ATTRIBUTES,\n [AttributeNames.TYPE]: NestType.APP_CREATION,\n [AttributeNames.VERSION]: moduleVersion,\n [AttributeNames.MODULE]: nestModule.name,\n },\n });\n const spanContext = api.trace.setSpan(api.context.active(), span);\n\n return api.context.with(spanContext, async () => {\n try {\n return await original.apply(this, arguments as any);\n } catch (e: any) {\n throw addError(span, e);\n } finally {\n span.end();\n }\n });\n };\n };\n}\n\nfunction createWrapCreateHandler(tracer: api.Tracer, moduleVersion?: string) {\n return function wrapCreateHandler(\n original: RouterExecutionContext['create']\n ) {\n return function createHandlerWithTrace(\n this: RouterExecutionContext,\n instance: Controller,\n callback: (...args: any[]) => unknown\n ) {\n arguments[1] = createWrapHandler(tracer, moduleVersion, callback);\n const handler = original.apply(this, arguments as any);\n const callbackName = callback.name;\n const instanceName =\n instance.constructor && instance.constructor.name\n ? instance.constructor.name\n : 'UnnamedInstance';\n const spanName = callbackName\n ? `${instanceName}.${callbackName}`\n : instanceName;\n\n return function (\n this: any,\n req: any,\n res: any,\n next: (...args: any[]) => unknown\n ) {\n const span = tracer.startSpan(spanName, {\n attributes: {\n ...NestInstrumentation.COMMON_ATTRIBUTES,\n [AttributeNames.VERSION]: moduleVersion,\n [AttributeNames.TYPE]: NestType.REQUEST_CONTEXT,\n [SEMATTRS_HTTP_METHOD]: req.method,\n [SEMATTRS_HTTP_URL]: req.originalUrl || req.url,\n [SEMATTRS_HTTP_ROUTE]:\n req.route?.path || req.routeOptions?.url || req.routerPath,\n [AttributeNames.CONTROLLER]: instanceName,\n [AttributeNames.CALLBACK]: callbackName,\n },\n });\n const spanContext = api.trace.setSpan(api.context.active(), span);\n\n return api.context.with(spanContext, async () => {\n try {\n return await handler.apply(this, arguments as any);\n } catch (e: any) {\n throw addError(span, e);\n } finally {\n span.end();\n }\n });\n };\n };\n };\n}\n\nfunction createWrapHandler(\n tracer: api.Tracer,\n moduleVersion: string | undefined,\n handler: Function\n) {\n const spanName = handler.name || 'anonymous nest handler';\n const options = {\n attributes: {\n ...NestInstrumentation.COMMON_ATTRIBUTES,\n [AttributeNames.VERSION]: moduleVersion,\n [AttributeNames.TYPE]: NestType.REQUEST_HANDLER,\n [AttributeNames.CALLBACK]: handler.name,\n },\n };\n const wrappedHandler = function (this: RouterExecutionContext) {\n const span = tracer.startSpan(spanName, options);\n const spanContext = api.trace.setSpan(api.context.active(), span);\n\n return api.context.with(spanContext, async () => {\n try {\n return await handler.apply(this, arguments);\n } catch (e: any) {\n throw addError(span, e);\n } finally {\n span.end();\n }\n });\n };\n\n if (handler.name) {\n Object.defineProperty(wrappedHandler, 'name', { value: handler.name });\n }\n\n // Get the current metadata and set onto the wrapper to ensure other decorators ( ie: NestJS EventPattern / RolesGuard )\n // won't be affected by the use of this instrumentation\n Reflect.getMetadataKeys(handler).forEach(metadataKey => {\n Reflect.defineMetadata(\n metadataKey,\n Reflect.getMetadata(metadataKey, handler),\n wrappedHandler\n );\n });\n return wrappedHandler;\n}\n\nconst addError = (span: api.Span, error: Error) => {\n span.recordException(error);\n span.setStatus({ code: api.SpanStatusCode.ERROR, message: error.message });\n return error;\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 './instrumentation';\nexport * from './enums/AttributeNames';\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// Postgresql specific attributes not covered by semantic conventions\nexport enum AttributeNames {\n PG_VALUES = 'db.postgresql.values',\n PG_PLAN = 'db.postgresql.plan',\n IDLE_TIMEOUT_MILLIS = 'db.postgresql.idle.timeout.millis',\n MAX_CLIENT = 'db.postgresql.max.client',\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// Contains span names produced by instrumentation\nexport enum SpanNames {\n QUERY_PREFIX = 'pg.query',\n CONNECT = 'pg.connect',\n POOL_CONNECT = 'pg-pool.connect',\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 trace,\n Span,\n SpanStatusCode,\n Tracer,\n SpanKind,\n diag,\n} from '@opentelemetry/api';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_DB_NAME,\n SEMATTRS_DB_CONNECTION_STRING,\n SEMATTRS_NET_PEER_NAME,\n SEMATTRS_NET_PEER_PORT,\n SEMATTRS_DB_USER,\n SEMATTRS_DB_STATEMENT,\n DBSYSTEMVALUES_POSTGRESQL,\n} from '@opentelemetry/semantic-conventions';\nimport {\n PgClientExtended,\n PostgresCallback,\n PgPoolCallback,\n PgPoolExtended,\n PgParsedConnectionParams,\n PgPoolOptionsParams,\n} from './internal-types';\nimport { PgInstrumentationConfig } from './types';\nimport type * as pgTypes from 'pg';\nimport { safeExecuteInTheMiddle } from '@opentelemetry/instrumentation';\nimport { SpanNames } from './enums/SpanNames';\n\n/**\n * Helper function to get a low cardinality span name from whatever info we have\n * about the query.\n *\n * This is tricky, because we don't have most of the information (table name,\n * operation name, etc) the spec recommends using to build a low-cardinality\n * value w/o parsing. So, we use db.name and assume that, if the query's a named\n * prepared statement, those `name` values will be low cardinality. If we don't\n * have a named prepared statement, we try to parse an operation (despite the\n * spec's warnings).\n *\n * @params dbName The name of the db against which this query is being issued,\n * which could be missing if no db name was given at the time that the\n * connection was established.\n * @params queryConfig Information we have about the query being issued, typed\n * to reflect only the validation we've actually done on the args to\n * `client.query()`. This will be undefined if `client.query()` was called\n * with invalid arguments.\n */\nexport function getQuerySpanName(\n dbName: string | undefined,\n queryConfig?: { text: string; name?: unknown }\n) {\n // NB: when the query config is invalid, we omit the dbName too, so that\n // someone (or some tool) reading the span name doesn't misinterpret the\n // dbName as being a prepared statement or sql commit name.\n if (!queryConfig) return SpanNames.QUERY_PREFIX;\n\n // Either the name of a prepared statement; or an attempted parse\n // of the SQL command, normalized to uppercase; or unknown.\n const command =\n typeof queryConfig.name === 'string' && queryConfig.name\n ? queryConfig.name\n : parseNormalizedOperationName(queryConfig.text);\n\n return `${SpanNames.QUERY_PREFIX}:${command}${dbName ? ` ${dbName}` : ''}`;\n}\n\nfunction parseNormalizedOperationName(queryText: string) {\n const indexOfFirstSpace = queryText.indexOf(' ');\n let sqlCommand =\n indexOfFirstSpace === -1\n ? queryText\n : queryText.slice(0, indexOfFirstSpace);\n sqlCommand = sqlCommand.toUpperCase();\n\n // Handle query text being \"COMMIT;\", which has an extra semicolon before the space.\n return sqlCommand.endsWith(';') ? sqlCommand.slice(0, -1) : sqlCommand;\n}\n\nexport function getConnectionString(params: PgParsedConnectionParams) {\n const host = params.host || 'localhost';\n const port = params.port || 5432;\n const database = params.database || '';\n return `postgresql://${host}:${port}/${database}`;\n}\n\nfunction getPort(port: number | undefined): number | undefined {\n // Port may be NaN as parseInt() is used on the value, passing null will result in NaN being parsed.\n // https://github.com/brianc/node-postgres/blob/2a8efbee09a284be12748ed3962bc9b816965e36/packages/pg/lib/connection-parameters.js#L66\n if (Number.isInteger(port)) {\n return port;\n }\n\n // Unable to find the default used in pg code, so falling back to 'undefined'.\n return undefined;\n}\n\nexport function getSemanticAttributesFromConnection(\n params: PgParsedConnectionParams\n) {\n return {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_POSTGRESQL,\n [SEMATTRS_DB_NAME]: params.database, // required\n [SEMATTRS_DB_CONNECTION_STRING]: getConnectionString(params), // required\n [SEMATTRS_NET_PEER_NAME]: params.host, // required\n [SEMATTRS_NET_PEER_PORT]: getPort(params.port),\n [SEMATTRS_DB_USER]: params.user,\n };\n}\n\nexport function getSemanticAttributesFromPool(params: PgPoolOptionsParams) {\n return {\n [SEMATTRS_DB_SYSTEM]: DBSYSTEMVALUES_POSTGRESQL,\n [SEMATTRS_DB_NAME]: params.database, // required\n [SEMATTRS_DB_CONNECTION_STRING]: getConnectionString(params), // required\n [SEMATTRS_NET_PEER_NAME]: params.host, // required\n [SEMATTRS_NET_PEER_PORT]: getPort(params.port),\n [SEMATTRS_DB_USER]: params.user,\n [AttributeNames.IDLE_TIMEOUT_MILLIS]: params.idleTimeoutMillis,\n [AttributeNames.MAX_CLIENT]: params.maxClient,\n };\n}\n\nexport function shouldSkipInstrumentation(\n instrumentationConfig: PgInstrumentationConfig\n) {\n return (\n instrumentationConfig.requireParentSpan === true &&\n trace.getSpan(context.active()) === undefined\n );\n}\n\n// Create a span from our normalized queryConfig object,\n// or return a basic span if no queryConfig was given/could be created.\nexport function handleConfigQuery(\n this: PgClientExtended,\n tracer: Tracer,\n instrumentationConfig: PgInstrumentationConfig,\n queryConfig?: { text: string; values?: unknown; name?: unknown }\n) {\n // Create child span.\n const { connectionParameters } = this;\n const dbName = connectionParameters.database;\n\n const spanName = getQuerySpanName(dbName, queryConfig);\n const span = tracer.startSpan(spanName, {\n kind: SpanKind.CLIENT,\n attributes: getSemanticAttributesFromConnection(connectionParameters),\n });\n\n if (!queryConfig) {\n return span;\n }\n\n // Set attributes\n if (queryConfig.text) {\n span.setAttribute(SEMATTRS_DB_STATEMENT, queryConfig.text);\n }\n\n if (\n instrumentationConfig.enhancedDatabaseReporting &&\n Array.isArray(queryConfig.values)\n ) {\n try {\n const convertedValues = queryConfig.values.map(value => {\n if (value == null) {\n return 'null';\n } else if (value instanceof Buffer) {\n return value.toString();\n } else if (typeof value === 'object') {\n if (typeof value.toPostgres === 'function') {\n return value.toPostgres();\n }\n return JSON.stringify(value);\n } else {\n //string, number\n return value.toString();\n }\n });\n span.setAttribute(AttributeNames.PG_VALUES, convertedValues);\n } catch (e) {\n diag.error('failed to stringify ', queryConfig.values, e);\n }\n }\n\n // Set plan name attribute, if present\n if (typeof queryConfig.name === 'string') {\n span.setAttribute(AttributeNames.PG_PLAN, queryConfig.name);\n }\n\n return span;\n}\n\nexport function handleExecutionResult(\n config: PgInstrumentationConfig,\n span: Span,\n pgResult: pgTypes.QueryResult | pgTypes.QueryArrayResult | unknown\n) {\n if (typeof config.responseHook === 'function') {\n safeExecuteInTheMiddle(\n () => {\n config.responseHook!(span, {\n data: pgResult as pgTypes.QueryResult | pgTypes.QueryArrayResult,\n });\n },\n err => {\n if (err) {\n diag.error('Error running response hook', err);\n }\n },\n true\n );\n }\n}\n\nexport function patchCallback(\n instrumentationConfig: PgInstrumentationConfig,\n span: Span,\n cb: PostgresCallback\n): PostgresCallback {\n return function patchedCallback(\n this: PgClientExtended,\n err: Error,\n res: object\n ) {\n if (err) {\n // span.recordException(err);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n } else {\n handleExecutionResult(instrumentationConfig, span, res);\n }\n\n span.end();\n cb.call(this, err, res);\n };\n}\n\nexport function patchCallbackPGPool(\n span: Span,\n cb: PgPoolCallback\n): PgPoolCallback {\n return function patchedCallback(\n this: PgPoolExtended,\n err: Error,\n res: object,\n done: any\n ) {\n if (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n }\n span.end();\n cb.call(this, err, res, done);\n };\n}\n\nexport function patchClientConnectCallback(span: Span, cb: Function): Function {\n return function patchedClientConnectCallback(\n this: pgTypes.Client,\n err: Error\n ) {\n if (err) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err.message,\n });\n }\n span.end();\n cb.apply(this, arguments);\n };\n}\n\n/**\n * Attempt to get a message string from a thrown value, while being quite\n * defensive, to recognize the fact that, in JS, any kind of value (even\n * primitives) can be thrown.\n */\nexport function getErrorMessage(e: unknown) {\n return typeof e === 'object' && e !== null && 'message' in e\n ? String((e as { message?: unknown }).message)\n : undefined;\n}\n\nexport function isObjectWithTextString(it: unknown): it is ObjectWithText {\n return (\n typeof it === 'object' &&\n typeof (it as null | { text?: unknown })?.text === 'string'\n );\n}\n\nexport type ObjectWithText = {\n text: string;\n [k: string]: unknown;\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.43.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-pg';\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 isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\n\nimport {\n context,\n trace,\n Span,\n SpanStatusCode,\n SpanKind,\n} from '@opentelemetry/api';\nimport type * as pgTypes from 'pg';\nimport type * as pgPoolTypes from 'pg-pool';\nimport {\n PgClientConnect,\n PgClientExtended,\n PostgresCallback,\n PgPoolExtended,\n PgPoolCallback,\n} from './internal-types';\nimport { PgInstrumentationConfig } from './types';\nimport * as utils from './utils';\nimport { addSqlCommenterComment } from '@opentelemetry/sql-common';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { SpanNames } from './enums/SpanNames';\n\nexport class PgInstrumentation extends InstrumentationBase {\n constructor(config: PgInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n protected init() {\n const modulePG = new InstrumentationNodeModuleDefinition(\n 'pg',\n ['>=8.0.0 <9'],\n (module: any) => {\n const moduleExports: typeof pgTypes =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.Client.prototype.query)) {\n this._unwrap(moduleExports.Client.prototype, 'query');\n }\n\n if (isWrapped(moduleExports.Client.prototype.connect)) {\n this._unwrap(moduleExports.Client.prototype, 'connect');\n }\n\n this._wrap(\n moduleExports.Client.prototype,\n 'query',\n this._getClientQueryPatch() as any\n );\n\n this._wrap(\n moduleExports.Client.prototype,\n 'connect',\n this._getClientConnectPatch() as any\n );\n\n return module;\n },\n (module: any) => {\n const moduleExports: typeof pgTypes =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.Client.prototype.query)) {\n this._unwrap(moduleExports.Client.prototype, 'query');\n }\n }\n );\n\n const modulePGPool = new InstrumentationNodeModuleDefinition(\n 'pg-pool',\n ['>=2.0.0 <4'],\n (moduleExports: typeof pgPoolTypes) => {\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n this._wrap(\n moduleExports.prototype,\n 'connect',\n this._getPoolConnectPatch() as any\n );\n return moduleExports;\n },\n (moduleExports: typeof pgPoolTypes) => {\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n }\n );\n\n return [modulePG, modulePGPool];\n }\n\n override setConfig(config: PgInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): PgInstrumentationConfig {\n return this._config as PgInstrumentationConfig;\n }\n\n private _getClientConnectPatch() {\n const plugin = this;\n return (original: PgClientConnect) => {\n return function connect(this: pgTypes.Client, callback?: Function) {\n if (utils.shouldSkipInstrumentation(plugin.getConfig())) {\n return original.call(this, callback);\n }\n\n const span = plugin.tracer.startSpan(SpanNames.CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromConnection(this),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchClientConnectCallback(span, callback);\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(\n trace.setSpan(context.active(), span),\n () => {\n return original.call(this, callback);\n }\n );\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n\n private _getClientQueryPatch() {\n const plugin = this;\n return (original: typeof pgTypes.Client.prototype.query) => {\n this._diag.debug('Patching pg.Client.prototype.query');\n return function query(this: PgClientExtended, ...args: unknown[]) {\n if (utils.shouldSkipInstrumentation(plugin.getConfig())) {\n return original.apply(this, args as never);\n }\n\n // client.query(text, cb?), client.query(text, values, cb?), and\n // client.query(configObj, cb?) are all valid signatures. We construct\n // a queryConfig obj from all (valid) signatures to build the span in a\n // unified way. We verify that we at least have query text, and code\n // defensively when dealing with `queryConfig` after that (to handle all\n // the other invalid cases, like a non-array for values being provided).\n // The type casts here reflect only what we've actually validated.\n const arg0 = args[0];\n const firstArgIsString = typeof arg0 === 'string';\n const firstArgIsQueryObjectWithText =\n utils.isObjectWithTextString(arg0);\n\n // TODO: remove the `as ...` casts below when the TS version is upgraded.\n // Newer TS versions will use the result of firstArgIsQueryObjectWithText\n // to properly narrow arg0, but TS 4.3.5 does not.\n const queryConfig = firstArgIsString\n ? {\n text: arg0 as string,\n values: Array.isArray(args[1]) ? args[1] : undefined,\n }\n : firstArgIsQueryObjectWithText\n ? (arg0 as utils.ObjectWithText)\n : undefined;\n\n const instrumentationConfig = plugin.getConfig();\n\n const span = utils.handleConfigQuery.call(\n this,\n plugin.tracer,\n instrumentationConfig,\n queryConfig\n );\n\n // Modify query text w/ a tracing comment before invoking original for\n // tracing, but only if args[0] has one of our expected shapes.\n if (instrumentationConfig.addSqlCommenterCommentToQueries) {\n args[0] = firstArgIsString\n ? addSqlCommenterComment(span, arg0)\n : firstArgIsQueryObjectWithText\n ? {\n ...arg0,\n text: addSqlCommenterComment(span, arg0.text),\n }\n : args[0];\n }\n\n // Bind callback (if any) to parent span (if any)\n if (args.length > 0) {\n const parentSpan = trace.getSpan(context.active());\n if (typeof args[args.length - 1] === 'function') {\n // Patch ParameterQuery callback\n args[args.length - 1] = utils.patchCallback(\n instrumentationConfig,\n span,\n args[args.length - 1] as PostgresCallback // nb: not type safe.\n );\n\n // If a parent span exists, bind the callback\n if (parentSpan) {\n args[args.length - 1] = context.bind(\n context.active(),\n args[args.length - 1]\n );\n }\n } else if (typeof queryConfig?.callback === 'function') {\n // Patch ConfigQuery callback\n let callback = utils.patchCallback(\n plugin.getConfig(),\n span,\n queryConfig.callback as PostgresCallback // nb: not type safe.\n );\n\n // If a parent span existed, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n\n (args[0] as { callback?: PostgresCallback }).callback = callback;\n }\n }\n\n if (\n typeof instrumentationConfig.requestHook === 'function' &&\n queryConfig\n ) {\n safeExecuteInTheMiddle(\n () => {\n // pick keys to expose explicitly, so we're not leaking pg package\n // internals that are subject to change\n const { database, host, port, user } = this.connectionParameters;\n const connection = { database, host, port, user };\n\n instrumentationConfig.requestHook!(span, {\n connection,\n query: {\n text: queryConfig.text,\n // nb: if `client.query` is called with illegal arguments\n // (e.g., if `queryConfig.values` is passed explicitly, but a\n // non-array is given), then the type casts will be wrong. But\n // we leave it up to the queryHook to handle that, and we\n // catch and swallow any errors it throws. The other options\n // are all worse. E.g., we could leave `queryConfig.values`\n // and `queryConfig.name` as `unknown`, but then the hook body\n // would be forced to validate (or cast) them before using\n // them, which seems incredibly cumbersome given that these\n // casts will be correct 99.9% of the time -- and pg.query\n // will immediately throw during development in the other .1%\n // of cases. Alternatively, we could simply skip calling the\n // hook when `values` or `name` don't have the expected type,\n // but that would add unnecessary validation overhead to every\n // hook invocation and possibly be even more confusing/unexpected.\n values: queryConfig.values as unknown[],\n name: queryConfig.name as string | undefined,\n },\n });\n },\n err => {\n if (err) {\n plugin._diag.error('Error running query hook', err);\n }\n },\n true\n );\n }\n\n let result: unknown;\n try {\n result = original.apply(this, args as never);\n } catch (e: unknown) {\n // span.recordException(e);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(e),\n });\n span.end();\n throw e;\n }\n\n // Bind promise to parent span and end the span\n if (result instanceof Promise) {\n return result\n .then((result: unknown) => {\n // Return a pass-along promise which ends the span and then goes to user's orig resolvers\n return new Promise(resolve => {\n utils.handleExecutionResult(plugin.getConfig(), span, result);\n span.end();\n resolve(result);\n });\n })\n .catch((error: Error) => {\n return new Promise((_, reject) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.end();\n reject(error);\n });\n });\n }\n\n // else returns void\n return result; // void\n };\n };\n }\n\n private _getPoolConnectPatch() {\n const plugin = this;\n return (originalConnect: typeof pgPoolTypes.prototype.connect) => {\n return function connect(this: PgPoolExtended, callback?: PgPoolCallback) {\n if (utils.shouldSkipInstrumentation(plugin.getConfig())) {\n return originalConnect.call(this, callback as any);\n }\n\n // setup span\n const span = plugin.tracer.startSpan(SpanNames.POOL_CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromPool(this.options),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchCallbackPGPool(\n span,\n callback\n ) as PgPoolCallback;\n // If a parent span exists, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(\n trace.setSpan(context.active(), span),\n () => {\n return originalConnect.call(this, callback as any);\n }\n );\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n}\n\nfunction handleConnectResult(span: Span, connectResult: unknown) {\n if (!(connectResult instanceof Promise)) {\n return connectResult;\n }\n\n const connectResultPromise = connectResult as Promise<unknown>;\n return context.bind(\n context.active(),\n connectResultPromise\n .then(result => {\n span.end();\n return result;\n })\n .catch((error: unknown) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(error),\n });\n span.end();\n return Promise.reject(error);\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 './instrumentation';\nexport * from './types';\nexport * from './enums/AttributeNames';\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 PACKAGE_VERSION = '0.40.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-hapi';\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 type * as Hapi from '@hapi/hapi';\n\nexport const HapiComponentName = '@hapi/hapi';\n\n/**\n * This symbol is used to mark a Hapi route handler or server extension handler as\n * already patched, since its possible to use these handlers multiple times\n * i.e. when allowing multiple versions of one plugin, or when registering a plugin\n * multiple times on different servers.\n */\nexport const handlerPatched: unique symbol = Symbol('hapi-handler-patched');\n\nexport type HapiServerRouteInputMethod = (route: HapiServerRouteInput) => void;\n\nexport type HapiServerRouteInput =\n | PatchableServerRoute\n | PatchableServerRoute[];\n\nexport type PatchableServerRoute = Hapi.ServerRoute<any> & {\n [handlerPatched]?: boolean;\n};\n\nexport type HapiPluginObject<T> = Hapi.ServerRegisterPluginObject<T>;\n\nexport type HapiPluginInput<T> =\n | HapiPluginObject<T>\n | Array<HapiPluginObject<T>>;\n\nexport type RegisterFunction<T> = (\n plugin: HapiPluginInput<T>,\n options?: Hapi.ServerRegisterOptions\n) => Promise<void>;\n\nexport type PatchableExtMethod = Hapi.Lifecycle.Method & {\n [handlerPatched]?: boolean;\n};\n\nexport type ServerExtDirectInput = [\n Hapi.ServerRequestExtType,\n Hapi.Lifecycle.Method,\n (Hapi.ServerExtOptions | undefined)?\n];\n\nexport const HapiLayerType = {\n ROUTER: 'router',\n PLUGIN: 'plugin',\n EXT: 'server.ext',\n};\n\nexport const HapiLifecycleMethodNames = new Set([\n 'onPreAuth',\n 'onCredentials',\n 'onPostAuth',\n 'onPreHandler',\n 'onPostHandler',\n 'onPreResponse',\n 'onRequest',\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 enum AttributeNames {\n HAPI_TYPE = 'hapi.type',\n PLUGIN_NAME = 'hapi.plugin.name',\n EXT_TYPE = 'server.ext.type',\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 { SpanAttributes } from '@opentelemetry/api';\nimport {\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_ROUTE,\n} from '@opentelemetry/semantic-conventions';\nimport type * as Hapi from '@hapi/hapi';\nimport {\n HapiLayerType,\n HapiLifecycleMethodNames,\n HapiPluginObject,\n PatchableExtMethod,\n ServerExtDirectInput,\n} from './internal-types';\nimport { AttributeNames } from './enums/AttributeNames';\n\nexport function getPluginName<T>(plugin: Hapi.Plugin<T>): string {\n if ((plugin as Hapi.PluginNameVersion).name) {\n return (plugin as Hapi.PluginNameVersion).name;\n } else {\n return (plugin as Hapi.PluginPackage).pkg.name;\n }\n}\n\nexport const isLifecycleExtType = (\n variableToCheck: unknown\n): variableToCheck is Hapi.ServerRequestExtType => {\n return (\n typeof variableToCheck === 'string' &&\n HapiLifecycleMethodNames.has(variableToCheck)\n );\n};\n\nexport const isLifecycleExtEventObj = (\n variableToCheck: unknown\n): variableToCheck is Hapi.ServerExtEventsRequestObject => {\n const event = (variableToCheck as Hapi.ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nexport const isDirectExtInput = (\n variableToCheck: unknown\n): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nexport const isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[]\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\nexport const getRouteMetadata = (\n route: Hapi.ServerRoute,\n pluginName?: string\n): {\n attributes: SpanAttributes;\n name: string;\n} => {\n if (pluginName) {\n return {\n attributes: {\n [SEMATTRS_HTTP_ROUTE]: route.path,\n [SEMATTRS_HTTP_METHOD]: route.method,\n [AttributeNames.HAPI_TYPE]: HapiLayerType.PLUGIN,\n [AttributeNames.PLUGIN_NAME]: pluginName,\n },\n name: `${pluginName}: route - ${route.path}`,\n };\n }\n return {\n attributes: {\n [SEMATTRS_HTTP_ROUTE]: route.path,\n [SEMATTRS_HTTP_METHOD]: route.method,\n [AttributeNames.HAPI_TYPE]: HapiLayerType.ROUTER,\n },\n name: `route - ${route.path}`,\n };\n};\n\nexport const getExtMetadata = (\n extPoint: Hapi.ServerRequestExtType,\n pluginName?: string\n): {\n attributes: SpanAttributes;\n name: string;\n} => {\n if (pluginName) {\n return {\n attributes: {\n [AttributeNames.EXT_TYPE]: extPoint,\n [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT,\n [AttributeNames.PLUGIN_NAME]: pluginName,\n },\n name: `${pluginName}: ext - ${extPoint}`,\n };\n }\n return {\n attributes: {\n [AttributeNames.EXT_TYPE]: extPoint,\n [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT,\n },\n name: `ext - ${extPoint}`,\n };\n};\n\nexport const getPluginFromInput = <T>(\n pluginObj: HapiPluginObject<T>\n): Hapi.Plugin<T, void> => {\n if ('plugin' in pluginObj) {\n if ('plugin' in pluginObj.plugin) {\n return pluginObj.plugin.plugin;\n }\n return pluginObj.plugin;\n }\n return pluginObj;\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 { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n InstrumentationBase,\n InstrumentationConfig,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n} from '@opentelemetry/instrumentation';\n\nimport type * as Hapi from '@hapi/hapi';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n HapiComponentName,\n HapiServerRouteInput,\n handlerPatched,\n PatchableServerRoute,\n HapiServerRouteInputMethod,\n HapiPluginInput,\n RegisterFunction,\n PatchableExtMethod,\n ServerExtDirectInput,\n} from './internal-types';\nimport {\n getRouteMetadata,\n getPluginName,\n isLifecycleExtType,\n isLifecycleExtEventObj,\n getExtMetadata,\n isDirectExtInput,\n isPatchableExtMethod,\n getPluginFromInput,\n} from './utils';\n\n/** Hapi instrumentation for OpenTelemetry */\nexport class HapiInstrumentation extends InstrumentationBase {\n constructor(config: InstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n HapiComponentName,\n ['>=17.0.0 <22'],\n (module: any) => {\n const moduleExports: typeof Hapi =\n module[Symbol.toStringTag] === 'Module' ? module.default : module;\n if (!isWrapped(moduleExports.server)) {\n this._wrap(\n moduleExports,\n 'server',\n this._getServerPatch.bind(this) as any\n );\n }\n\n if (!isWrapped(moduleExports.Server)) {\n this._wrap(\n moduleExports,\n 'Server',\n this._getServerPatch.bind(this) as any\n );\n }\n return moduleExports;\n },\n (module: any) => {\n const moduleExports: typeof Hapi =\n module[Symbol.toStringTag] === 'Module' ? module.default : module;\n this._massUnwrap([moduleExports], ['server', 'Server']);\n }\n );\n }\n\n /**\n * Patches the Hapi.server and Hapi.Server functions in order to instrument\n * the server.route, server.ext, and server.register functions via calls to the\n * @function _getServerRoutePatch, @function _getServerExtPatch, and\n * @function _getServerRegisterPatch functions\n * @param original - the original Hapi Server creation function\n */\n private _getServerPatch(\n original: (options?: Hapi.ServerOptions) => Hapi.Server\n ) {\n const instrumentation: HapiInstrumentation = this;\n const self = this;\n return function server(this: Hapi.Server, opts?: Hapi.ServerOptions) {\n const newServer: Hapi.Server = original.apply(this, [opts]);\n\n self._wrap(newServer, 'route', originalRouter => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(\n originalRouter\n );\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(newServer, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalExtHandler as any\n );\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.Server.register\n // function, which requires supporting a variety of different types of Plugin inputs\n self._wrap(\n newServer,\n 'register',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n instrumentation._getServerRegisterPatch.bind(instrumentation) as any\n );\n return newServer;\n };\n }\n\n /**\n * Patches the plugin register function used by the Hapi Server. This function\n * goes through each plugin that is being registered and adds instrumentation\n * via a call to the @function _wrapRegisterHandler function.\n * @param {RegisterFunction<T>} original - the original register function which\n * registers each plugin on the server\n */\n private _getServerRegisterPatch<T>(\n original: RegisterFunction<T>\n ): RegisterFunction<T> {\n const instrumentation: HapiInstrumentation = this;\n return function register(\n this: Hapi.Server,\n pluginInput: HapiPluginInput<T>,\n options?: Hapi.ServerRegisterOptions\n ) {\n if (Array.isArray(pluginInput)) {\n for (const pluginObj of pluginInput) {\n const plugin = getPluginFromInput(pluginObj);\n instrumentation._wrapRegisterHandler(plugin);\n }\n } else {\n const plugin = getPluginFromInput(pluginInput);\n instrumentation._wrapRegisterHandler(plugin);\n }\n return original.apply(this, [pluginInput, options]);\n };\n }\n\n /**\n * Patches the Server.ext function which adds extension methods to the specified\n * point along the request lifecycle. This function accepts the full range of\n * accepted input into the standard Hapi `server.ext` function. For each extension,\n * it adds instrumentation to the handler via a call to the @function _wrapExtMethods\n * function.\n * @param original - the original ext function which adds the extension method to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server extension. Else, signifies that the extension was added directly\n */\n private _getServerExtPatch(\n original: (...args: unknown[]) => unknown,\n pluginName?: string\n ) {\n const instrumentation: HapiInstrumentation = this;\n\n return function ext(\n this: ThisParameterType<typeof original>,\n ...args: Parameters<typeof original>\n ) {\n if (Array.isArray(args[0])) {\n const eventsList:\n | Hapi.ServerExtEventsObject[]\n | Hapi.ServerExtEventsRequestObject[] = args[0];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i];\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj =\n eventObj as Hapi.ServerExtEventsRequestObject;\n const handler = instrumentation._wrapExtMethods(\n lifecycleEventObj.method,\n eventObj.type,\n pluginName\n );\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return original.apply(this, args);\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = instrumentation._wrapExtMethods(\n method,\n extInput[0],\n pluginName\n );\n return original.apply(this, [extInput[0], handler, extInput[2]]);\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = instrumentation._wrapExtMethods(\n lifecycleEventObj.method,\n lifecycleEventObj.type,\n pluginName\n );\n lifecycleEventObj.method = handler;\n return original.call(this, lifecycleEventObj);\n }\n return original.apply(this, args);\n };\n }\n\n /**\n * Patches the Server.route function. This function accepts either one or an array\n * of Hapi.ServerRoute objects and adds instrumentation on each route via a call to\n * the @function _wrapRouteHandler function.\n * @param {HapiServerRouteInputMethod} original - the original route function which adds\n * the route to the server\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _getServerRoutePatch(\n original: HapiServerRouteInputMethod,\n pluginName?: string\n ) {\n const instrumentation: HapiInstrumentation = this;\n return function route(\n this: Hapi.Server,\n route: HapiServerRouteInput\n ): void {\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n const newRoute = instrumentation._wrapRouteHandler.call(\n instrumentation,\n route[i],\n pluginName\n );\n route[i] = newRoute;\n }\n } else {\n route = instrumentation._wrapRouteHandler.call(\n instrumentation,\n route,\n pluginName\n );\n }\n return original.apply(this, [route]);\n };\n }\n\n /**\n * Wraps newly registered plugins to add instrumentation to the plugin's clone of\n * the original server. Specifically, wraps the server.route and server.ext functions\n * via calls to @function _getServerRoutePatch and @function _getServerExtPatch\n * @param {Hapi.Plugin<T>} plugin - the new plugin which is being instrumented\n */\n private _wrapRegisterHandler<T>(plugin: Hapi.Plugin<T>): void {\n const instrumentation: HapiInstrumentation = this;\n const pluginName = getPluginName(plugin);\n const oldHandler = plugin.register;\n const self = this;\n const newRegisterHandler = function (server: Hapi.Server, options: T) {\n self._wrap(server, 'route', original => {\n return instrumentation._getServerRoutePatch.bind(instrumentation)(\n original,\n pluginName\n );\n });\n\n // Casting as any is necessary here due to multiple overloads on the Hapi.ext\n // function, which requires supporting a variety of different parameters\n // as extension inputs\n self._wrap(server, 'ext', originalExtHandler => {\n return instrumentation._getServerExtPatch.bind(instrumentation)(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n originalExtHandler as any,\n pluginName\n );\n });\n return oldHandler(server, options);\n };\n plugin.register = newRegisterHandler;\n }\n\n /**\n * Wraps request extension methods to add instrumentation to each new extension handler.\n * Patches each individual extension in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableExtMethod | PatchableExtMethod[]} method - the request extension\n * handler which is being instrumented\n * @param {Hapi.ServerRequestExtType} extPoint - the point in the Hapi request lifecycle\n * which this extension targets\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: Hapi.ServerRequestExtType,\n pluginName?: string\n ): T {\n const instrumentation: HapiInstrumentation = this;\n if (method instanceof Array) {\n for (let i = 0; i < method.length; i++) {\n method[i] = instrumentation._wrapExtMethods(\n method[i],\n extPoint\n ) as PatchableExtMethod;\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = async function (\n ...params: Parameters<Hapi.Lifecycle.Method>\n ) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with<\n Parameters<Hapi.Lifecycle.Method>,\n Hapi.Lifecycle.Method\n >(\n api.trace.setSpan(api.context.active(), span),\n method,\n undefined,\n ...params\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n return newHandler as T;\n }\n return method;\n }\n\n /**\n * Patches each individual route handler method in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {PatchableServerRoute} route - the route handler which is being instrumented\n * @param {string} [pluginName] - if present, represents the name of the plugin responsible\n * for adding this server route. Else, signifies that the route was added directly\n */\n private _wrapRouteHandler(\n route: PatchableServerRoute,\n pluginName?: string\n ): PatchableServerRoute {\n const instrumentation: HapiInstrumentation = this;\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (\n oldHandler: Hapi.Lifecycle.Method\n ) => Hapi.Lifecycle.Method = oldHandler => {\n return async function (...params: Parameters<Hapi.Lifecycle.Method>) {\n if (api.trace.getSpan(api.context.active()) === undefined) {\n return await oldHandler.call(this, ...params);\n }\n const rpcMetadata = getRPCMetadata(api.context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route.path;\n }\n const metadata = getRouteMetadata(route, pluginName);\n const span = instrumentation.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n try {\n return await api.context.with(\n api.trace.setSpan(api.context.active(), span),\n () => oldHandler.call(this, ...params)\n );\n } catch (err: any) {\n span.recordException(err);\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n throw err;\n } finally {\n span.end();\n }\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as Hapi.Lifecycle.Method);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server) {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(\n options.handler as Hapi.Lifecycle.Method\n );\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(\n route.options.handler as Hapi.Lifecycle.Method\n );\n }\n return route;\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 './instrumentation';\nexport * from './enums/AttributeNames';\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 { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\n\nexport enum KoaLayerType {\n ROUTER = 'router',\n MIDDLEWARE = 'middleware',\n}\n\n/**\n * Information about the current Koa middleware layer\n * The middleware layer type is any by default.\n * One can install koa types packages `@types/koa` and `@types/koa__router`\n * with compatible versions to the koa version used in the project\n * to get more specific types for the middleware layer property.\n *\n * Example use in a custom attribute function:\n * ```ts\n * import type { Middleware, ParameterizedContext, DefaultState } from 'koa';\n * import type { RouterParamContext } from '@koa/router';\n *\n * type KoaContext = ParameterizedContext<DefaultState, RouterParamContext>;\n * type KoaMiddleware = Middleware<DefaultState, KoaContext>;\n *\n * const koaConfig: KoaInstrumentationConfig<KoaContext, KoaMiddleware> = {\n * requestHook: (span: Span, info: KoaRequestInfo<KoaContext, KoaMiddleware>) => {\n * // custom typescript code that can access the typed into.middlewareLayer and info.context\n * }\n *\n */\nexport type KoaRequestInfo<KoaContextType = any, KoaMiddlewareType = any> = {\n context: KoaContextType;\n middlewareLayer: KoaMiddlewareType;\n layerType: KoaLayerType;\n};\n\n/**\n * Function that can be used to add custom attributes to the current span\n * @param span - The Express middleware layer span.\n * @param context - The current KoaContext.\n */\nexport interface KoaRequestCustomAttributeFunction<\n KoaContextType = any,\n KoaMiddlewareType = any\n> {\n (span: Span, info: KoaRequestInfo<KoaContextType, KoaMiddlewareType>): void;\n}\n\n/**\n * Options available for the Koa Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-Instrumentation-koa#koa-Instrumentation-options))\n */\nexport interface KoaInstrumentationConfig<\n KoaContextType = any,\n KoaMiddlewareType = any\n> extends InstrumentationConfig {\n /** Ignore specific layers based on their type */\n ignoreLayersType?: KoaLayerType[];\n /** Function for adding custom attributes to each middleware layer span */\n requestHook?: KoaRequestCustomAttributeFunction<\n KoaContextType,\n KoaMiddlewareType\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.42.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-koa';\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 enum AttributeNames {\n KOA_TYPE = 'koa.type',\n KOA_NAME = 'koa.name',\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 { KoaLayerType, KoaInstrumentationConfig } from './types';\nimport { KoaContext, KoaMiddleware } from './internal-types';\nimport { AttributeNames } from './enums/AttributeNames';\nimport { Attributes } from '@opentelemetry/api';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\n\nexport const getMiddlewareMetadata = (\n context: KoaContext,\n layer: KoaMiddleware,\n isRouter: boolean,\n layerPath?: string | RegExp\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (isRouter) {\n return {\n attributes: {\n [AttributeNames.KOA_NAME]: layerPath?.toString(),\n [AttributeNames.KOA_TYPE]: KoaLayerType.ROUTER,\n [SEMATTRS_HTTP_ROUTE]: layerPath?.toString(),\n },\n name: context._matchedRouteName || `router - ${layerPath}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.KOA_NAME]: layer.name ?? 'middleware',\n [AttributeNames.KOA_TYPE]: KoaLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n type: KoaLayerType,\n config?: KoaInstrumentationConfig\n): boolean => {\n return !!(\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\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 */\nimport type { Middleware, ParameterizedContext, DefaultState } from 'koa';\nimport type * as Router from '@koa/router';\n\nexport type KoaContext = ParameterizedContext<\n DefaultState,\n Router.RouterParamContext\n>;\nexport type KoaMiddleware = Middleware<DefaultState, KoaContext> & {\n router?: Router;\n};\n\n/**\n * This symbol is used to mark a Koa layer as being already instrumented\n * since its possible to use a given layer multiple times (ex: middlewares)\n */\nexport const kLayerPatched: unique symbol = Symbol('koa-layer-patched');\n\nexport type KoaPatchedMiddleware = KoaMiddleware & {\n [kLayerPatched]?: 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\nimport * as api from '@opentelemetry/api';\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\n\nimport type * as koa from 'koa';\nimport { KoaLayerType, KoaInstrumentationConfig } from './types';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { getMiddlewareMetadata, isLayerIgnored } from './utils';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n kLayerPatched,\n KoaContext,\n KoaMiddleware,\n KoaPatchedMiddleware,\n} from './internal-types';\n\n/** Koa instrumentation for OpenTelemetry */\nexport class KoaInstrumentation extends InstrumentationBase {\n constructor(config: KoaInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n override setConfig(config: KoaInstrumentationConfig = {}) {\n this._config = Object.assign({}, config);\n }\n\n override getConfig(): KoaInstrumentationConfig {\n return this._config as KoaInstrumentationConfig;\n }\n\n protected init() {\n return new InstrumentationNodeModuleDefinition(\n 'koa',\n ['>=2.0.0 <3'],\n (module: any) => {\n const moduleExports: typeof koa =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (moduleExports == null) {\n return moduleExports;\n }\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n this._wrap(\n moduleExports.prototype,\n 'use',\n this._getKoaUsePatch.bind(this)\n );\n return module;\n },\n (module: any) => {\n const moduleExports: typeof koa =\n module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n if (isWrapped(moduleExports.prototype.use)) {\n this._unwrap(moduleExports.prototype, 'use');\n }\n }\n );\n }\n\n /**\n * Patches the Koa.use function in order to instrument each original\n * middleware layer which is introduced\n * @param {KoaMiddleware} middleware - the original middleware function\n */\n private _getKoaUsePatch(original: (middleware: KoaMiddleware) => koa) {\n const plugin = this;\n return function use(this: koa, middlewareFunction: KoaMiddleware) {\n let patchedFunction: KoaMiddleware;\n if (middlewareFunction.router) {\n patchedFunction = plugin._patchRouterDispatch(middlewareFunction);\n } else {\n patchedFunction = plugin._patchLayer(middlewareFunction, false);\n }\n return original.apply(this, [patchedFunction]);\n };\n }\n\n /**\n * Patches the dispatch function used by @koa/router. This function\n * goes through each routed middleware and adds instrumentation via a call\n * to the @function _patchLayer function.\n * @param {KoaMiddleware} dispatchLayer - the original dispatch function which dispatches\n * routed middleware\n */\n private _patchRouterDispatch(dispatchLayer: KoaMiddleware): KoaMiddleware {\n api.diag.debug('Patching @koa/router dispatch');\n\n const router = dispatchLayer.router;\n\n const routesStack = router?.stack ?? [];\n for (const pathLayer of routesStack) {\n const path = pathLayer.path;\n const pathStack = pathLayer.stack;\n for (let j = 0; j < pathStack.length; j++) {\n const routedMiddleware: KoaMiddleware = pathStack[j];\n pathStack[j] = this._patchLayer(routedMiddleware, true, path);\n }\n }\n\n return dispatchLayer;\n }\n\n /**\n * Patches each individual @param middlewareLayer function in order to create the\n * span and propagate context. It does not create spans when there is no parent span.\n * @param {KoaMiddleware} middlewareLayer - the original middleware function.\n * @param {boolean} isRouter - tracks whether the original middleware function\n * was dispatched by the router originally\n * @param {string?} layerPath - if present, provides additional data from the\n * router about the routed path which the middleware is attached to\n */\n private _patchLayer(\n middlewareLayer: KoaPatchedMiddleware,\n isRouter: boolean,\n layerPath?: string | RegExp\n ): KoaMiddleware {\n const layerType = isRouter ? KoaLayerType.ROUTER : KoaLayerType.MIDDLEWARE;\n // Skip patching layer if its ignored in the config\n if (\n middlewareLayer[kLayerPatched] === true ||\n isLayerIgnored(layerType, this.getConfig())\n )\n return middlewareLayer;\n\n if (\n middlewareLayer.constructor.name === 'GeneratorFunction' ||\n middlewareLayer.constructor.name === 'AsyncGeneratorFunction'\n ) {\n api.diag.debug('ignoring generator-based Koa middleware layer');\n return middlewareLayer;\n }\n\n middlewareLayer[kLayerPatched] = true;\n\n api.diag.debug('patching Koa middleware layer');\n return async (context: KoaContext, next: koa.Next) => {\n const parent = api.trace.getSpan(api.context.active());\n if (parent === undefined) {\n return middlewareLayer(context, next);\n }\n const metadata = getMiddlewareMetadata(\n context,\n middlewareLayer,\n isRouter,\n layerPath\n );\n const span = this.tracer.startSpan(metadata.name, {\n attributes: metadata.attributes,\n });\n\n const rpcMetadata = getRPCMetadata(api.context.active());\n\n if (rpcMetadata?.type === RPCType.HTTP && context._matchedRoute) {\n rpcMetadata.route = context._matchedRoute.toString();\n }\n\n if (this.getConfig().requestHook) {\n safeExecuteInTheMiddle(\n () =>\n this.getConfig().requestHook!(span, {\n context,\n middlewareLayer,\n layerType,\n }),\n e => {\n if (e) {\n api.diag.error('koa instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n const newContext = api.trace.setSpan(api.context.active(), span);\n return api.context.with(newContext, async () => {\n try {\n return await middlewareLayer(context, next);\n } catch (err: any) {\n span.recordException(err);\n throw err;\n } finally {\n span.end();\n }\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 './instrumentation';\nexport * from './types';\nexport * from './enums/AttributeNames';\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 AttributeNames {\n CONNECT_TYPE = 'connect.type',\n CONNECT_NAME = 'connect.name',\n}\n\nexport enum ConnectTypes {\n MIDDLEWARE = 'middleware',\n REQUEST_HANDLER = 'request_handler',\n}\n\nexport enum ConnectNames {\n MIDDLEWARE = 'middleware',\n REQUEST_HANDLER = 'request handler',\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// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.38.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-connect';\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 type { HandleFunction, IncomingMessage, Server } from 'connect';\n\nexport const _LAYERS_STORE_PROPERTY: unique symbol = Symbol(\n 'opentelemetry.instrumentation-connect.request-route-stack'\n);\n\nexport type UseArgs1 = [HandleFunction];\nexport type UseArgs2 = [string, HandleFunction];\nexport type UseArgs = UseArgs1 | UseArgs2;\nexport type Use = (...args: UseArgs) => Server;\nexport type PatchedRequest = {\n [_LAYERS_STORE_PROPERTY]: string[];\n} & IncomingMessage;\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 { diag } from '@opentelemetry/api';\nimport { _LAYERS_STORE_PROPERTY, PatchedRequest } from './internal-types';\n\nexport const addNewStackLayer = (request: PatchedRequest) => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n request[_LAYERS_STORE_PROPERTY].push('/');\n\n const stackLength = request[_LAYERS_STORE_PROPERTY].length;\n\n return () => {\n if (stackLength === request[_LAYERS_STORE_PROPERTY].length) {\n request[_LAYERS_STORE_PROPERTY].pop();\n } else {\n diag.warn('Connect: Trying to pop the stack multiple time');\n }\n };\n};\n\nexport const replaceCurrentStackRoute = (\n request: PatchedRequest,\n newRoute?: string\n) => {\n if (newRoute) {\n request[_LAYERS_STORE_PROPERTY].splice(-1, 1, newRoute);\n }\n};\n\n// generate route from existing stack on request object.\n// splash between stack layer will be deduped\n// [\"/first/\", \"/second\", \"/third/\"] => /first/second/third/\nexport const generateRoute = (request: PatchedRequest) => {\n return request[_LAYERS_STORE_PROPERTY].reduce(\n (acc, sub) => acc.replace(/\\/+$/, '') + sub\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, Span, SpanOptions } from '@opentelemetry/api';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport type { HandleFunction, NextFunction, Server } from 'connect';\nimport type { ServerResponse } from 'http';\nimport {\n AttributeNames,\n ConnectNames,\n ConnectTypes,\n} from './enums/AttributeNames';\nimport { PatchedRequest, Use, UseArgs, UseArgs2 } from './internal-types';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationConfig,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n} from '@opentelemetry/instrumentation';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n replaceCurrentStackRoute,\n addNewStackLayer,\n generateRoute,\n} from './utils';\n\nexport const ANONYMOUS_NAME = 'anonymous';\n\n/** Connect instrumentation for OpenTelemetry */\nexport class ConnectInstrumentation extends InstrumentationBase {\n constructor(config: InstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'connect',\n ['>=3.0.0 <4'],\n moduleExports => {\n return this._patchConstructor(moduleExports);\n }\n ),\n ];\n }\n\n private _patchApp(patchedApp: Server) {\n if (!isWrapped(patchedApp.use)) {\n this._wrap(patchedApp, 'use', this._patchUse.bind(this));\n }\n if (!isWrapped(patchedApp.handle)) {\n this._wrap(patchedApp, 'handle', this._patchHandle.bind(this));\n }\n }\n\n private _patchConstructor(original: () => Server): () => Server {\n const instrumentation = this;\n return function (this: Server, ...args) {\n const app = original.apply(this, args) as Server;\n instrumentation._patchApp(app);\n return app;\n };\n }\n\n public _patchNext(next: NextFunction, finishSpan: () => void): NextFunction {\n return function nextFunction(this: NextFunction, err?: any): void {\n const result = next.apply(this, [err]);\n finishSpan();\n return result;\n };\n }\n\n public _startSpan(routeName: string, middleWare: HandleFunction): Span {\n let connectType: ConnectTypes;\n let connectName: string;\n let connectTypeName: string;\n if (routeName) {\n connectType = ConnectTypes.REQUEST_HANDLER;\n connectTypeName = ConnectNames.REQUEST_HANDLER;\n connectName = routeName;\n } else {\n connectType = ConnectTypes.MIDDLEWARE;\n connectTypeName = ConnectNames.MIDDLEWARE;\n connectName = middleWare.name || ANONYMOUS_NAME;\n }\n const spanName = `${connectTypeName} - ${connectName}`;\n const options: SpanOptions = {\n attributes: {\n [SEMATTRS_HTTP_ROUTE]: routeName.length > 0 ? routeName : '/',\n [AttributeNames.CONNECT_TYPE]: connectType,\n [AttributeNames.CONNECT_NAME]: connectName,\n },\n };\n\n return this.tracer.startSpan(spanName, options);\n }\n\n public _patchMiddleware(\n routeName: string,\n middleWare: HandleFunction\n ): HandleFunction {\n const instrumentation = this;\n const isErrorMiddleware = middleWare.length === 4;\n\n function patchedMiddleware(this: Use): void {\n if (!instrumentation.isEnabled()) {\n return (middleWare as any).apply(this, arguments);\n }\n const [reqArgIdx, resArgIdx, nextArgIdx] = isErrorMiddleware\n ? [1, 2, 3]\n : [0, 1, 2];\n const req = arguments[reqArgIdx] as PatchedRequest;\n const res = arguments[resArgIdx] as ServerResponse;\n const next = arguments[nextArgIdx] as NextFunction;\n\n replaceCurrentStackRoute(req, routeName);\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (routeName && rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = generateRoute(req);\n }\n\n let spanName = '';\n if (routeName) {\n spanName = `request handler - ${routeName}`;\n } else {\n spanName = `middleware - ${middleWare.name || ANONYMOUS_NAME}`;\n }\n const span = instrumentation._startSpan(routeName, middleWare);\n instrumentation._diag.debug('start span', spanName);\n let spanFinished = false;\n\n function finishSpan() {\n if (!spanFinished) {\n spanFinished = true;\n instrumentation._diag.debug(`finishing span ${(span as any).name}`);\n span.end();\n } else {\n instrumentation._diag.debug(\n `span ${(span as any).name} - already finished`\n );\n }\n res.removeListener('close', finishSpan);\n }\n\n res.addListener('close', finishSpan);\n arguments[nextArgIdx] = instrumentation._patchNext(next, finishSpan);\n\n return (middleWare as any).apply(this, arguments);\n }\n\n Object.defineProperty(patchedMiddleware, 'length', {\n value: middleWare.length,\n writable: false,\n configurable: true,\n });\n\n return patchedMiddleware;\n }\n\n public _patchUse(original: Server['use']): Use {\n const instrumentation = this;\n return function (this: Server, ...args: UseArgs): Server {\n const middleWare = args[args.length - 1] as HandleFunction;\n const routeName = (args[args.length - 2] || '') as string;\n\n args[args.length - 1] = instrumentation._patchMiddleware(\n routeName,\n middleWare\n );\n\n return original.apply(this, args as UseArgs2);\n };\n }\n\n public _patchHandle(original: Server['handle']): Server['handle'] {\n const instrumentation = this;\n return function (this: Server): ReturnType<Server['handle']> {\n const [reqIdx, outIdx] = [0, 2];\n const req = arguments[reqIdx] as PatchedRequest;\n const out = arguments[outIdx];\n const completeStack = addNewStackLayer(req);\n\n if (typeof out === 'function') {\n arguments[outIdx] = instrumentation._patchOut(\n out as NextFunction,\n completeStack\n );\n }\n\n return (original as any).apply(this, arguments);\n };\n }\n\n public _patchOut(out: NextFunction, completeStack: () => void): NextFunction {\n return function nextFunction(this: NextFunction, ...args: any[]): void {\n completeStack();\n return Reflect.apply(out, this, args);\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 './enums/AttributeNames';\nexport * from './instrumentation';\n","import { accountAuthStrategy } from './auth-strategies/index.js';\n\nexport const { isLoggedIn: isLoggedInToAccount } = accountAuthStrategy;\n\nexport { logout } from './logout.js';\nexport { getUserInfo } from './auth-data.js';\nexport type { UserInfo } from './schemas.js';\nexport { useAuth } from './useAuth.js';\nexport { ApiKeyLogin } from './components/ApiKeyLogin.js';\nexport { LoginWithI18n as Login } from './components/Login.js';\nexport { AccountAuthProvider } from './providers/AccountAuthProvider.js';\nexport { SiteAuthProvider } from './providers/SiteAuthProvider.js';\nexport { useSiteAuth } from './hooks/useSiteAuth.js';\nexport { authenticateWithSiteId } from './authenticate.js';\nexport type { AuthState } from './context.js';\n","export type { AuthStrategyState, AuthStrategy } from './auth-strategy-types.js';\nexport { apiKeyAuthStrategy } from './api-key-auth-strategy.js';\nexport { accountAuthStrategy } from './account-auth-strategy.js';\nexport { createSiteAuthStrategy } from './site-auth-strategy.js';\n","import { match } from 'variant';\nimport type { Headers } from '@wix/cli-http-client';\nimport { client } from '../client.js';\nimport type { ApiKeyAuth } from '../schemas.js';\nimport {\n readApiKeyAuthData,\n saveApiKeyAuthData,\n deleteAuthData,\n} from '../auth-data.js';\nimport type {\n ApiKeyAuthStrategy,\n AuthStrategyState,\n} from './auth-strategy-types.js';\n\nfunction createApiKeyAuthState({\n authData: { token, accountId, userInfo },\n siteId,\n}: {\n authData: ApiKeyAuth;\n siteId?: string;\n}): AuthStrategyState {\n return {\n getAccessToken: async () => token,\n getRefreshToken: () => {\n throw new Error('API key auth does not support refresh tokens');\n },\n getRequestHeaders: (): Headers => {\n if (siteId) {\n return { 'wix-site-id': siteId };\n }\n\n return { 'wix-account-id': accountId };\n },\n userInfo,\n };\n}\n\nexport const apiKeyAuthStrategy: ApiKeyAuthStrategy = {\n async isLoggedIn({ siteId }: { siteId?: string } = {}) {\n const apiKeyAuth = await readApiKeyAuthData();\n\n return match(apiKeyAuth, {\n Authenticated: ({ payload }) => {\n return createApiKeyAuthState({ authData: payload, siteId });\n },\n Unauthenticated: () => null,\n });\n },\n async login({ token }) {\n const { accountId, accountOwner, slug } = await client.getMyAccount({\n token,\n });\n\n const authData: ApiKeyAuth = {\n token,\n accountId,\n userInfo: {\n userId: accountOwner,\n // TODO: this should be the email of the account owner, not the slug\n // https://jira.wixpress.com/browse/FEDINF-12201\n email: slug,\n },\n };\n\n await deleteAuthData();\n await saveApiKeyAuthData(authData);\n\n return createApiKeyAuthState({ authData });\n },\n};\n","import pRetry from 'p-retry';\nimport type { Options } from 'p-retry';\nimport type {\n DeviceCodeRequest,\n RevokeRefreshTokenRequest,\n} from '@wix/ambassador-identity-oauth-v1-refresh-token/types';\nimport { getMyAccount } from '@wix/ambassador-identity-account-v2-account/http';\nimport {\n deviceCode as deviceCodeRequest,\n token as tokenRequest,\n revokeRefreshToken,\n} from '@wix/ambassador-identity-oauth-v1-refresh-token/http';\nimport type { HttpClient, HttpError } from '@wix/cli-http-client';\nimport {\n isHttpError,\n isHttpApplicationError,\n createHttpClient,\n} from '@wix/cli-http-client';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport { fields, payload, variant } from 'variant';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\nimport type { SiteAuth, UserInfo } from './schemas.js';\nimport {\n deviceCodeSchema,\n tokenSchema,\n userInfoSchema,\n getMyAccountSchema,\n} from './schemas.js';\n\nconst {\n InvalidResponseData,\n FailedToGetAuthToken,\n FailedToGetDeviceCode,\n FailedToRenewAuthToken,\n FailedToRenewAuthTokenSiteNotFound,\n FailedToRevokeRefreshToken,\n} = CliErrorCode;\n\nconst clientId = '6f95cec8-3e98-48b9-b4e5-1fb92fcd9973';\n\nconst getCurrentTimestamp = () => Math.floor(Date.now() / 1000);\n\ninterface TokenRequest {\n clientId: string;\n grantType: string;\n scope?: string;\n deviceCode?: string;\n refreshToken?: string;\n siteId?: string;\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n}\n\nexport class DeviceCodeNotYetVerifiedError extends Error {}\n\nexport const RenewTokenData = variant({\n TokenRenewed: payload<SiteAuth>(),\n RefreshTokenRevoked: fields<{ cause: HttpError }>(),\n});\n\nclass AuthClient {\n private readonly retryOptions: Options;\n constructor(private readonly httpClient: HttpClient) {\n const { minRetryTimeout } = getTestOverrides();\n\n this.retryOptions = {\n retries: 3,\n minTimeout: minRetryTimeout,\n maxTimeout: 3 * 1000,\n };\n }\n\n async requestDeviceCode(req: DeviceCodeRequest = {}) {\n try {\n const { data } = await pRetry(\n () => this.httpClient.request(deviceCodeRequest({ ...req, clientId })),\n this.retryOptions\n );\n\n return deviceCodeSchema.parse(data);\n } catch (error) {\n throw new CliError({\n code: FailedToGetDeviceCode(),\n cause: error,\n });\n }\n }\n\n async createToken(req: { deviceCode: string }) {\n try {\n const payload: TokenRequest = {\n clientId,\n grantType: 'urn:ietf:params:oauth:grant-type:device_code',\n scope: 'offline_access',\n ...req,\n };\n\n const tokenData = await pRetry(async () => {\n // any is needed because `tokenRequest` uses `RawHttpRequest` and `RawHttpResponse` which are not typed correctly\n const { data, requestId } =\n await this.httpClient.request<TokenResponse>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tokenRequest(payload as any) as any\n );\n\n const result = tokenSchema.safeParse(data);\n\n if (result.success) {\n return result.data;\n }\n\n throw new CliError({\n code: InvalidResponseData(),\n cause: result.error,\n info: { requestId, data },\n });\n }, this.retryOptions);\n\n return {\n ...tokenData,\n issuedAt: getCurrentTimestamp(),\n };\n } catch (error) {\n if (\n isHttpError(error) &&\n (error.response?.data?.message === 'Device code is not yet verified' ||\n // https://github.com/wix-private/wix-cli/pull/655#discussion_r1145992702\n error.response?.data?.error === 'authorization_pending')\n ) {\n throw new DeviceCodeNotYetVerifiedError(\n 'Device code is not yet verified.'\n );\n }\n\n throw new CliError({\n code: FailedToGetAuthToken(),\n cause: error,\n });\n }\n }\n\n async renewToken(req: { refreshToken: string; siteId?: string }) {\n try {\n const payload: TokenRequest = {\n clientId,\n grantType: 'refresh_token',\n ...req,\n };\n\n // any is needed because `tokenRequest` uses `RawHttpRequest` and `RawHttpResponse` which are not typed correctly\n const { data } = await pRetry(\n () =>\n this.httpClient.request<TokenResponse>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n tokenRequest(payload as any) as any\n ),\n this.retryOptions\n );\n\n const tokenData = tokenSchema.parse(data);\n\n return RenewTokenData.TokenRenewed({\n ...tokenData,\n issuedAt: getCurrentTimestamp(),\n });\n } catch (error) {\n if (isHttpError(error)) {\n if (\n error.response?.status === 400 &&\n error.response.data?.error === 'invalid_grant'\n ) {\n return RenewTokenData.RefreshTokenRevoked({ cause: error });\n }\n if (\n req.siteId &&\n error.response?.status === 404 &&\n isHttpApplicationError(error) &&\n error.response.data.details.applicationError.code === 'SITE_NOT_FOUND'\n ) {\n throw new CliError({\n code: FailedToRenewAuthTokenSiteNotFound({ siteId: req.siteId }),\n cause: error,\n });\n }\n }\n\n throw new CliError({\n code: FailedToRenewAuthToken(),\n cause: error,\n });\n }\n }\n\n async revokeRefreshToken(\n req: RevokeRefreshTokenRequest,\n { email }: UserInfo\n ) {\n try {\n const { data } = await this.httpClient.request(revokeRefreshToken(req));\n\n return data;\n } catch (error) {\n throw new CliError({\n code: FailedToRevokeRefreshToken({\n email,\n }),\n info: {\n email,\n },\n cause: error,\n });\n }\n }\n\n async userInfo({ accessToken }: { accessToken: string }) {\n try {\n const httpClient = createHttpClient({\n type: 'backoffice',\n getAppToken: async () => accessToken,\n });\n const { data: userInfoData } = await httpClient.get(\n '/_serverless/wix-cli-userinfo/userinfo'\n );\n\n return userInfoSchema.parse(userInfoData);\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToGetUserInfo(),\n cause: error,\n });\n }\n }\n\n async getMyAccount({ token }: { token: string }) {\n try {\n const httpClient = createHttpClient({\n type: 'backoffice',\n getAppToken: async () => token,\n });\n const { data } = await httpClient.request(getMyAccount({}));\n\n return getMyAccountSchema.parse(data).account;\n } catch (error) {\n // 48876 is code for `TargetAccountIsMissingErrorCode`,\n // which in this case means that user tried to log in with invalid API key.\n if (\n isHttpError(error) &&\n error.response?.status === 428 &&\n isHttpApplicationError(error) &&\n error.response.data.details.applicationError.code === '48876'\n ) {\n throw new CliError({\n code: CliErrorCode.InvalidApiKey(),\n cause: error,\n });\n }\n if (\n isHttpError(error) &&\n error.response?.status === 404 &&\n isHttpApplicationError(error) &&\n error.response.data.details.applicationError.code === '48886'\n ) {\n throw new CliError({\n code: CliErrorCode.AccountWasDeleted(),\n cause: error,\n });\n }\n throw new CliError({\n code: CliErrorCode.FailedToGetMyAccount(),\n cause: error,\n });\n }\n }\n}\n\nexport const client = new AuthClient(createHttpClient({ type: 'backoffice' }));\n","import retry from 'retry';\nimport isNetworkError from 'is-network-error';\n\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\n\t\tif (message instanceof Error) {\n\t\t\tthis.originalError = message;\n\t\t\t({message} = message);\n\t\t} else {\n\t\t\tthis.originalError = new Error(message);\n\t\t\tthis.originalError.stack = this.stack;\n\t\t}\n\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\nconst decorateErrorWithCounts = (error, attemptNumber, options) => {\n\t// Minus 1 from attemptNumber because the first attempt does not count as a retry\n\tconst retriesLeft = options.retries - (attemptNumber - 1);\n\n\terror.attemptNumber = attemptNumber;\n\terror.retriesLeft = retriesLeft;\n\treturn error;\n};\n\nexport default async function pRetry(input, options) {\n\treturn new Promise((resolve, reject) => {\n\t\toptions = {...options};\n\t\toptions.onFailedAttempt ??= () => {};\n\t\toptions.shouldRetry ??= () => true;\n\t\toptions.retries ??= 10;\n\n\t\tconst operation = retry.operation(options);\n\n\t\tconst abortHandler = () => {\n\t\t\toperation.stop();\n\t\t\treject(options.signal?.reason);\n\t\t};\n\n\t\tif (options.signal && !options.signal.aborted) {\n\t\t\toptions.signal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tconst cleanUp = () => {\n\t\t\toptions.signal?.removeEventListener('abort', abortHandler);\n\t\t\toperation.stop();\n\t\t};\n\n\t\toperation.attempt(async attemptNumber => {\n\t\t\ttry {\n\t\t\t\tconst result = await input(attemptNumber);\n\t\t\t\tcleanUp();\n\t\t\t\tresolve(result);\n\t\t\t} catch (error) {\n\t\t\t\ttry {\n\t\t\t\t\tif (!(error instanceof Error)) {\n\t\t\t\t\t\tthrow new TypeError(`Non-error was thrown: \"${error}\". You should only throw errors.`);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof AbortError) {\n\t\t\t\t\t\tthrow error.originalError;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (error instanceof TypeError && !isNetworkError(error)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\n\t\t\t\t\tdecorateErrorWithCounts(error, attemptNumber, options);\n\n\t\t\t\t\tif (!(await options.shouldRetry(error))) {\n\t\t\t\t\t\toperation.stop();\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}\n\n\t\t\t\t\tawait options.onFailedAttempt(error);\n\n\t\t\t\t\tif (!operation.retry(error)) {\n\t\t\t\t\t\tthrow operation.mainError();\n\t\t\t\t\t}\n\t\t\t\t} catch (finalError) {\n\t\t\t\t\tdecorateErrorWithCounts(finalError, attemptNumber, options);\n\t\t\t\t\tcleanUp();\n\t\t\t\t\treject(finalError);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t});\n}\n","const objectToString = Object.prototype.toString;\n\nconst isError = value => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n\t'network error', // Chrome\n\t'Failed to fetch', // Chrome\n\t'NetworkError when attempting to fetch resource.', // Firefox\n\t'The Internet connection appears to be offline.', // Safari 16\n\t'Load failed', // Safari 17+\n\t'Network request failed', // `cross-fetch`\n\t'fetch failed', // Undici (Node.js)\n\t'terminated', // Undici (Node.js)\n]);\n\nexport default function isNetworkError(error) {\n\tconst isValid = error\n\t\t&& isError(error)\n\t\t&& error.name === 'TypeError'\n\t\t&& typeof error.message === 'string';\n\n\tif (!isValid) {\n\t\treturn false;\n\t}\n\n\t// We do an extra check for Safari 17+ as it has a very generic error message.\n\t// Network errors in Safari have no stack.\n\tif (error.message === 'Load failed') {\n\t\treturn error.stack === undefined;\n\t}\n\n\treturn errorMessages.has(error.message);\n}\n",null,"export * from './serialization';\nexport * from './url-resolver';\nexport * from './flatten-params';\n","export * from './utils';\n","type SchemaType = 'Array' | 'Map';\n\nexport function parseLeanSchemaRef(renderedSchemaName: string = ''): {\n schemaName: string;\n schemaType?: SchemaType;\n} {\n const [typeOrName, schemaName] = getSchemaNameAndType(renderedSchemaName);\n\n if (schemaName) {\n return {\n schemaName,\n schemaType: typeOrName as SchemaType,\n };\n }\n\n return {\n schemaName: typeOrName,\n };\n}\n\n// if there is no type, returns only the name\nconst getSchemaNameAndType = (leanSchema: string): string[] =>\n leanSchema.split('#');\n","import { findByPath } from './utils';\n\nconst USER_DOMAIN = '_';\n\nconst DOMAINS = ['wix.com', 'editorx.com'];\n\nconst WIX_API_DOMAINS = ['42.wixprod.net', 'uw2-edt-1.wixprod.net'];\n\nconst DEV_WIX_CODE_DOMAIN = 'dev.wix-code.com';\n\nconst REGEX_CAPTURE_PROTO_FIELD = /{(.*)}/;\n\nconst REGEX_CAPTURE_DOMAINS = new RegExp(`\\\\.(${DOMAINS.join('|')})$`);\n\nconst REGEX_CAPTURE_API_DOMAINS = new RegExp(\n `\\\\.(${WIX_API_DOMAINS.join('|')})$`,\n);\n\nconst REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN = new RegExp(\n `.*\\\\.${DEV_WIX_CODE_DOMAIN}$`,\n);\n\nexport type ResolveUrlOpts = {\n // resource path as defined in proto file, including all wildcards & co.\n protoPath: string;\n\n // domain as defined on FP to its mappings (might be more than one)\n // www._base_domain_ => [{ srcPath: '/_api/foo', destPath: '/api' }]\n domainToMappings: DomainToMappings;\n\n // actual payload attached to request, needed in order to rersolve path,\n // in case it contains some dynamic parameters\n data?: object;\n\n // request's host\n host: string;\n};\n\nexport function resolveUrl(opts: ResolveUrlOpts) {\n const domain = resolveDomain(opts.host);\n const mappings = resolveMappingsByDomain(domain, opts.domainToMappings);\n const path = injectDataIntoProtoPath(opts.protoPath, opts.data || {});\n\n return resolvePath(path, mappings);\n}\n\nfunction injectDataIntoProtoPath(protoPath: string, data: object) {\n return protoPath\n .split('/')\n .map((path) => maybeProtoPathToData(path, data))\n .join('/');\n}\n\nfunction maybeProtoPathToData(protoPath: string, data: object) {\n const protoRegExpMatch = protoPath.match(REGEX_CAPTURE_PROTO_FIELD) || [];\n\n const field = protoRegExpMatch[1];\n\n if (field) {\n const suffix = protoPath.replace(protoRegExpMatch[0]!, '');\n return findByPath(data, field, protoPath, suffix);\n }\n\n return protoPath;\n}\n\nfunction resolveDomain(host: string) {\n const resolvedHost = fixHostExceptions(host);\n\n return resolvedHost\n .replace(REGEX_CAPTURE_DOMAINS, '._base_domain_')\n .replace(REGEX_CAPTURE_API_DOMAINS, '._api_base_domain_')\n .replace(REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN, '*.dev.wix-code.com');\n}\n\n// hosts which standard string replacing doesn't apply to them, will be fixed here.\nfunction fixHostExceptions(host: string) {\n // https://system-kb.wixanswers.com/kb/en/article/editorx-domains-matching-to-wixcom\n return host.replace('create.editorx.com', 'editor.editorx.com');\n}\n\nfunction resolveMappingsByDomain(\n domain: string,\n domainToMappings: DomainToMappings,\n) {\n const mappings = domainToMappings[domain];\n\n if (mappings) {\n return mappings;\n }\n\n const rootDomainMappings = resolveRootDomain(domain, domainToMappings);\n\n if (!rootDomainMappings) {\n const userMappings = domainToMappings[USER_DOMAIN];\n\n if (userMappings) {\n return userMappings;\n }\n if (isBaseDomain(domain)) {\n // fallback <lang>.wix.com sub domains to www.wix.com\n // since all of the languages subdomain are not mapped automatically in FP and we want to support those kind of calls\n // for example: fr.wix.com\n return domainToMappings[wwwBaseDomain];\n }\n }\n\n return rootDomainMappings ?? [];\n}\n\nfunction resolveRootDomain(domain: string, domainToMappings: DomainToMappings) {\n return Object.entries(domainToMappings).find(([entryDomain]) => {\n const [_, ...rooDomainSegments] = domain.split('.');\n return rooDomainSegments.join('.') === entryDomain;\n })?.[1];\n}\nfunction resolvePath(protoPath: string, mappings: Mapping[]) {\n const mapping = mappings?.find((m) => protoPath.startsWith(m.destPath));\n\n if (!mapping) {\n // todo: should we return the path? if no - what should we do in case of testings?\n return protoPath;\n }\n\n return mapping.srcPath + protoPath.slice(mapping.destPath.length);\n}\n\ntype Mapping = {\n srcPath: string;\n destPath: string;\n};\n\ntype DomainToMappings = Record<string, Mapping[]>;\n\nfunction isBaseDomain(domain: string) {\n return !!domain.match(/\\._base_domain_$/);\n}\n\nconst wwwBaseDomain = 'www._base_domain_';\n","export function findByPath(\n obj: object,\n path: string,\n defaultValue: string,\n suffix: string,\n) {\n let result: any = obj;\n for (const field of path.split('.')) {\n if (!result) {\n return defaultValue;\n }\n result = result[field];\n }\n\n return `${result}${suffix}`;\n}\n","import { encode } from 'js-base64';\n\n// Flatten a nested object to params object { field: { text: 'foo' } } => { field.text ='foo' }\nfunction flattenParams(data: object, path = ''): object {\n const params: any = {};\n\n Object.entries(data).forEach(([key, value]) => {\n const isObject =\n value !== null && typeof value === 'object' && !Array.isArray(value);\n const fieldPath = resolvePath(path, key);\n\n if (isObject) {\n const serializedObject = flattenParams(value, fieldPath);\n Object.assign(params, serializedObject);\n } else {\n params[fieldPath] = value;\n }\n });\n\n return params;\n}\n\nfunction resolvePath(path: string, key: string) {\n return `${path}${path ? '.' : ''}${key}`;\n}\n\n/**\n * serializes the params object to URLSearchParams,\n * if isComplexRequest is true and the payload is not serializable as regular URLSearchParams (because of nested fields),\n * it will serialize the payload into the .r query param exclusively\n * @param params\n * @param isComplexRequest\n * @returns\n */\nexport function toURLSearchParams(params: object, isComplexRequest?: boolean) {\n const flatten = flattenParams(params);\n\n // payloads with deep arrays or complex arrays are not serializable as URLSearchParams\n const isPayloadNonSerializableAsUrlSearchParams = Object.entries(\n flatten,\n ).some(\n ([key, value]) =>\n key.includes('.') ||\n (Array.isArray(value) && value.some((v) => typeof v === 'object')),\n );\n const shouldSerializeToRParam =\n isComplexRequest && isPayloadNonSerializableAsUrlSearchParams;\n\n if (shouldSerializeToRParam) {\n return new URLSearchParams({ '.r': encode(JSON.stringify(params), true) });\n } else {\n return Object.entries(flatten).reduce((urlSearchParams, [key, value]) => {\n // inorder to make `foo: [1,2]` turn into `foo=1&foo=2` and not `foo[]=1&foo[]=2`\n const keyParams = Array.isArray(value) ? value : [value];\n\n keyParams.forEach((param: any) => {\n if (\n param === undefined ||\n param === null ||\n (Array.isArray(value) && typeof param === 'object')\n ) {\n return;\n }\n\n urlSearchParams.append(key, param);\n });\n\n return urlSearchParams;\n }, new URLSearchParams());\n }\n}\n","/**\n * base64.ts\n *\n * Licensed under the BSD 3-Clause License.\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * References:\n * http://en.wikipedia.org/wiki/Base64\n *\n * @author Dan Kogai (https://github.com/dankogai)\n */\nconst version = '3.7.7';\n/**\n * @deprecated use lowercase `version`.\n */\nconst VERSION = version;\nconst _hasBuffer = typeof Buffer === 'function';\nconst _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;\nconst _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;\nconst b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\nconst b64chs = Array.prototype.slice.call(b64ch);\nconst b64tab = ((a) => {\n let tab = {};\n a.forEach((c, i) => tab[c] = i);\n return tab;\n})(b64chs);\nconst b64re = /^(?:[A-Za-z\\d+\\/]{4})*?(?:[A-Za-z\\d+\\/]{2}(?:==)?|[A-Za-z\\d+\\/]{3}=?)?$/;\nconst _fromCC = String.fromCharCode.bind(String);\nconst _U8Afrom = typeof Uint8Array.from === 'function'\n ? Uint8Array.from.bind(Uint8Array)\n : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));\nconst _mkUriSafe = (src) => src\n .replace(/=/g, '').replace(/[+\\/]/g, (m0) => m0 == '+' ? '-' : '_');\nconst _tidyB64 = (s) => s.replace(/[^A-Za-z0-9\\+\\/]/g, '');\n/**\n * polyfill version of `btoa`\n */\nconst btoaPolyfill = (bin) => {\n // console.log('polyfilled');\n let u32, c0, c1, c2, asc = '';\n const pad = bin.length % 3;\n for (let i = 0; i < bin.length;) {\n if ((c0 = bin.charCodeAt(i++)) > 255 ||\n (c1 = bin.charCodeAt(i++)) > 255 ||\n (c2 = bin.charCodeAt(i++)) > 255)\n throw new TypeError('invalid character found');\n u32 = (c0 << 16) | (c1 << 8) | c2;\n asc += b64chs[u32 >> 18 & 63]\n + b64chs[u32 >> 12 & 63]\n + b64chs[u32 >> 6 & 63]\n + b64chs[u32 & 63];\n }\n return pad ? asc.slice(0, pad - 3) + \"===\".substring(pad) : asc;\n};\n/**\n * does what `window.btoa` of web browsers do.\n * @param {String} bin binary string\n * @returns {string} Base64-encoded string\n */\nconst _btoa = typeof btoa === 'function' ? (bin) => btoa(bin)\n : _hasBuffer ? (bin) => Buffer.from(bin, 'binary').toString('base64')\n : btoaPolyfill;\nconst _fromUint8Array = _hasBuffer\n ? (u8a) => Buffer.from(u8a).toString('base64')\n : (u8a) => {\n // cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326\n const maxargs = 0x1000;\n let strs = [];\n for (let i = 0, l = u8a.length; i < l; i += maxargs) {\n strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));\n }\n return _btoa(strs.join(''));\n };\n/**\n * converts a Uint8Array to a Base64 string.\n * @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5\n * @returns {string} Base64 string\n */\nconst fromUint8Array = (u8a, urlsafe = false) => urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);\n// This trick is found broken https://github.com/dankogai/js-base64/issues/130\n// const utob = (src: string) => unescape(encodeURIComponent(src));\n// reverting good old fationed regexp\nconst cb_utob = (c) => {\n if (c.length < 2) {\n var cc = c.charCodeAt(0);\n return cc < 0x80 ? c\n : cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))\n + _fromCC(0x80 | (cc & 0x3f)))\n : (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))\n + _fromCC(0x80 | ((cc >>> 6) & 0x3f))\n + _fromCC(0x80 | (cc & 0x3f)));\n }\n else {\n var cc = 0x10000\n + (c.charCodeAt(0) - 0xD800) * 0x400\n + (c.charCodeAt(1) - 0xDC00);\n return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))\n + _fromCC(0x80 | ((cc >>> 12) & 0x3f))\n + _fromCC(0x80 | ((cc >>> 6) & 0x3f))\n + _fromCC(0x80 | (cc & 0x3f)));\n }\n};\nconst re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n/**\n * @deprecated should have been internal use only.\n * @param {string} src UTF-8 string\n * @returns {string} UTF-16 string\n */\nconst utob = (u) => u.replace(re_utob, cb_utob);\n//\nconst _encode = _hasBuffer\n ? (s) => Buffer.from(s, 'utf8').toString('base64')\n : _TE\n ? (s) => _fromUint8Array(_TE.encode(s))\n : (s) => _btoa(utob(s));\n/**\n * converts a UTF-8-encoded string to a Base64 string.\n * @param {boolean} [urlsafe] if `true` make the result URL-safe\n * @returns {string} Base64 string\n */\nconst encode = (src, urlsafe = false) => urlsafe\n ? _mkUriSafe(_encode(src))\n : _encode(src);\n/**\n * converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.\n * @returns {string} Base64 string\n */\nconst encodeURI = (src) => encode(src, true);\n// This trick is found broken https://github.com/dankogai/js-base64/issues/130\n// const btou = (src: string) => decodeURIComponent(escape(src));\n// reverting good old fationed regexp\nconst re_btou = /[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xF7][\\x80-\\xBF]{3}/g;\nconst cb_btou = (cccc) => {\n switch (cccc.length) {\n case 4:\n var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n | ((0x3f & cccc.charCodeAt(1)) << 12)\n | ((0x3f & cccc.charCodeAt(2)) << 6)\n | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000;\n return (_fromCC((offset >>> 10) + 0xD800)\n + _fromCC((offset & 0x3FF) + 0xDC00));\n case 3:\n return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12)\n | ((0x3f & cccc.charCodeAt(1)) << 6)\n | (0x3f & cccc.charCodeAt(2)));\n default:\n return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6)\n | (0x3f & cccc.charCodeAt(1)));\n }\n};\n/**\n * @deprecated should have been internal use only.\n * @param {string} src UTF-16 string\n * @returns {string} UTF-8 string\n */\nconst btou = (b) => b.replace(re_btou, cb_btou);\n/**\n * polyfill version of `atob`\n */\nconst atobPolyfill = (asc) => {\n // console.log('polyfilled');\n asc = asc.replace(/\\s+/g, '');\n if (!b64re.test(asc))\n throw new TypeError('malformed base64.');\n asc += '=='.slice(2 - (asc.length & 3));\n let u24, bin = '', r1, r2;\n for (let i = 0; i < asc.length;) {\n u24 = b64tab[asc.charAt(i++)] << 18\n | b64tab[asc.charAt(i++)] << 12\n | (r1 = b64tab[asc.charAt(i++)]) << 6\n | (r2 = b64tab[asc.charAt(i++)]);\n bin += r1 === 64 ? _fromCC(u24 >> 16 & 255)\n : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255)\n : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);\n }\n return bin;\n};\n/**\n * does what `window.atob` of web browsers do.\n * @param {String} asc Base64-encoded string\n * @returns {string} binary string\n */\nconst _atob = typeof atob === 'function' ? (asc) => atob(_tidyB64(asc))\n : _hasBuffer ? (asc) => Buffer.from(asc, 'base64').toString('binary')\n : atobPolyfill;\n//\nconst _toUint8Array = _hasBuffer\n ? (a) => _U8Afrom(Buffer.from(a, 'base64'))\n : (a) => _U8Afrom(_atob(a).split('').map(c => c.charCodeAt(0)));\n/**\n * converts a Base64 string to a Uint8Array.\n */\nconst toUint8Array = (a) => _toUint8Array(_unURI(a));\n//\nconst _decode = _hasBuffer\n ? (a) => Buffer.from(a, 'base64').toString('utf8')\n : _TD\n ? (a) => _TD.decode(_toUint8Array(a))\n : (a) => btou(_atob(a));\nconst _unURI = (a) => _tidyB64(a.replace(/[-_]/g, (m0) => m0 == '-' ? '+' : '/'));\n/**\n * converts a Base64 string to a UTF-8 string.\n * @param {String} src Base64 string. Both normal and URL-safe are supported\n * @returns {string} UTF-8 string\n */\nconst decode = (src) => _decode(_unURI(src));\n/**\n * check if a value is a valid Base64 string\n * @param {String} src a value to check\n */\nconst isValid = (src) => {\n if (typeof src !== 'string')\n return false;\n const s = src.replace(/\\s+/g, '').replace(/={0,2}$/, '');\n return !/[^\\s0-9a-zA-Z\\+/]/.test(s) || !/[^\\s0-9a-zA-Z\\-_]/.test(s);\n};\n//\nconst _noEnum = (v) => {\n return {\n value: v, enumerable: false, writable: true, configurable: true\n };\n};\n/**\n * extend String.prototype with relevant methods\n */\nconst extendString = function () {\n const _add = (name, body) => Object.defineProperty(String.prototype, name, _noEnum(body));\n _add('fromBase64', function () { return decode(this); });\n _add('toBase64', function (urlsafe) { return encode(this, urlsafe); });\n _add('toBase64URI', function () { return encode(this, true); });\n _add('toBase64URL', function () { return encode(this, true); });\n _add('toUint8Array', function () { return toUint8Array(this); });\n};\n/**\n * extend Uint8Array.prototype with relevant methods\n */\nconst extendUint8Array = function () {\n const _add = (name, body) => Object.defineProperty(Uint8Array.prototype, name, _noEnum(body));\n _add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); });\n _add('toBase64URI', function () { return fromUint8Array(this, true); });\n _add('toBase64URL', function () { return fromUint8Array(this, true); });\n};\n/**\n * extend Builtin prototypes with relevant methods\n */\nconst extendBuiltins = () => {\n extendString();\n extendUint8Array();\n};\nconst gBase64 = {\n version: version,\n VERSION: VERSION,\n atob: _atob,\n atobPolyfill: atobPolyfill,\n btoa: _btoa,\n btoaPolyfill: btoaPolyfill,\n fromBase64: decode,\n toBase64: encode,\n encode: encode,\n encodeURI: encodeURI,\n encodeURL: encodeURI,\n utob: utob,\n btou: btou,\n decode: decode,\n isValid: isValid,\n fromUint8Array: fromUint8Array,\n toUint8Array: toUint8Array,\n extendString: extendString,\n extendUint8Array: extendUint8Array,\n extendBuiltins: extendBuiltins\n};\n// makecjs:CUT //\nexport { version };\nexport { VERSION };\nexport { _atob as atob };\nexport { atobPolyfill };\nexport { _btoa as btoa };\nexport { btoaPolyfill };\nexport { decode as fromBase64 };\nexport { encode as toBase64 };\nexport { utob };\nexport { encode };\nexport { encodeURI };\nexport { encodeURI as encodeURL };\nexport { btou };\nexport { decode };\nexport { isValid };\nexport { fromUint8Array };\nexport { toUint8Array };\nexport { extendString };\nexport { extendUint8Array };\nexport { extendBuiltins };\n// and finally,\nexport { gBase64 as Base64 };\n","import type {\n RenderedLeanSchema,\n RenderedLeanSchemaFields,\n} from '@wix/metro-public-utils';\nimport { ConverterType, Payload } from './serializer/domain';\nimport { schemaSerializer } from './serializer/serializer';\nimport { protobufConverters } from './serializer/protobuf-converters/converters';\nimport { typeToConverterSet } from './serializer/utils';\n\nconst ambassadorConverters = typeToConverterSet([...protobufConverters]);\n\nexport type { GoogleProtoDuration } from './serializer/protobuf-converters/types';\n\nexport function serializer<T>(\n rootSchema: RenderedLeanSchemaFields,\n depSchemas: RenderedLeanSchema = {},\n) {\n const transform = schemaSerializer(\n rootSchema,\n depSchemas,\n ambassadorConverters,\n );\n\n return {\n fromJSON(jsonOrString: Payload | string): T {\n const jsonOrText = safeJsonParse(jsonOrString) || jsonOrString;\n return transform(jsonOrText, ConverterType.FROM_JSON) as T;\n },\n\n toJSON(json: T) {\n return transform(json, ConverterType.TO_JSON) as Payload;\n },\n };\n}\n\nfunction safeJsonParse(someString: string): any {\n try {\n return JSON.parse(someString);\n } catch (error) {}\n}\n","export enum ConverterType {\n TO_JSON,\n FROM_JSON,\n}\n\nexport type Payload = any;\n\nexport type Converter = {\n transform: (val: any) => any;\n checkRepetable?: (val: any) => boolean;\n};\n\nexport type ConverterSet = {\n types: string[];\n [ConverterType.FROM_JSON]: Converter;\n [ConverterType.TO_JSON]: Converter;\n};\n\nexport type TypeToConverterSet = Record<string, ConverterSet>;\n","import type {\n RenderedLeanSchemaFields,\n RenderedLeanSchema,\n} from '@wix/metro-public-utils';\nimport { parseLeanSchemaRef } from '..';\nimport { ConverterType, Payload, TypeToConverterSet } from './domain';\n\nexport function schemaSerializer(\n rootSchema: RenderedLeanSchemaFields,\n depSchemas: RenderedLeanSchema = {},\n converterSets: TypeToConverterSet,\n) {\n return function serialize(\n json: Payload = {},\n converterType: ConverterType,\n ): Payload {\n return typeof json === 'string' ? json : transformSchema(rootSchema, json);\n\n function transformSchema(\n schema: RenderedLeanSchemaFields,\n payload: any,\n ): Payload {\n const result = {} as Payload;\n if ([null, undefined].includes(payload)) {\n return payload;\n }\n\n Object.entries(payload).forEach(([key, val]) => {\n const renderedSchemaName = schema[key];\n const { schemaName, schemaType } =\n parseLeanSchemaRef(renderedSchemaName);\n\n const isMap = schemaType === 'Map';\n const isRepeatable =\n getConverter(schemaName)?.checkRepetable?.(val) ?? Array.isArray(val);\n\n let parsedValue;\n\n if (isRepeatable) {\n parsedValue = (val as any[]).map((v) => applyField(v, schemaName));\n } else if (isMap) {\n parsedValue = applyFieldOnMap(val, schemaName);\n } else {\n parsedValue = applyField(val, schemaName);\n }\n\n result[key] = parsedValue;\n });\n\n return result;\n }\n\n function applyField(val: unknown, schemaOrSerializer?: string) {\n if (!schemaOrSerializer) {\n return val;\n }\n\n const maybeSchema = depSchemas[schemaOrSerializer];\n const maybeConverter = getConverter(schemaOrSerializer);\n\n if (maybeConverter) {\n return getConverter(schemaOrSerializer).transform(val);\n } else if (maybeSchema) {\n return transformSchema(maybeSchema, val);\n }\n\n throw new Error(\n `${schemaOrSerializer} is neither schema nor serializable type`,\n );\n }\n\n function getConverter(name: string) {\n return converterSets[name]?.[converterType];\n }\n\n function applyFieldOnMap(val: any, sanitizedSchemaOrSerializer: string) {\n return Object.entries(val).reduce<Record<string, any>>(\n (acc, [propertyName, value]) => {\n acc[propertyName] = applyField(value, sanitizedSchemaOrSerializer);\n return acc;\n },\n {},\n );\n }\n };\n}\n","import { ConverterSet } from '../domain';\nimport { timestamp } from './timestamp';\nimport { fieldMask } from './field-mask';\nimport { bytes } from './bytes';\nimport { duration } from './duration';\nimport { float } from './float';\n\nexport const protobufConverters: ConverterSet[] = [\n timestamp,\n fieldMask,\n bytes,\n duration,\n float,\n];\n","import { ConverterSet, ConverterType } from '../domain';\n\nexport const timestamp: ConverterSet = {\n types: ['google.protobuf.Timestamp'],\n\n [ConverterType.TO_JSON]: {\n transform: (val: Date | string) => {\n if (typeof val === 'string' || !val) {\n return val;\n }\n return val.toISOString();\n },\n },\n\n [ConverterType.FROM_JSON]: {\n transform: (val: string) => (val ? new Date(val) : val),\n },\n};\n","import { ConverterSet, ConverterType } from '../domain';\n\nexport const fieldMask: ConverterSet = {\n types: ['google.protobuf.FieldMask'],\n\n [ConverterType.TO_JSON]: {\n transform: (val: string[]) => val.join(','),\n\n /**\n * This one handles cases where we have a repeated google.protobuf.FieldMask type,\n * so it will look like: [['foo', 'bar'], ['qux']].\n *\n * The problem is that the serializer detects it as an array with actual fields (strings),\n * while in practice it is an array of multiple google.protobuf.FieldMask.\n *\n * We should determine if the items are actual fields (so each item is a string),\n * or arrays of google.protobuf.FieldMask (so each item is array that has items with fields).\n *\n * Another approach could be marking on the schama itseld each field if it's a repeatable or not,\n * it's not a good appraoch, but as long as google.protobuf.FieldMask is our only issue, it's\n * not _that_ bad solution.\n */\n checkRepetable: (val: string[] | string[][]) => {\n return val.some((v: string | string[]) => Array.isArray(v));\n },\n },\n\n [ConverterType.FROM_JSON]: {\n transform: (val: string | { paths: string[] }) => {\n /**\n * Support Scala FW JSON mapping bug, for more details see:\n *\n * https://github.com/wix-private/server-infra/issues/17953\n */\n if (typeof val === 'object') {\n return val.paths;\n }\n\n return val.split(',');\n },\n },\n};\n","import { ConverterSet, ConverterType } from '../domain';\n\nexport const bytes: ConverterSet = {\n types: ['google.protobuf.BytesValue', 'BYTES'],\n\n [ConverterType.TO_JSON]: {\n transform: (val: number[]) => {\n const chars = val.reduce((res, c) => res + String.fromCharCode(c), '');\n\n return btoa(chars);\n },\n },\n\n [ConverterType.FROM_JSON]: {\n transform: (val: string) => {\n return Uint8Array.from(atob(val), (c) => c.charCodeAt(0));\n },\n },\n};\n","import { ConverterSet, ConverterType } from '../domain';\nimport { GoogleProtoDuration } from './types';\n\nexport const duration: ConverterSet = {\n types: ['google.protobuf.Duration'],\n\n [ConverterType.TO_JSON]: {\n transform: ({ seconds = '0', nanos = 0 }: GoogleProtoDuration) => {\n let nanosPortion = '';\n\n if (nanos !== 0) {\n nanosPortion = `.${nanos.toString().padStart(9, '0')}`;\n }\n\n return `${seconds}${nanosPortion}s`;\n },\n },\n\n [ConverterType.FROM_JSON]: {\n transform: (val: string): GoogleProtoDuration => {\n const [seconds, nanos] = val.substring(0, val.length - 1).split('.');\n\n return {\n seconds,\n nanos: nanosForString(nanos),\n };\n },\n },\n};\n\nfunction nanosForString(nanos: string) {\n let res = 0;\n\n if (nanos !== undefined) {\n const precision = 3 - nanos.length / 3;\n res = parseInt(nanos, 10) * Math.pow(1000, precision);\n }\n\n return res;\n}\n","import { ConverterSet, ConverterType } from '../domain';\n\nexport const float: ConverterSet = {\n types: [\n 'FLOAT',\n 'DOUBLE',\n 'google.protobuf.FloatValue',\n 'google.protobuf.DoubleValue',\n ],\n\n [ConverterType.TO_JSON]: {\n transform: (val: number) => {\n return isFinite(val) ? val : val.toString();\n },\n },\n\n [ConverterType.FROM_JSON]: {\n transform: (val: string | number) => {\n if (val === 'NaN') {\n return NaN;\n }\n\n if (val === 'Infinity') {\n return Infinity;\n }\n\n if (val === '-Infinity') {\n return -Infinity;\n }\n\n return val;\n },\n },\n};\n","import { TypeToConverterSet, ConverterSet } from './domain';\n\nexport function typeToConverterSet(\n converterSets: ConverterSet[],\n): TypeToConverterSet {\n return converterSets.reduce((result, converterSet) => {\n const types = converterSet.types.reduce((typeResult, type) => {\n return {\n ...typeResult,\n [type]: converterSet,\n };\n }, {} as TypeToConverterSet);\n\n return {\n ...result,\n ...types,\n };\n }, {} as TypeToConverterSet);\n}\n",null,"import { CliError, CliErrorCode } from '@wix/cli-error';\nimport type { IHttpClient, Headers } from '@wix/http-client';\nimport { createHttpClient as createHttpClientOriginal } from '@wix/http-client';\nimport { isHttpError } from './is-http-error.js';\n\nexport interface CreateHttpClientOptions {\n getAppToken?: () => Promise<string>;\n createHeaders?: () => Headers;\n\n type: keyof typeof baseUrls;\n}\n\nconst baseUrls = {\n backoffice: 'https://manage.wix.com',\n editor: 'https://editor.wix.com',\n code: 'https://code.wix.com',\n general: 'https://www.wix.com',\n api: 'https://www.wixapis.com',\n standalone: undefined,\n};\n\nfunction interceptRequest<P extends unknown[], R>(\n client: IHttpClient,\n fn: (...args: P) => Promise<R>\n) {\n return (...args: P) =>\n fn.apply(client, args).catch((error: unknown) => {\n if (isHttpError(error) && !client.isCancel(error) && !error.response) {\n // Network error\n throw new CliError({\n code: CliErrorCode.NetworkError(),\n cause: error,\n info: { code: error.code },\n });\n }\n\n throw error;\n });\n}\n\nexport function createHttpClient({\n getAppToken,\n createHeaders,\n type,\n}: CreateHttpClientOptions): IHttpClient {\n const client = createHttpClientOriginal({\n baseURL: baseUrls[type],\n ...(type !== 'standalone'\n ? {\n getAppToken,\n }\n : {}),\n createHeaders: () => ({\n ...createHeaders?.(),\n // See https://wix.slack.com/archives/C0JLGMT28/p1667219337530909\n 'X-XSRF-TOKEN': 'nocheck',\n Cookie: 'XSRF-TOKEN=nocheck',\n 'User-Agent': 'wix-cli',\n }),\n });\n\n return {\n ...client,\n request: interceptRequest(client, client.request),\n get: interceptRequest(client, client.get),\n delete: interceptRequest(client, client.delete),\n head: interceptRequest(client, client.head),\n options: interceptRequest(client, client.options),\n post: interceptRequest(client, client.post),\n put: interceptRequest(client, client.put),\n patch: interceptRequest(client, client.patch),\n };\n}\n","import { z } from 'zod';\nimport type { IHttpError } from '@wix/http-client';\nimport { HttpClient } from '@wix/http-client';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\n\ntype HttpErrorResponse =\n | {\n message?: string;\n error?: string;\n details?: {\n applicationError?: object;\n validationError?: object;\n };\n }\n | undefined;\n\nexport function isHttpError(\n error: unknown\n): error is IHttpError<HttpErrorResponse> {\n return HttpClient.isHttpError(error);\n}\n\nconst validationErrorSchema = z.object({\n details: z.object({\n validationError: z.object({\n fieldViolations: z\n .array(\n z.object({\n description: z.string(),\n field: z.string(),\n })\n )\n .nonempty(),\n }),\n }),\n});\n\ntype HttpValidationErrorResponse = z.infer<typeof validationErrorSchema>;\n\nexport function isHttpValidationError(\n error: IHttpError<HttpErrorResponse>\n): error is IHttpError<HttpValidationErrorResponse> {\n if (error.response?.data?.details?.validationError) {\n const result = validationErrorSchema.safeParse(error.response.data);\n\n if (result.success) {\n return true;\n }\n\n throw new CliError({\n cause: error,\n code: CliErrorCode.FailedToParseHttpErrorResponse(),\n info: {\n zodError: result.error,\n },\n });\n }\n\n return false;\n}\n\nconst applicationErrorSchema = z.object({\n details: z.object({\n applicationError: z.object({\n code: z.string(),\n data: z\n .object({\n appNotInstalled: z\n .object({\n appId: z.string(),\n })\n .optional(),\n })\n .optional(),\n }),\n }),\n});\n\ntype HttpApplicationErrorResponse = z.infer<typeof applicationErrorSchema>;\n\nexport function isHttpApplicationError(\n error: IHttpError<HttpErrorResponse>\n): error is IHttpError<HttpApplicationErrorResponse> {\n if (error.response?.data?.details?.applicationError) {\n const result = applicationErrorSchema.safeParse(error.response.data);\n\n if (result.success) {\n return true;\n }\n\n throw new CliError({\n cause: error,\n code: CliErrorCode.FailedToParseHttpErrorResponse(),\n info: {\n zodError: result.error,\n },\n });\n }\n\n return false;\n}\n","import type { IHttpError } from '@wix/http-client';\nimport { HttpClient } from '@wix/http-client';\nimport VError from 'verror';\n\nexport function extractHttpError(error: unknown): IHttpError | null {\n if (HttpClient.isHttpError(error)) {\n return error;\n }\n\n const nestedError = error instanceof Error ? VError.cause(error) : null;\n return nestedError ? extractHttpError(nestedError) : null;\n}\n","import type { IHttpError } from '@wix/http-client';\n\nexport function getHttpErrorInfo(httpError: IHttpError) {\n return {\n request: {\n baseURL: httpError.config.baseURL,\n url: httpError.config.url,\n method: httpError.config.method,\n headers: httpError.config.headers,\n data: httpError.config.data,\n },\n response: {\n code: httpError.code,\n message: httpError.message,\n status: httpError.response?.status,\n headers: httpError.response?.headers,\n data: httpError.response?.data,\n },\n } as const;\n}\n","import { z } from 'zod';\n\nexport const deviceCodeSchema = z.object({\n deviceCode: z.string(),\n verificationUri: z.string().url(),\n userCode: z.string(),\n expiresIn: z.number(),\n});\n\nexport type DeviceCodeResponse = z.TypeOf<typeof deviceCodeSchema>;\n\nexport const tokenSchema = z\n .object({\n access_token: z.string(),\n refresh_token: z.string(),\n expires_in: z.number(),\n })\n .transform((token) => ({\n accessToken: token.access_token,\n refreshToken: token.refresh_token,\n expiresIn: token.expires_in,\n }));\n\nexport const userInfoSchema = z.object({\n userId: z.string().uuid(),\n email: z.string().email(),\n});\n\nexport type UserInfo = z.TypeOf<typeof userInfoSchema>;\n\nexport const getMyAccountSchema = z.object({\n account: z.object({\n slug: z.string(),\n accountId: z.string().uuid(),\n accountOwner: z.string().uuid(),\n }),\n});\n\nexport const siteAuthSchema = z.object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresIn: z.number(),\n issuedAt: z.number(),\n});\n\nexport type SiteAuth = z.TypeOf<typeof siteAuthSchema>;\n\nexport const accountAuthSchema = siteAuthSchema.extend({\n userInfo: userInfoSchema,\n});\n\nexport type AccountAuth = z.TypeOf<typeof accountAuthSchema>;\n\nexport const apiKeyAuthSchema = z.object({\n token: z.string(),\n accountId: z.string().uuid(),\n userInfo: z.object({\n userId: z.string().uuid(),\n email: z.string(),\n }),\n});\n\nexport type ApiKeyAuth = z.TypeOf<typeof apiKeyAuthSchema>;\n","import { unlink, rm } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { getDataDirPath } from '@wix/cli-data-dir';\nimport type { VariantOf } from 'variant';\nimport { match, fields, variant, payload, isType } from 'variant';\nimport { pathExists, readJson, writeJson } from '@wix/cli-fs';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport type { ApiKeyAuth, AccountAuth, SiteAuth, UserInfo } from './schemas.js';\nimport {\n apiKeyAuthSchema,\n accountAuthSchema,\n siteAuthSchema,\n} from './schemas.js';\n\nfunction getLegacyAuthDataFilePath() {\n return resolve(getDataDirPath(), 'auth.json');\n}\n\nfunction getAuthDataFolder() {\n return resolve(getDataDirPath(), 'auth');\n}\n\nfunction getApiKeyAuthDataFilePath() {\n return resolve(getAuthDataFolder(), 'api-key.json');\n}\n\nfunction getAccountAuthDataFilePath() {\n return resolve(getAuthDataFolder(), 'account.json');\n}\n\nfunction getSiteAuthDataFilePath(siteId: string) {\n return resolve(getAuthDataFolder(), `${siteId}.json`);\n}\n\nconst ApiKeyAuthData = variant({\n Authenticated: payload<ApiKeyAuth>(),\n Unauthenticated: {},\n});\n\ntype ApiKeyAuthData = VariantOf<typeof ApiKeyAuthData>;\n\nexport async function readApiKeyAuthData(): Promise<ApiKeyAuthData> {\n const apiKeyAuthDataFilePath = getApiKeyAuthDataFilePath();\n\n if (!(await pathExists(apiKeyAuthDataFilePath))) {\n return ApiKeyAuthData.Unauthenticated();\n }\n\n const apiKeyFileContents = await readJson(apiKeyAuthDataFilePath);\n const savedApiKeyAuthData = apiKeyAuthSchema.parse(apiKeyFileContents);\n\n return ApiKeyAuthData.Authenticated(savedApiKeyAuthData);\n}\n\nexport async function saveApiKeyAuthData(authData: ApiKeyAuth) {\n try {\n const targetFilePath = getApiKeyAuthDataFilePath();\n\n await writeJson(targetFilePath, authData);\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToSaveApiKeyAuthData(),\n cause: error,\n });\n }\n}\n\nexport const AccountAuthData = variant({\n Authenticated: fields<AccountAuth>(),\n Unauthenticated: {},\n Expired: fields<AccountAuth>(),\n});\nexport type AccountAuthData = VariantOf<typeof AccountAuthData>;\n\nexport async function readAccountAuthData(): Promise<AccountAuthData> {\n const accountAuthDataFilePath = getAccountAuthDataFilePath();\n\n if (!(await pathExists(accountAuthDataFilePath))) {\n return AccountAuthData.Unauthenticated();\n }\n\n const authFileContents = await readJson(accountAuthDataFilePath);\n const savedAccountAuthData = accountAuthSchema.parse(authFileContents);\n\n if (!isValidToken(savedAccountAuthData)) {\n return AccountAuthData.Expired(savedAccountAuthData);\n }\n\n return AccountAuthData.Authenticated(savedAccountAuthData);\n}\n\nconst SiteAuthData = variant({\n Authenticated: fields<SiteAuth>(),\n Unauthenticated: {},\n Expired: fields<SiteAuth>(),\n});\n\ntype SiteAuthData = VariantOf<typeof SiteAuthData>;\n\nexport async function readSiteAuthData(siteId: string): Promise<SiteAuthData> {\n const siteAuthDataFilePath = getSiteAuthDataFilePath(siteId);\n\n if (!(await pathExists(siteAuthDataFilePath))) {\n return SiteAuthData.Unauthenticated();\n }\n\n const authFileContents = await readJson(siteAuthDataFilePath);\n const savedSiteAuthData = siteAuthSchema.parse(authFileContents);\n\n if (!isValidToken(savedSiteAuthData)) {\n return SiteAuthData.Expired(savedSiteAuthData);\n }\n\n return SiteAuthData.Authenticated(savedSiteAuthData);\n}\n\nexport async function saveAuthData(\n authData: AccountAuth | SiteAuth,\n siteId?: string\n) {\n try {\n const targetFilePath = siteId\n ? getSiteAuthDataFilePath(siteId)\n : getAccountAuthDataFilePath();\n\n await writeJson(targetFilePath, authData);\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToSaveAuthData(),\n cause: error,\n });\n }\n}\n\nexport async function deleteAuthData() {\n try {\n await rm(getAuthDataFolder(), { recursive: true, force: true });\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToDeleteAuthData(),\n cause: error,\n });\n }\n\n if (await hasLegacyAuthData()) {\n await deleteLegacyAuthData();\n }\n}\n\nasync function deleteLegacyAuthData() {\n try {\n await unlink(getLegacyAuthDataFilePath());\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToDeleteLegacyAuthData(),\n cause: error,\n });\n }\n}\n\nexport async function hasLegacyAuthData() {\n return pathExists(getLegacyAuthDataFilePath());\n}\n\nexport function isValidToken(authData: {\n expiresIn: number;\n issuedAt: number;\n}): boolean {\n const currentTimestamp = Math.floor(Date.now() / 1000);\n const tokenOffset = 10 * 60; // 10 minutes\n const tokenLifetime = authData.expiresIn - tokenOffset;\n const tokenGenerationTimestamp = authData.issuedAt;\n\n return tokenGenerationTimestamp + tokenLifetime > currentTimestamp;\n}\n\nexport async function getUserInfo(): Promise<UserInfo | null> {\n const apiKeyAuthData = await readApiKeyAuthData();\n\n if (isType(apiKeyAuthData, ApiKeyAuthData.Authenticated)) {\n return apiKeyAuthData.payload.userInfo;\n }\n\n const accountAuthData = await readAccountAuthData();\n return match(accountAuthData, {\n Authenticated: ({ userInfo }) => userInfo,\n Expired: ({ userInfo }) => userInfo,\n Unauthenticated: () => null,\n });\n}\n","import pLimit from 'p-limit';\nimport { match, constant, isType } from 'variant';\nimport pWaitFor, { TimeoutError } from 'p-wait-for';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\nimport type { AccountAuth, DeviceCodeResponse } from '../schemas.js';\nimport {\n client,\n RenewTokenData,\n DeviceCodeNotYetVerifiedError,\n} from '../client.js';\nimport {\n isValidToken,\n deleteAuthData,\n readAccountAuthData,\n saveAuthData,\n} from '../auth-data.js';\nimport type { AuthStrategyState, AuthStrategy } from './auth-strategy-types.js';\nimport { apiKeyAuthStrategy } from './api-key-auth-strategy.js';\n\nconst seconds = (n: number) => 1000 * n;\n\nasync function waitForLogin(\n { deviceCode, expiresIn }: DeviceCodeResponse,\n { signal }: { signal: AbortSignal }\n) {\n try {\n const authData = await pWaitFor(\n async () => {\n try {\n const tokenData = await client.createToken({\n deviceCode,\n });\n\n return pWaitFor.resolveWith(tokenData);\n } catch (error) {\n if (error instanceof DeviceCodeNotYetVerifiedError) {\n // continue polling\n return false;\n }\n\n throw error;\n }\n },\n {\n interval: getTestOverrides().waitForLoginInterval ?? seconds(3),\n timeout: { milliseconds: seconds(expiresIn), signal },\n }\n );\n\n const userInfo = await client.userInfo({\n accessToken: authData.accessToken,\n });\n\n const result = { ...authData, userInfo };\n\n await deleteAuthData();\n await saveAuthData(result);\n\n return result;\n } catch (error) {\n if (error instanceof TimeoutError) {\n throw new CliError({\n code: CliErrorCode.DeviceCodeTimedOut(),\n cause: error,\n });\n }\n\n throw error;\n }\n}\n\nasync function renewAccountAuth({ refreshToken, userInfo }: AccountAuth) {\n const renewTokenResult = await client.renewToken({ refreshToken });\n\n if (isType(renewTokenResult, RenewTokenData.TokenRenewed)) {\n await saveAuthData({ ...renewTokenResult.payload, userInfo });\n }\n\n return renewTokenResult;\n}\n\nasync function getNonExpiredAccountAuth(): Promise<AccountAuth | null> {\n const accountAuthStatus = await readAccountAuthData();\n\n return match(accountAuthStatus, {\n Authenticated: (accountAuth) => accountAuth,\n Unauthenticated: () => null,\n Expired: async (accountAuth) => {\n const renewTokenResult = await renewAccountAuth(accountAuth);\n\n return match(renewTokenResult, {\n TokenRenewed: ({ payload: newTokenData }) => ({\n ...newTokenData,\n userInfo: accountAuth.userInfo,\n }),\n RefreshTokenRevoked: constant(null),\n });\n },\n });\n}\n\nfunction createAccountAuthState({\n userInfo,\n ...initialTokenData\n}: AccountAuth): AuthStrategyState {\n const limiter = pLimit(1);\n let tokenData = { ...initialTokenData };\n\n return {\n getAccessToken: () => {\n return limiter(async () => {\n if (isValidToken(tokenData)) {\n return tokenData.accessToken;\n }\n\n const renewTokenResult = await renewAccountAuth({\n ...tokenData,\n userInfo,\n });\n\n return match(renewTokenResult, {\n TokenRenewed: ({ payload: newTokenData }) => {\n tokenData = newTokenData;\n return tokenData.accessToken;\n },\n RefreshTokenRevoked: ({ cause }) => {\n throw new CliError({\n code: CliErrorCode.FailedToRenewAuthTokenRefreshTokenRevoked(),\n cause,\n });\n },\n });\n });\n },\n getRefreshToken: () => tokenData.refreshToken,\n userInfo,\n };\n}\n\nexport const accountAuthStrategy: AuthStrategy = {\n async isLoggedIn() {\n const apiKeyAuth = await apiKeyAuthStrategy.isLoggedIn();\n\n if (apiKeyAuth) {\n return apiKeyAuth;\n }\n\n const accountAuth = await getNonExpiredAccountAuth();\n\n if (accountAuth) {\n return createAccountAuthState(accountAuth);\n }\n\n return null;\n },\n async login({ deviceCode, signal }) {\n const accountAuth = await waitForLogin(deviceCode, { signal });\n\n return createAccountAuthState(accountAuth);\n },\n};\n","import Queue from 'yocto-queue';\n\nexport default function pLimit(concurrency) {\n\tvalidateConcurrency(concurrency);\n\n\tconst queue = new Queue();\n\tlet activeCount = 0;\n\n\tconst resumeNext = () => {\n\t\tif (activeCount < concurrency && queue.size > 0) {\n\t\t\tqueue.dequeue()();\n\t\t\t// Since `pendingCount` has been decreased by one, increase `activeCount` by one.\n\t\t\tactiveCount++;\n\t\t}\n\t};\n\n\tconst next = () => {\n\t\tactiveCount--;\n\n\t\tresumeNext();\n\t};\n\n\tconst run = async (function_, resolve, arguments_) => {\n\t\tconst result = (async () => function_(...arguments_))();\n\n\t\tresolve(result);\n\n\t\ttry {\n\t\t\tawait result;\n\t\t} catch {}\n\n\t\tnext();\n\t};\n\n\tconst enqueue = (function_, resolve, arguments_) => {\n\t\t// Queue `internalResolve` instead of the `run` function\n\t\t// to preserve asynchronous context.\n\t\tnew Promise(internalResolve => {\n\t\t\tqueue.enqueue(internalResolve);\n\t\t}).then(\n\t\t\trun.bind(undefined, function_, resolve, arguments_),\n\t\t);\n\n\t\t(async () => {\n\t\t\t// This function needs to wait until the next microtask before comparing\n\t\t\t// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously\n\t\t\t// after the `internalResolve` function is dequeued and called. The comparison in the if-statement\n\t\t\t// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.\n\t\t\tawait Promise.resolve();\n\n\t\t\tif (activeCount < concurrency) {\n\t\t\t\tresumeNext();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst generator = (function_, ...arguments_) => new Promise(resolve => {\n\t\tenqueue(function_, resolve, arguments_);\n\t});\n\n\tObject.defineProperties(generator, {\n\t\tactiveCount: {\n\t\t\tget: () => activeCount,\n\t\t},\n\t\tpendingCount: {\n\t\t\tget: () => queue.size,\n\t\t},\n\t\tclearQueue: {\n\t\t\tvalue() {\n\t\t\t\tqueue.clear();\n\t\t\t},\n\t\t},\n\t\tconcurrency: {\n\t\t\tget: () => concurrency,\n\n\t\t\tset(newConcurrency) {\n\t\t\t\tvalidateConcurrency(newConcurrency);\n\t\t\t\tconcurrency = newConcurrency;\n\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\t// eslint-disable-next-line no-unmodified-loop-condition\n\t\t\t\t\twhile (activeCount < concurrency && queue.size > 0) {\n\t\t\t\t\t\tresumeNext();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t},\n\t});\n\n\treturn generator;\n}\n\nexport function limitFunction(function_, option) {\n\tconst {concurrency} = option;\n\tconst limit = pLimit(concurrency);\n\n\treturn (...arguments_) => limit(() => function_(...arguments_));\n}\n\nfunction validateConcurrency(concurrency) {\n\tif (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {\n\t\tthrow new TypeError('Expected `concurrency` to be a number from 1 and up');\n\t}\n}\n","/*\nHow it works:\n`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.\n*/\n\nclass Node {\n\tvalue;\n\tnext;\n\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n}\n\nexport default class Queue {\n\t#head;\n\t#tail;\n\t#size;\n\n\tconstructor() {\n\t\tthis.clear();\n\t}\n\n\tenqueue(value) {\n\t\tconst node = new Node(value);\n\n\t\tif (this.#head) {\n\t\t\tthis.#tail.next = node;\n\t\t\tthis.#tail = node;\n\t\t} else {\n\t\t\tthis.#head = node;\n\t\t\tthis.#tail = node;\n\t\t}\n\n\t\tthis.#size++;\n\t}\n\n\tdequeue() {\n\t\tconst current = this.#head;\n\t\tif (!current) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#head = this.#head.next;\n\t\tthis.#size--;\n\t\treturn current.value;\n\t}\n\n\tpeek() {\n\t\tif (!this.#head) {\n\t\t\treturn;\n\t\t}\n\n\t\treturn this.#head.value;\n\n\t\t// TODO: Node.js 18.\n\t\t// return this.#head?.value;\n\t}\n\n\tclear() {\n\t\tthis.#head = undefined;\n\t\tthis.#tail = undefined;\n\t\tthis.#size = 0;\n\t}\n\n\tget size() {\n\t\treturn this.#size;\n\t}\n\n\t* [Symbol.iterator]() {\n\t\tlet current = this.#head;\n\n\t\twhile (current) {\n\t\t\tyield current.value;\n\t\t\tcurrent = current.next;\n\t\t}\n\t}\n}\n","import pTimeout from 'p-timeout';\n\nconst resolveValue = Symbol('resolveValue');\n\nexport default async function pWaitFor(condition, options = {}) {\n\tconst {\n\t\tinterval = 20,\n\t\ttimeout = Number.POSITIVE_INFINITY,\n\t\tbefore = true,\n\t} = options;\n\n\tlet retryTimeout;\n\tlet abort = false;\n\n\tconst promise = new Promise((resolve, reject) => {\n\t\tconst check = async () => {\n\t\t\ttry {\n\t\t\t\tconst value = await condition();\n\n\t\t\t\tif (typeof value === 'object' && value[resolveValue]) {\n\t\t\t\t\tresolve(value[resolveValue]);\n\t\t\t\t} else if (typeof value !== 'boolean') {\n\t\t\t\t\tthrow new TypeError('Expected condition to return a boolean');\n\t\t\t\t} else if (value === true) {\n\t\t\t\t\tresolve();\n\t\t\t\t} else if (!abort) {\n\t\t\t\t\tretryTimeout = setTimeout(check, interval);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t};\n\n\t\tif (before) {\n\t\t\tcheck();\n\t\t} else {\n\t\t\tretryTimeout = setTimeout(check, interval);\n\t\t}\n\t});\n\n\tif (timeout === Number.POSITIVE_INFINITY) {\n\t\treturn promise;\n\t}\n\n\ttry {\n\t\treturn await pTimeout(promise, typeof timeout === 'number' ? {milliseconds: timeout} : timeout);\n\t} finally {\n\t\tabort = true;\n\t\tclearTimeout(retryTimeout);\n\t}\n}\n\npWaitFor.resolveWith = value => ({[resolveValue]: value});\n\nexport {TimeoutError} from 'p-timeout';\n","export class TimeoutError extends Error {\n\tconstructor(message) {\n\t\tsuper(message);\n\t\tthis.name = 'TimeoutError';\n\t}\n}\n\n/**\nAn error to be thrown when the request is aborted by AbortController.\nDOMException is thrown instead of this Error when DOMException is available.\n*/\nexport class AbortError extends Error {\n\tconstructor(message) {\n\t\tsuper();\n\t\tthis.name = 'AbortError';\n\t\tthis.message = message;\n\t}\n}\n\n/**\nTODO: Remove AbortError and just throw DOMException when targeting Node 18.\n*/\nconst getDOMException = errorMessage => globalThis.DOMException === undefined\n\t? new AbortError(errorMessage)\n\t: new DOMException(errorMessage);\n\n/**\nTODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.\n*/\nconst getAbortedReason = signal => {\n\tconst reason = signal.reason === undefined\n\t\t? getDOMException('This operation was aborted.')\n\t\t: signal.reason;\n\n\treturn reason instanceof Error ? reason : getDOMException(reason);\n};\n\nexport default function pTimeout(promise, options) {\n\tconst {\n\t\tmilliseconds,\n\t\tfallback,\n\t\tmessage,\n\t\tcustomTimers = {setTimeout, clearTimeout},\n\t} = options;\n\n\tlet timer;\n\tlet abortHandler;\n\n\tconst wrappedPromise = new Promise((resolve, reject) => {\n\t\tif (typeof milliseconds !== 'number' || Math.sign(milliseconds) !== 1) {\n\t\t\tthrow new TypeError(`Expected \\`milliseconds\\` to be a positive number, got \\`${milliseconds}\\``);\n\t\t}\n\n\t\tif (options.signal) {\n\t\t\tconst {signal} = options;\n\t\t\tif (signal.aborted) {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t}\n\n\t\t\tabortHandler = () => {\n\t\t\t\treject(getAbortedReason(signal));\n\t\t\t};\n\n\t\t\tsignal.addEventListener('abort', abortHandler, {once: true});\n\t\t}\n\n\t\tif (milliseconds === Number.POSITIVE_INFINITY) {\n\t\t\tpromise.then(resolve, reject);\n\t\t\treturn;\n\t\t}\n\n\t\t// We create the error outside of `setTimeout` to preserve the stack trace.\n\t\tconst timeoutError = new TimeoutError();\n\n\t\ttimer = customTimers.setTimeout.call(undefined, () => {\n\t\t\tif (fallback) {\n\t\t\t\ttry {\n\t\t\t\t\tresolve(fallback());\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (typeof promise.cancel === 'function') {\n\t\t\t\tpromise.cancel();\n\t\t\t}\n\n\t\t\tif (message === false) {\n\t\t\t\tresolve();\n\t\t\t} else if (message instanceof Error) {\n\t\t\t\treject(message);\n\t\t\t} else {\n\t\t\t\ttimeoutError.message = message ?? `Promise timed out after ${milliseconds} milliseconds`;\n\t\t\t\treject(timeoutError);\n\t\t\t}\n\t\t}, milliseconds);\n\n\t\t(async () => {\n\t\t\ttry {\n\t\t\t\tresolve(await promise);\n\t\t\t} catch (error) {\n\t\t\t\treject(error);\n\t\t\t}\n\t\t})();\n\t});\n\n\tconst cancelablePromise = wrappedPromise.finally(() => {\n\t\tcancelablePromise.clear();\n\t\tif (abortHandler && options.signal) {\n\t\t\toptions.signal.removeEventListener('abort', abortHandler);\n\t\t}\n\t});\n\n\tcancelablePromise.clear = () => {\n\t\tcustomTimers.clearTimeout.call(undefined, timer);\n\t\ttimer = undefined;\n\t};\n\n\treturn cancelablePromise;\n}\n","import pLimit from 'p-limit';\nimport { match, matcher, variant, payload, fields, isType } from 'variant';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport type { HttpError } from '@wix/cli-http-client';\nimport type { SiteAuth, UserInfo } from '../schemas.js';\nimport { client, RenewTokenData } from '../client.js';\nimport { isValidToken, readSiteAuthData, saveAuthData } from '../auth-data.js';\nimport type { AuthStrategyState, AuthStrategy } from './auth-strategy-types.js';\nimport { apiKeyAuthStrategy } from './api-key-auth-strategy.js';\nimport { accountAuthStrategy } from './account-auth-strategy.js';\n\nasync function renewSiteAuth({\n accountRefreshToken,\n siteId,\n}: {\n accountRefreshToken: string;\n siteId: string;\n}) {\n const renewTokenResult = await client.renewToken({\n refreshToken: accountRefreshToken,\n siteId,\n });\n\n if (isType(renewTokenResult, RenewTokenData.TokenRenewed)) {\n await saveAuthData(renewTokenResult.payload, siteId);\n }\n\n return renewTokenResult;\n}\n\nconst AuthenticationResult = variant({\n Ok: payload<SiteAuth>(),\n RefreshTokenRevoked: fields<{ cause: HttpError }>(),\n});\nasync function ensureAuthenticatedToSite({\n siteId,\n accountRefreshToken,\n}: {\n siteId: string;\n accountRefreshToken: string;\n}) {\n const siteAuthStatus = await readSiteAuthData(siteId);\n\n return matcher(siteAuthStatus)\n .with({ Authenticated: (data) => AuthenticationResult.Ok(data) })\n .when(['Unauthenticated', 'Expired'], async () => {\n const renewTokenResult = await renewSiteAuth({\n accountRefreshToken,\n siteId,\n });\n\n return match(renewTokenResult, {\n TokenRenewed: ({ payload }) => AuthenticationResult.Ok(payload),\n RefreshTokenRevoked: ({ cause }) => {\n return AuthenticationResult.RefreshTokenRevoked({ cause });\n },\n });\n })\n .complete();\n}\n\nfunction createSiteAuthState({\n siteAuth: initialTokenData,\n accountRefreshToken,\n siteId,\n userInfo,\n}: {\n siteId: string;\n accountRefreshToken: string;\n userInfo: UserInfo;\n siteAuth: SiteAuth;\n}): AuthStrategyState {\n const limiter = pLimit(1);\n let tokenData = { ...initialTokenData };\n\n return {\n getAccessToken: () => {\n return limiter(async () => {\n if (isValidToken(tokenData)) {\n return tokenData.accessToken;\n }\n\n const renewTokenResult = await renewSiteAuth({\n accountRefreshToken,\n siteId,\n });\n\n return match(renewTokenResult, {\n TokenRenewed: ({ payload: newTokenData }) => {\n tokenData = newTokenData;\n return tokenData.accessToken;\n },\n RefreshTokenRevoked: ({ cause }) => {\n throw new CliError({\n code: CliErrorCode.FailedToRenewAuthTokenRefreshTokenRevoked(),\n cause,\n });\n },\n });\n });\n },\n getRefreshToken: () => tokenData.refreshToken,\n userInfo,\n };\n}\n\nexport const createSiteAuthStrategy = (siteId: string): AuthStrategy => ({\n async isLoggedIn() {\n const apiKeyAuth = await apiKeyAuthStrategy.isLoggedIn({ siteId });\n\n if (apiKeyAuth) {\n return apiKeyAuth;\n }\n\n const accountAuth = await accountAuthStrategy.isLoggedIn();\n\n if (accountAuth) {\n const accountRefreshToken = accountAuth.getRefreshToken();\n const siteAuthResult = await ensureAuthenticatedToSite({\n siteId,\n accountRefreshToken,\n });\n\n if (isType(siteAuthResult, AuthenticationResult.Ok)) {\n return createSiteAuthState({\n siteId,\n siteAuth: siteAuthResult.payload,\n accountRefreshToken,\n userInfo: accountAuth.userInfo,\n });\n }\n }\n\n return null;\n },\n async login({ deviceCode, signal }) {\n const accountAuth = await accountAuthStrategy.login({ deviceCode, signal });\n const accountRefreshToken = accountAuth.getRefreshToken();\n const siteAuthResult = await ensureAuthenticatedToSite({\n siteId,\n accountRefreshToken,\n });\n\n return match(siteAuthResult, {\n Ok: ({ payload: siteAuth }) => {\n return createSiteAuthState({\n siteId,\n siteAuth,\n accountRefreshToken,\n userInfo: accountAuth.userInfo,\n });\n },\n RefreshTokenRevoked: ({ cause }) => {\n throw new CliError({\n code: CliErrorCode.FailedToRenewAuthTokenRefreshTokenRevoked(),\n cause,\n });\n },\n });\n },\n});\n","import { isType } from 'variant';\nimport {\n deleteAuthData,\n readAccountAuthData,\n AccountAuthData,\n} from './auth-data.js';\nimport { client } from './client.js';\n\nexport async function logout() {\n const authData = await readAccountAuthData();\n if (!isType(authData, AccountAuthData.Unauthenticated)) {\n await client.revokeRefreshToken(\n { token: authData.refreshToken },\n authData.userInfo\n );\n }\n\n await deleteAuthData();\n\n return null;\n}\n","import { useContext } from 'react';\nimport { AuthContext } from './context.js';\nimport type { AuthState } from './context.js';\n\nexport function useAuth(): AuthState {\n const context = useContext(AuthContext);\n\n if (!context) {\n throw new Error('useAuth() cannot be used without an <AuthProvider>');\n }\n\n return context;\n}\n","import { createContext } from 'react';\nimport type { AuthStrategyState } from './auth-strategies/index.js';\n\nexport type AuthState = Pick<\n AuthStrategyState,\n 'getAccessToken' | 'getRequestHeaders' | 'userInfo'\n>;\n\nexport const AuthContext = createContext<AuthState | null>(null);\n","import React from 'react';\nimport type { FC } from 'react';\nimport { Spinner, useAsync } from '@wix/cli-ui-kit';\nimport { useBiLogger } from '@wix/cli-telemetry-react';\nimport { wixCliLoginStart, wixCliLoginEnd } from '@wix/bi-logger-wix-cli/v2';\nimport { match } from 'variant';\nimport { apiKeyAuthStrategy } from '../auth-strategies/index.js';\nimport type { AuthStrategyState } from '../auth-strategies/index.js';\n\ninterface Props {\n token: string;\n onLogin: (data: AuthStrategyState) => void;\n onError: (error: unknown) => void;\n}\n\nexport const ApiKeyLogin: FC<Props> = ({ token, onLogin, onError }) => {\n const biLogger = useBiLogger();\n\n const { status } = useAsync(\n async () => {\n void biLogger.report(wixCliLoginStart({}));\n\n return apiKeyAuthStrategy.login({ token });\n },\n [],\n {\n onSuccess: (authData) => {\n void biLogger.report(\n wixCliLoginEnd({\n isSuccess: true,\n })\n );\n onLogin(authData);\n },\n onError: (error) => {\n void biLogger.report(\n wixCliLoginEnd({\n isSuccess: false,\n ...(error instanceof Error\n ? {\n errorType: error.name,\n }\n : {\n errorType: 'unknown',\n errorMessage: JSON.stringify(error),\n }),\n })\n );\n\n onError(error);\n },\n }\n );\n\n return match(status, {\n Error: () => null,\n Loading: () => <Spinner />,\n Success: () => null,\n });\n};\n","export { useBiLogger, BiProvider } from './useBi.js';\n","import type { ReactNode } from 'react';\nimport React, { createContext, useContext } from 'react';\nimport type { BiLogger } from '@wix/cli-telemetry';\n\nconst BiContext = createContext<BiLogger | null>(null);\n\nexport const BiProvider = function ({\n children,\n value: biLogger,\n}: {\n children: ReactNode;\n value: BiLogger;\n}) {\n return <BiContext.Provider value={biLogger}>{children}</BiContext.Provider>;\n};\n\nexport const useBiLogger = (): BiLogger => {\n const context = useContext(BiContext);\n\n if (context == null) {\n throw new Error('useBiLogger() cannot be used without an <BiProvider>');\n }\n\n return context;\n};\n","import React from 'react';\nimport type { FC } from 'react';\nimport { Spinner, useAsync, useAsyncCallback } from '@wix/cli-ui-kit';\nimport { I18nProvider } from '@wix/cli-i18n';\nimport { useBiLogger } from '@wix/cli-telemetry-react';\nimport { wixCliLoginStart, wixCliLoginEnd } from '@wix/bi-logger-wix-cli/v2';\nimport { match } from 'variant';\nimport type { DeviceCodeResponse } from '../schemas.js';\nimport messages from '../messages.json' with { type: 'json' };\nimport { accountAuthStrategy } from '../auth-strategies/index.js';\nimport type {\n AuthStrategy,\n AuthStrategyState,\n} from '../auth-strategies/index.js';\nimport { LoginInstructions } from './LoginInstructions.js';\nimport { client } from '../client.js';\n\ninterface Props {\n loginFn: AuthStrategy['login'];\n onLogin: (data: AuthStrategyState) => void;\n onError: (error: unknown) => void;\n}\n\nexport const Login: FC<Props> = ({ loginFn, onLogin, onError }) => {\n const biLogger = useBiLogger();\n\n function handleError(error: unknown) {\n void biLogger.report(\n wixCliLoginEnd({\n isSuccess: false,\n ...(error instanceof Error\n ? {\n errorType: error.name,\n }\n : {\n errorType: 'unknown',\n errorMessage: JSON.stringify(error),\n }),\n })\n );\n\n onError(error);\n }\n\n const loginAction = useAsyncCallback(\n async ({ signal }, deviceCodeResponse: DeviceCodeResponse) => {\n try {\n const authData = await loginFn({\n deviceCode: deviceCodeResponse,\n signal,\n });\n void biLogger.report(\n wixCliLoginEnd({\n isSuccess: true,\n })\n );\n onLogin(authData);\n } catch (error) {\n handleError(error);\n }\n }\n );\n\n const { status } = useAsync(\n async () => {\n void biLogger.report(wixCliLoginStart({}));\n\n return client.requestDeviceCode();\n },\n [],\n {\n onSuccess: (deviceCodeResponse) => {\n void loginAction.execute(deviceCodeResponse);\n },\n onError: handleError,\n }\n );\n\n return match(status, {\n Error: () => null,\n Loading: () => <Spinner />,\n Success: ({ result: { userCode, verificationUri } }) => (\n <LoginInstructions\n userCode={userCode}\n verificationUri={verificationUri}\n />\n ),\n });\n};\n\nexport function LoginWithI18n(props: Omit<Props, 'loginFn'>) {\n return (\n <I18nProvider messages={messages}>\n <Login loginFn={accountAuthStrategy.login} {...props} />\n </I18nProvider>\n );\n}\n","{\n \"login.instructions_title\": \"Authorize the CLI to access your Wix account:\",\n \"login.instructions_details\": \"1. Copy this code to the clipboard: <0>{code}</0>\\n2. Choose an option:\",\n \"login.have_wix_account\": \"Already have an account? Press <0/> to <1>log in</1> and then paste the code\",\n \"login.new_to_wix\": \"New to Wix? Press <0/> to <1>sign up</1> and then paste the code\",\n \"login.legacy_auth_notice\": \"We implemented a new and more secure login method. You'll need to re-login to continue using the CLI.\",\n \"login.error_opening_browser\": \"Failed to open browser, please try opening <0/> manually.\"\n}\n","import React, { useState } from 'react';\nimport type { FC } from 'react';\nimport { Box, Text, Link, useInput, Key } from '@wix/cli-ui-kit';\nimport { Trans } from '@wix/cli-i18n';\nimport { openBrowser } from '@wix/user-browser';\nimport { ErrorViewer, useErrorReporter } from '@wix/cli-error-reporting';\nimport { useColoredVerificationUri } from '../useColoredVerificationUri.js';\n\ninterface Props {\n userCode: string;\n verificationUri: string;\n}\n\nexport const LoginInstructions: FC<Props> = ({ userCode, verificationUri }) => {\n const { coloredVerificationUri, signupUri } =\n useColoredVerificationUri(verificationUri);\n const { reportError } = useErrorReporter();\n const [openBrowserError, setOpenBrowserError] = useState<unknown>(null);\n\n useInput((input, key) => {\n if (key.return) {\n openBrowser(coloredVerificationUri).catch((error: unknown) => {\n reportError(error);\n setOpenBrowserError(error);\n });\n }\n if (input === ' ') {\n openBrowser(signupUri).catch((error: unknown) => {\n reportError(error);\n setOpenBrowserError(error);\n });\n }\n });\n\n return (\n <>\n <Trans i18nKey=\"login.instructions_title\" />\n <Box flexDirection=\"column\" marginTop={1} marginBottom={1} marginLeft={2}>\n <Box marginBottom={1}>\n <Trans\n i18nKey=\"login.instructions_details\"\n components={[<Text skin=\"info\" />]}\n values={{ code: userCode }}\n />\n </Box>\n <Box marginBottom={1}>\n <Trans\n i18nKey=\"login.have_wix_account\"\n components={[\n <Key value=\"enter\" />,\n <Link url={coloredVerificationUri} />,\n ]}\n />\n </Box>\n <Trans\n i18nKey=\"login.new_to_wix\"\n components={[<Key value=\"space\" />, <Link url={signupUri} />]}\n />\n </Box>\n\n {openBrowserError != null && (\n <>\n <Box flexDirection=\"column\" marginBottom={1}>\n <ErrorViewer error={openBrowserError} />\n </Box>\n\n <Trans\n i18nKey=\"login.error_opening_browser\"\n components={[<Link url={coloredVerificationUri} />]}\n />\n </>\n )}\n </>\n );\n};\n","import open from 'open';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\nimport { open as openTestkit } from './open-testkit.js';\n\nexport async function openBrowser(url: string) {\n const { userBrowserTestEndpoint: testEndpoint } = getTestOverrides();\n\n try {\n if (testEndpoint) {\n await openTestkit(testEndpoint, url);\n } else {\n await open(url, {\n background: true,\n });\n }\n } catch (error) {\n throw new CliError({\n code: CliErrorCode.FailedToOpenBrowser(),\n info: { url },\n cause: error,\n });\n }\n}\n","import process from 'node:process';\nimport {Buffer} from 'node:buffer';\nimport path from 'node:path';\nimport {fileURLToPath} from 'node:url';\nimport childProcess from 'node:child_process';\nimport fs, {constants as fsConstants} from 'node:fs/promises';\nimport isWsl from 'is-wsl';\nimport defineLazyProperty from 'define-lazy-prop';\nimport defaultBrowser from 'default-browser';\nimport isInsideContainer from 'is-inside-container';\n\n// Path to included `xdg-open`.\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\nconst localXdgOpenPath = path.join(__dirname, 'xdg-open');\n\nconst {platform, arch} = process;\n\n/**\nGet the mount point for fixed drives in WSL.\n\n@inner\n@returns {string} The mount point.\n*/\nconst getWslDrivesMountPoint = (() => {\n\t// Default value for \"root\" param\n\t// according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config\n\tconst defaultMountPoint = '/mnt/';\n\n\tlet mountPoint;\n\n\treturn async function () {\n\t\tif (mountPoint) {\n\t\t\t// Return memoized mount point value\n\t\t\treturn mountPoint;\n\t\t}\n\n\t\tconst configFilePath = '/etc/wsl.conf';\n\n\t\tlet isConfigFileExists = false;\n\t\ttry {\n\t\t\tawait fs.access(configFilePath, fsConstants.F_OK);\n\t\t\tisConfigFileExists = true;\n\t\t} catch {}\n\n\t\tif (!isConfigFileExists) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tconst configContent = await fs.readFile(configFilePath, {encoding: 'utf8'});\n\t\tconst configMountPoint = /(?<!#.*)root\\s*=\\s*(?<mountPoint>.*)/g.exec(configContent);\n\n\t\tif (!configMountPoint) {\n\t\t\treturn defaultMountPoint;\n\t\t}\n\n\t\tmountPoint = configMountPoint.groups.mountPoint.trim();\n\t\tmountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`;\n\n\t\treturn mountPoint;\n\t};\n})();\n\nconst pTryEach = async (array, mapper) => {\n\tlet latestError;\n\n\tfor (const item of array) {\n\t\ttry {\n\t\t\treturn await mapper(item); // eslint-disable-line no-await-in-loop\n\t\t} catch (error) {\n\t\t\tlatestError = error;\n\t\t}\n\t}\n\n\tthrow latestError;\n};\n\nconst baseOpen = async options => {\n\toptions = {\n\t\twait: false,\n\t\tbackground: false,\n\t\tnewInstance: false,\n\t\tallowNonzeroExitCode: false,\n\t\t...options,\n\t};\n\n\tif (Array.isArray(options.app)) {\n\t\treturn pTryEach(options.app, singleApp => baseOpen({\n\t\t\t...options,\n\t\t\tapp: singleApp,\n\t\t}));\n\t}\n\n\tlet {name: app, arguments: appArguments = []} = options.app ?? {};\n\tappArguments = [...appArguments];\n\n\tif (Array.isArray(app)) {\n\t\treturn pTryEach(app, appName => baseOpen({\n\t\t\t...options,\n\t\t\tapp: {\n\t\t\t\tname: appName,\n\t\t\t\targuments: appArguments,\n\t\t\t},\n\t\t}));\n\t}\n\n\tif (app === 'browser' || app === 'browserPrivate') {\n\t\t// IDs from default-browser for macOS and windows are the same\n\t\tconst ids = {\n\t\t\t'com.google.chrome': 'chrome',\n\t\t\t'google-chrome.desktop': 'chrome',\n\t\t\t'org.mozilla.firefox': 'firefox',\n\t\t\t'firefox.desktop': 'firefox',\n\t\t\t'com.microsoft.msedge': 'edge',\n\t\t\t'com.microsoft.edge': 'edge',\n\t\t\t'microsoft-edge.desktop': 'edge',\n\t\t};\n\n\t\t// Incognito flags for each browser in `apps`.\n\t\tconst flags = {\n\t\t\tchrome: '--incognito',\n\t\t\tfirefox: '--private-window',\n\t\t\tedge: '--inPrivate',\n\t\t};\n\n\t\tconst browser = await defaultBrowser();\n\t\tif (browser.id in ids) {\n\t\t\tconst browserName = ids[browser.id];\n\n\t\t\tif (app === 'browserPrivate') {\n\t\t\t\tappArguments.push(flags[browserName]);\n\t\t\t}\n\n\t\t\treturn baseOpen({\n\t\t\t\t...options,\n\t\t\t\tapp: {\n\t\t\t\t\tname: apps[browserName],\n\t\t\t\t\targuments: appArguments,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tthrow new Error(`${browser.name} is not supported as a default browser`);\n\t}\n\n\tlet command;\n\tconst cliArguments = [];\n\tconst childProcessOptions = {};\n\n\tif (platform === 'darwin') {\n\t\tcommand = 'open';\n\n\t\tif (options.wait) {\n\t\t\tcliArguments.push('--wait-apps');\n\t\t}\n\n\t\tif (options.background) {\n\t\t\tcliArguments.push('--background');\n\t\t}\n\n\t\tif (options.newInstance) {\n\t\t\tcliArguments.push('--new');\n\t\t}\n\n\t\tif (app) {\n\t\t\tcliArguments.push('-a', app);\n\t\t}\n\t} else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) {\n\t\tconst mountPoint = await getWslDrivesMountPoint();\n\n\t\tcommand = isWsl\n\t\t\t? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`\n\t\t\t: `${process.env.SYSTEMROOT || process.env.windir || 'C:\\\\Windows'}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell`;\n\n\t\tcliArguments.push(\n\t\t\t'-NoProfile',\n\t\t\t'-NonInteractive',\n\t\t\t'-ExecutionPolicy',\n\t\t\t'Bypass',\n\t\t\t'-EncodedCommand',\n\t\t);\n\n\t\tif (!isWsl) {\n\t\t\tchildProcessOptions.windowsVerbatimArguments = true;\n\t\t}\n\n\t\tconst encodedArguments = ['Start'];\n\n\t\tif (options.wait) {\n\t\t\tencodedArguments.push('-Wait');\n\t\t}\n\n\t\tif (app) {\n\t\t\t// Double quote with double quotes to ensure the inner quotes are passed through.\n\t\t\t// Inner quotes are delimited for PowerShell interpretation with backticks.\n\t\t\tencodedArguments.push(`\"\\`\"${app}\\`\"\"`);\n\t\t\tif (options.target) {\n\t\t\t\tappArguments.push(options.target);\n\t\t\t}\n\t\t} else if (options.target) {\n\t\t\tencodedArguments.push(`\"${options.target}\"`);\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tappArguments = appArguments.map(argument => `\"\\`\"${argument}\\`\"\"`);\n\t\t\tencodedArguments.push('-ArgumentList', appArguments.join(','));\n\t\t}\n\n\t\t// Using Base64-encoded command, accepted by PowerShell, to allow special characters.\n\t\toptions.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');\n\t} else {\n\t\tif (app) {\n\t\t\tcommand = app;\n\t\t} else {\n\t\t\t// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.\n\t\t\tconst isBundled = !__dirname || __dirname === '/';\n\n\t\t\t// Check if local `xdg-open` exists and is executable.\n\t\t\tlet exeLocalXdgOpen = false;\n\t\t\ttry {\n\t\t\t\tawait fs.access(localXdgOpenPath, fsConstants.X_OK);\n\t\t\t\texeLocalXdgOpen = true;\n\t\t\t} catch {}\n\n\t\t\tconst useSystemXdgOpen = process.versions.electron\n\t\t\t\t?? (platform === 'android' || isBundled || !exeLocalXdgOpen);\n\t\t\tcommand = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;\n\t\t}\n\n\t\tif (appArguments.length > 0) {\n\t\t\tcliArguments.push(...appArguments);\n\t\t}\n\n\t\tif (!options.wait) {\n\t\t\t// `xdg-open` will block the process unless stdio is ignored\n\t\t\t// and it's detached from the parent even if it's unref'd.\n\t\t\tchildProcessOptions.stdio = 'ignore';\n\t\t\tchildProcessOptions.detached = true;\n\t\t}\n\t}\n\n\tif (platform === 'darwin' && appArguments.length > 0) {\n\t\tcliArguments.push('--args', ...appArguments);\n\t}\n\n\t// This has to come after `--args`.\n\tif (options.target) {\n\t\tcliArguments.push(options.target);\n\t}\n\n\tconst subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);\n\n\tif (options.wait) {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tsubprocess.once('error', reject);\n\n\t\t\tsubprocess.once('close', exitCode => {\n\t\t\t\tif (!options.allowNonzeroExitCode && exitCode > 0) {\n\t\t\t\t\treject(new Error(`Exited with code ${exitCode}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tresolve(subprocess);\n\t\t\t});\n\t\t});\n\t}\n\n\tsubprocess.unref();\n\n\treturn subprocess;\n};\n\nconst open = (target, options) => {\n\tif (typeof target !== 'string') {\n\t\tthrow new TypeError('Expected a `target`');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\ttarget,\n\t});\n};\n\nexport const openApp = (name, options) => {\n\tif (typeof name !== 'string' && !Array.isArray(name)) {\n\t\tthrow new TypeError('Expected a valid `name`');\n\t}\n\n\tconst {arguments: appArguments = []} = options ?? {};\n\tif (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {\n\t\tthrow new TypeError('Expected `appArguments` as Array type');\n\t}\n\n\treturn baseOpen({\n\t\t...options,\n\t\tapp: {\n\t\t\tname,\n\t\t\targuments: appArguments,\n\t\t},\n\t});\n};\n\nfunction detectArchBinary(binary) {\n\tif (typeof binary === 'string' || Array.isArray(binary)) {\n\t\treturn binary;\n\t}\n\n\tconst {[arch]: archBinary} = binary;\n\n\tif (!archBinary) {\n\t\tthrow new Error(`${arch} is not supported`);\n\t}\n\n\treturn archBinary;\n}\n\nfunction detectPlatformBinary({[platform]: platformBinary}, {wsl}) {\n\tif (wsl && isWsl) {\n\t\treturn detectArchBinary(wsl);\n\t}\n\n\tif (!platformBinary) {\n\t\tthrow new Error(`${platform} is not supported`);\n\t}\n\n\treturn detectArchBinary(platformBinary);\n}\n\nexport const apps = {};\n\ndefineLazyProperty(apps, 'chrome', () => detectPlatformBinary({\n\tdarwin: 'google chrome',\n\twin32: 'chrome',\n\tlinux: ['google-chrome', 'google-chrome-stable', 'chromium'],\n}, {\n\twsl: {\n\t\tia32: '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe',\n\t\tx64: ['/mnt/c/Program Files/Google/Chrome/Application/chrome.exe', '/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe'],\n\t},\n}));\n\ndefineLazyProperty(apps, 'firefox', () => detectPlatformBinary({\n\tdarwin: 'firefox',\n\twin32: 'C:\\\\Program Files\\\\Mozilla Firefox\\\\firefox.exe',\n\tlinux: 'firefox',\n}, {\n\twsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe',\n}));\n\ndefineLazyProperty(apps, 'edge', () => detectPlatformBinary({\n\tdarwin: 'microsoft edge',\n\twin32: 'msedge',\n\tlinux: ['microsoft-edge', 'microsoft-edge-dev'],\n}, {\n\twsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',\n}));\n\ndefineLazyProperty(apps, 'browser', () => 'browser');\n\ndefineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate');\n\nexport default open;\n","import process from 'node:process';\nimport os from 'node:os';\nimport fs from 'node:fs';\nimport isInsideContainer from 'is-inside-container';\n\nconst isWsl = () => {\n\tif (process.platform !== 'linux') {\n\t\treturn false;\n\t}\n\n\tif (os.release().toLowerCase().includes('microsoft')) {\n\t\tif (isInsideContainer()) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\ttry {\n\t\treturn fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')\n\t\t\t? !isInsideContainer() : false;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport default process.env.__IS_WSL_TEST__ ? isWsl : isWsl();\n","import fs from 'node:fs';\nimport isDocker from 'is-docker';\n\nlet cachedResult;\n\n// Podman detection\nconst hasContainerEnv = () => {\n\ttry {\n\t\tfs.statSync('/run/.containerenv');\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport default function isInsideContainer() {\n\t// TODO: Use `??=` when targeting Node.js 16.\n\tif (cachedResult === undefined) {\n\t\tcachedResult = hasContainerEnv() || isDocker();\n\t}\n\n\treturn cachedResult;\n}\n","import fs from 'node:fs';\n\nlet isDockerCached;\n\nfunction hasDockerEnv() {\n\ttry {\n\t\tfs.statSync('/.dockerenv');\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction hasDockerCGroup() {\n\ttry {\n\t\treturn fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport default function isDocker() {\n\t// TODO: Use `??=` when targeting Node.js 16.\n\tif (isDockerCached === undefined) {\n\t\tisDockerCached = hasDockerEnv() || hasDockerCGroup();\n\t}\n\n\treturn isDockerCached;\n}\n","export default function defineLazyProperty(object, propertyName, valueGetter) {\n\tconst define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true});\n\n\tObject.defineProperty(object, propertyName, {\n\t\tconfigurable: true,\n\t\tenumerable: true,\n\t\tget() {\n\t\t\tconst result = valueGetter();\n\t\t\tdefine(result);\n\t\t\treturn result;\n\t\t},\n\t\tset(value) {\n\t\t\tdefine(value);\n\t\t}\n\t});\n\n\treturn object;\n}\n","import {promisify} from 'node:util';\nimport process from 'node:process';\nimport {execFile} from 'node:child_process';\nimport defaultBrowserId from 'default-browser-id';\nimport bundleName from 'bundle-name';\nimport windows from './windows.js';\n\nconst execFileAsync = promisify(execFile);\n\n// Inlined: https://github.com/sindresorhus/titleize/blob/main/index.js\nconst titleize = string => string.toLowerCase().replaceAll(/(?:^|\\s|-)\\S/g, x => x.toUpperCase());\n\nexport default async function defaultBrowser() {\n\tif (process.platform === 'darwin') {\n\t\tconst id = await defaultBrowserId();\n\t\tconst name = await bundleName(id);\n\t\treturn {name, id};\n\t}\n\n\tif (process.platform === 'linux') {\n\t\tconst {stdout} = await execFileAsync('xdg-mime', ['query', 'default', 'x-scheme-handler/http']);\n\t\tconst id = stdout.trim();\n\t\tconst name = titleize(id.replace(/.desktop$/, '').replace('-', ' '));\n\t\treturn {name, id};\n\t}\n\n\tif (process.platform === 'win32') {\n\t\treturn windows();\n\t}\n\n\tthrow new Error('Only macOS, Linux, and Windows are supported');\n}\n","import {promisify} from 'node:util';\nimport process from 'node:process';\nimport {execFile} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\nexport default async function defaultBrowserId() {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst {stdout} = await execFileAsync('defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure', 'LSHandlers']);\n\n\t// `(?!-)` is to prevent matching `LSHandlerRoleAll = \"-\";`.\n\tconst match = /LSHandlerRoleAll = \"(?!-)(?<id>[^\"]+?)\";\\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);\n\n\treturn match?.groups.id ?? 'com.apple.Safari';\n}\n","import {runAppleScript} from 'run-applescript';\n\nexport default async function bundleName(bundleId) {\n\treturn runAppleScript(`tell application \"Finder\" to set app_path to application file id \"${bundleId}\" as string\\ntell application \"System Events\" to get value of property list item \"CFBundleName\" of property list file (app_path & \":Contents:Info.plist\")`);\n}\n","import process from 'node:process';\nimport {promisify} from 'node:util';\nimport {execFile, execFileSync} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\nexport async function runAppleScript(script, {humanReadableOutput = true} = {}) {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst outputArguments = humanReadableOutput ? [] : ['-ss'];\n\n\tconst {stdout} = await execFileAsync('osascript', ['-e', script, outputArguments]);\n\treturn stdout.trim();\n}\n\nexport function runAppleScriptSync(script, {humanReadableOutput = true} = {}) {\n\tif (process.platform !== 'darwin') {\n\t\tthrow new Error('macOS only');\n\t}\n\n\tconst outputArguments = humanReadableOutput ? [] : ['-ss'];\n\n\tconst stdout = execFileSync('osascript', ['-e', script, ...outputArguments], {\n\t\tencoding: 'utf8',\n\t\tstdio: ['ignore', 'pipe', 'ignore'],\n\t\ttimeout: 500,\n\t});\n\n\treturn stdout.trim();\n}\n","import {promisify} from 'node:util';\nimport {execFile} from 'node:child_process';\n\nconst execFileAsync = promisify(execFile);\n\n// Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake\n// ones that look real and match the macOS/Linux versions for cross-platform apps.\nconst windowsBrowserProgIds = {\n\tAppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'},\n\tMSEdgeDHTML: {name: 'Edge', id: 'com.microsoft.edge'}, // On macOS, it's \"com.microsoft.edgemac\"\n\tMSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // Newer Edge/Win10 releases\n\t'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'},\n\tFirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'},\n\tChromeHTML: {name: 'Chrome', id: 'com.google.chrome'},\n\tBraveHTML: {name: 'Brave', id: 'com.brave.Browser'},\n\tBraveBHTML: {name: 'Brave Beta', id: 'com.brave.Browser.beta'},\n\tBraveSSHTM: {name: 'Brave Nightly', id: 'com.brave.Browser.nightly'},\n};\n\nexport class UnknownBrowserError extends Error {}\n\nexport default async function defaultBrowser(_execFileAsync = execFileAsync) {\n\tconst {stdout} = await _execFileAsync('reg', [\n\t\t'QUERY',\n\t\t' HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\Windows\\\\Shell\\\\Associations\\\\UrlAssociations\\\\http\\\\UserChoice',\n\t\t'/v',\n\t\t'ProgId',\n\t]);\n\n\tconst match = /ProgId\\s*REG_SZ\\s*(?<id>\\S+)/.exec(stdout);\n\tif (!match) {\n\t\tthrow new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);\n\t}\n\n\tconst {id} = match.groups;\n\n\tconst browser = windowsBrowserProgIds[id];\n\tif (!browser) {\n\t\tthrow new UnknownBrowserError(`Unknown browser ID: ${id}`);\n\t}\n\n\treturn browser;\n}\n","import { createHttpClient, HttpClient } from '@wix/http-client';\n\nexport async function open(testEndpoint: string, url: string) {\n await createHttpClient()\n .post(testEndpoint, undefined, {\n params: {\n url,\n },\n })\n .catch((error: unknown) => {\n if (HttpClient.isHttpError(error) && error.response?.data?.message) {\n throw new Error(error.response.data.message);\n }\n\n throw error;\n });\n}\n","export {\n createErrorHandler,\n type ErrorHandlerFn,\n} from './create-error-handler.js';\nexport { ErrorViewer } from './components/ErrorViewer.js';\nexport { OutdatedVersionMessage } from './components/OutdatedVersionMessage.js';\nexport { createErrorReporter, type ErrorReporter } from './error-reporter.js';\nexport {\n ErrorReporterProvider,\n useErrorReporter,\n} from './error-reporter-context.js';\n","import process from 'node:process';\nimport React from 'react';\nimport { renderErrorSync } from '@wix/cli-ui-kit';\nimport { writeCrashReport } from '@wix/cli-debug-log';\nimport { createEnv } from '@wix/cli-env';\nimport { ErrorViewer } from './components/ErrorViewer.js';\nimport type { ErrorReporterOptions } from './error-reporter.js';\nimport { createErrorReporter } from './error-reporter.js';\nimport { collectUserFeedback } from './user-feedback.js';\nimport { RawErrorViewer } from './components/RawErrorViewer.js';\n\nexport type ErrorHandlerFn = (args: { error: unknown; data?: unknown }) => void;\n\nexport function createErrorHandler({\n debugOutputPath,\n userFeedbackCachePath,\n ...errorReporterOptions\n}: {\n debugOutputPath: string;\n userFeedbackCachePath?: string;\n} & ErrorReporterOptions) {\n const errorReporter = createErrorReporter(errorReporterOptions);\n\n const handler: ErrorHandlerFn = function ({ error, data }) {\n const reportResult = errorReporter.reportError(error, { data });\n const { isCI } = createEnv();\n const occuredAt = new Date();\n\n renderErrorSync(\n <>\n <ErrorViewer error={error} />\n {isCI && <RawErrorViewer error={error} occurredAt={occuredAt} />}\n </>\n );\n\n writeCrashReport(debugOutputPath, error, occuredAt);\n process.exitCode = 1;\n\n collectUserFeedback({\n reportResult,\n errorReporter,\n cachePath: userFeedbackCachePath,\n }).catch((e: unknown) => {\n writeCrashReport(debugOutputPath, e, new Date());\n });\n };\n\n const registerToProcessErrors = function () {\n process.on('uncaughtException', (error) => {\n handler({\n error,\n data: { mechanism: { handled: false, type: 'uncaughtException' } },\n });\n });\n\n process.on('unhandledRejection', (error) => {\n /**\n * Temporary workaround for https://github.com/vitejs/vite/issues/14706\n */\n if (\n error instanceof Error &&\n error.message.startsWith('Build failed with') &&\n error.stack?.includes('esbuild')\n ) {\n return;\n }\n\n /**\n * Workaround for PostCSS unhandled errors https://github.com/vitejs/vite/issues/18882\n */\n if (\n error instanceof Error &&\n error.message.startsWith('Failed to load PostCSS config')\n ) {\n return;\n }\n\n handler({\n error,\n data: { mechanism: { handled: false, type: 'unhandledRejection' } },\n });\n });\n };\n\n return {\n handler,\n errorReporter,\n registerToProcessErrors,\n };\n}\n","import { dirname } from 'node:path';\nimport { appendFileSync, mkdirSync } from 'node:fs';\nimport React, { createContext, useContext, useCallback } from 'react';\nimport type { FC, ReactNode } from 'react';\nimport VError from 'verror';\nimport { extractHttpError, getHttpErrorInfo } from '@wix/cli-http-client';\n\nexport function writeCrashReport(\n reportPath: string,\n error: unknown,\n occurredAt: Date\n) {\n try {\n let content = `----- CLI crash report at ${occurredAt.toISOString()}\\n`;\n if (error instanceof Error) {\n content += `Error Trace\\n`;\n content += `${VError.fullStack(error)}\\n`;\n content += `Error Info\\n`;\n content += `${JSON.stringify(VError.info(error), null, 2)}\\n`;\n\n const httpError = extractHttpError(error);\n if (httpError) {\n content += `Request Info\\n`;\n content += `${JSON.stringify(getHttpErrorInfo(httpError), null, 2)}\\n`;\n }\n }\n mkdirSync(dirname(reportPath), { recursive: true });\n appendFileSync(reportPath, content);\n } catch {\n // well there is so much we can do...\n }\n}\n\nexport type WriteDebugLogFn = (error: unknown) => void;\n\nconst DebugLogContext = createContext<WriteDebugLogFn | null>(null);\n\ninterface Props {\n filePath: string;\n children: ReactNode;\n}\n\nexport const DebugLogProvider: FC<Props> = ({ filePath, children }) => {\n const writeToDebugLog = useCallback<WriteDebugLogFn>(\n (error) => writeCrashReport(filePath, error, new Date()),\n [filePath]\n );\n\n return (\n <DebugLogContext.Provider value={writeToDebugLog}>\n {children}\n </DebugLogContext.Provider>\n );\n};\n\nexport const useDebugLog = (): WriteDebugLogFn => {\n const context = useContext(DebugLogContext);\n if (context == null) {\n throw new Error(\n 'useDebugLog() cannot be used without an <DebugLogProvider>'\n );\n }\n return context;\n};\n","import ci from 'ci-info';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\n\nexport const createEnv = () => {\n // CI detection should be configurable per test, not bound to the runtime environment.\n // This prevents environment-driven variability (e.g., local vs. GitHub Actions) and ensures predictable behavior.\n const overrides = getTestOverrides();\n return {\n isCI: overrides.isCI ?? ci.isCI,\n isPR: overrides.isPR ?? ci.isPR,\n ciName: overrides.ciName ?? ci.name ?? process.env.CI_NAME ?? null,\n };\n};\n","import { createElement, useMemo } from 'react';\nimport type { FC, ReactNode } from 'react';\nimport { isCliSystemError, normalizeError } from '@wix/cli-error';\nimport { getErrorComponent } from '../get-error-component.js';\n\ninterface Props {\n error: unknown;\n systemErrorOverride?: ReactNode;\n}\n\nexport const ErrorViewer: FC<Props> = ({\n error: originalError,\n systemErrorOverride,\n}) => {\n return useMemo(() => {\n const error = normalizeError(originalError);\n\n return isCliSystemError(error) && systemErrorOverride\n ? systemErrorOverride\n : createElement(getErrorComponent(error.cliCode, error.cause()));\n }, [originalError, systemErrorOverride]);\n};\n","import type { ComponentType } from 'react';\nimport React, { Fragment } from 'react';\nimport { match } from 'variant';\nimport { Box, Newline, Text, Link, Alert } from '@wix/cli-ui-kit';\nimport { outdent } from 'outdent';\nimport type { ZodIssue } from 'zod';\nimport type { CliErrorCodeType } from '@wix/cli-error';\nimport { ErrorMessage, SystemErrorMessage } from './components/ErrorMessage.js';\nimport { OutdatedVersionMessage } from './components/OutdatedVersionMessage.js';\nimport { ServeDeprecationMessage } from './components/ServeDeprecationMessage.js';\n\nexport function getErrorComponent(\n code: CliErrorCodeType,\n cause: Error | undefined\n): ComponentType {\n return match(code, {\n UnknownFailure: ({ error }) => {\n return () => (\n <>\n <Text skin=\"error\">\n Oh no, seems like the CLI encountered an unexpected error:\n </Text>\n\n {error instanceof Error ? (\n <Text skin=\"error\">{error.message}</Text>\n ) : (\n <Text>{JSON.stringify(error)}</Text>\n )}\n </>\n );\n },\n FailedToGetDeviceCode: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while logging in: Failed to issue a login device code\" />\n );\n },\n FailedToGetAuthToken: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while logging in: Failed to issue refresh token\" />\n );\n },\n FailedToRefreshTokenForSite: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while logging in: Failed to issue refresh token for site\" />\n );\n },\n FailedToRemoveDir: ({ dirPath }) => {\n return () => (\n <ErrorMessage\n message={`We failed to delete the directory ${dirPath}.`}\n hint={`Try to delete this directory manually.`}\n />\n );\n },\n FailedToQueryLocales: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to pull multilingual data.\" />\n );\n },\n FailedToQueryPublishedContents: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to query published contents.\" />\n );\n },\n NoTranslationPublishedContents: () => {\n return () => (\n <ErrorMessage\n message=\"No translation published contents found.\"\n hint={`Please make sure the \"Wix Multilingual\" app has published content.`}\n />\n );\n },\n TranslationUnsupportedForProjectType: () => {\n return () => (\n <ErrorMessage message=\"Translation command only applicable for headless sites.\" />\n );\n },\n TranslationFileNotFound: ({ filePath }) => {\n return () => (\n <ErrorMessage\n message={`Translation file not found at \\`${filePath}\\`.`}\n hint={`Please create a \\`${filePath}\\` file in your project and run the command again.`}\n explanation={`The translation file is used to store the translation keys and values for your project.`}\n />\n );\n },\n InvalidTranslationsFileSchema: ({ filePath, zodError }) => {\n return () => (\n <ErrorMessage\n message={outdent`\n Invalid translations file format at \\`${filePath}\\`:\n The following errors were found:\n ${zodError.errors.map(formatZodIssue).join('\\n')}`}\n hint=\"The translations file should be a JSON object with string values, or a nested object with string values.\"\n />\n );\n },\n ConnectUnsupportedForProjectType: () => {\n return () => (\n <ErrorMessage message=\"The connect command is only available for Site projects.\" />\n );\n },\n FailedToRenewAuthToken: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to renew access token.\" />\n );\n },\n FailedToRenewAuthTokenSiteNotFound: ({ siteId }) => {\n return () => (\n <ErrorMessage\n message={`Authenticate failed, your configured development site (${siteId}) could not be accessed`}\n hint=\"Make sure the site exists and you still have access to it\"\n />\n );\n },\n FailedToRenewAuthTokenRefreshTokenRevoked: () => {\n return () => (\n <ErrorMessage\n message=\"Failed to renew access token: refresh token has been revoked\"\n hint=\"Please login again to get a new refresh token\"\n />\n );\n },\n FailedToRevokeRefreshToken: ({ email }) => {\n return () => (\n <SystemErrorMessage\n message=\"An error occurred while trying to logout: Failed to revoke refresh token!\"\n explanation={`Wix CLI is still logged in to account ${email}`}\n />\n );\n },\n FailedToFetchPackageJson: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to fetch package data.\" />\n );\n },\n FailedToCreateProjectFolder: ({ packageFolder }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to create project folder: ${packageFolder}.`}\n />\n );\n },\n LatestVersionOfCreateAppRequired: ({\n currentVersion,\n latestVersion,\n updateCommand,\n }) => {\n return () => (\n <ErrorMessage\n message={\n <>\n Generating a Wix App is only supported using the latest version (\n {latestVersion}) of <Text bold>@wix/create-app</Text> (current:{' '}\n {currentVersion})\n </>\n }\n hint={\n <Text>\n Make sure you are using the following command:\n <Newline />\n <Text bold>{updateCommand}</Text>\n <Newline />\n If the problem persists, try clearing your package manager's cache\n </Text>\n }\n />\n );\n },\n EmptyDirectoryRequiredAppGeneration: ({ folder }) => {\n return () => (\n <ErrorMessage\n message={\n <>\n Generating a Wix App requires an empty directory but{' '}\n <Text bold>{folder}</Text> already exists and isn't empty\n </>\n }\n hint={\n <Text>\n Choose a different project name or delete the existing{' '}\n <Text bold>{folder}</Text> folder\n </Text>\n }\n />\n );\n },\n InvalidNewPackageName: ({ packageName, validations }) => {\n return () => (\n <ErrorMessage\n message={\n <>\n Generating a Wix App requires a valid npm package name for the\n generated <Text bold>package.json</Text> <Newline />\n The name <Text bold>{packageName}</Text> failed the following\n validations:\n <Newline />\n {validations.map((validation, id) => (\n <Text key={id}>\n <Newline />- {validation}\n </Text>\n ))}\n </>\n }\n hint={`Choose a different project name that follows the validations above`}\n />\n );\n },\n SiteSelectorTimedout: () => {\n return () => (\n <ErrorMessage\n message={`Waiting for application installation timed out.`}\n />\n );\n },\n TypeErrorInvalidUrl: () => {\n return () => <ErrorMessage message={`Invalid assets URL.`} />;\n },\n UnsupportedPackageManager: ({ packageManagerName }) => {\n return () => (\n <ErrorMessage\n message={`Unsupported package manager detected. Please use a supported one.`}\n hint={`Expected Yarn or NPM but ${\n packageManagerName\n ? `got ${packageManagerName}`\n : `failed to detect a package manager`\n }`}\n />\n );\n },\n UnsupportedPackageManagerWorkspaces: ({ packageManagerName }) => {\n return () => (\n <ErrorMessage\n message={`Generating a Wix App inside ${packageManagerName} workspaces is not supported`}\n />\n );\n },\n FailedToGetDeveloperApps: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get the list of your applications\" />\n );\n },\n FailedToCreateDevCenterApp: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to register your application in Wix\" />\n );\n },\n FailedToCreateDevCenterOAuthApp: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to register your oauth application in Wix\" />\n );\n },\n FailedToUpdateDevCenterOAuthApp: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to update your oauth application in Wix\" />\n );\n },\n FailedToAddPermission: () => {\n return () => <SystemErrorMessage message=\"Failed to add permission\" />;\n },\n FailedToGetPlacements: () => {\n return () => <SystemErrorMessage message=\"Failed to get placements\" />;\n },\n FailedToCreateTunnel: () => {\n return () => <ErrorMessage message=\"Failed to create tunnel\" />;\n },\n FailedToDeleteTunnel: () => {\n return () => <ErrorMessage message=\"Failed to delete tunnel\" />;\n },\n FailedToGetBlocksExtensionsData: () => {\n return () => (\n <ErrorMessage message=\"Failed to get blocks extensions data\" />\n );\n },\n FailedToGetBlocksStructure: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get blocks structure\" />\n );\n },\n FailedToUpdateBlocksAfterSync: () => {\n return () => (\n <ErrorMessage message=\"Failed updating blocks service after changes occoured\" />\n );\n },\n SitePermissionDenied: ({ siteId }) => {\n return () => {\n return (\n <ErrorMessage\n message={`You don't have permissions to site ${siteId}`}\n />\n );\n };\n },\n AppPermissionDenied: ({ appId }) => {\n return () => {\n return (\n <ErrorMessage\n message={`You don't have permissions to application ${appId}`}\n />\n );\n };\n },\n FailedToUpdateTelemetryConfig: () => {\n return () => (\n <ErrorMessage message=\"Failed to change telemetry preferences\" />\n );\n },\n FailedToInstallPackage: ({ packageName }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to install npm package ${packageName}.`}\n />\n );\n },\n FailedToResolveNpmDependencies: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to resolve npm dependencies\" />\n );\n },\n FailedToInstallPackages: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to install npm packages.\" />\n );\n },\n FailedToRunExternalCommand: ({ file, args }) => {\n const commandString = [file, ...args].join(' ');\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to run external command: ${commandString}`}\n hint=\"Make sure the command is available on your machine and try again.\"\n />\n );\n },\n FailedMigrationToAnyNpm: () => {\n return () => (\n <ErrorMessage\n message=\"Could not start the migration process\"\n explanation=\"Make sure your `package.json` does not contain any packages under `dependencies`, as the migration cannot proceed if any are present.\"\n hint=\"If you need to keep any of these packages, move them to `devDependencies` before proceeding.\"\n />\n );\n },\n FailedToUninstallPackage: ({ packageName }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to uninstall npm package ${packageName}.`}\n />\n );\n },\n FailedToSyncToRevision: ({ revision }) => {\n return () => (\n <ErrorMessage\n message={`Failed to sync the local project to revision ${revision}`}\n />\n );\n },\n FailedToReadCache: ({ path }) => {\n return () => (\n <ErrorMessage message={`Failed to read cache file at ${path}.`} />\n );\n },\n FailedToWriteCache: ({ path }) => {\n return () => (\n <ErrorMessage message={`Failed to write cache file at ${path}.`} />\n );\n },\n UploadApplicationFailed: () => {\n return () => <ErrorMessage message=\"Failed to upload the application\" />;\n },\n BuiltProjectNeeded: () => {\n return () => (\n <ErrorMessage message=\"Can not find build output, please execute `wix app build` to build your app before proceeding\" />\n );\n },\n WixUninstallMissingPackageName: () => {\n return () => <ErrorMessage message=\"Please specify a package name\" />;\n },\n FailedToReadJson: ({ filePath }) => {\n return () => (\n <ErrorMessage cause={cause} message={`Failed to read ${filePath}.`} />\n );\n },\n FailedToReadFile: ({ filePath }) => {\n return () => (\n <ErrorMessage cause={cause} message={`Failed to read ${filePath}.`} />\n );\n },\n InvalidJsonFile: ({ filePath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Invalid JSON file located at ${filePath}.`}\n />\n );\n },\n FailedToWriteWixLock: () => {\n return () => <ErrorMessage message={`Failed to write 'wix.lock'`} />;\n },\n FailedToWriteDependenciesMetadata: () => {\n return () => (\n <ErrorMessage\n message={`Failed to write 'dependencies-metadata.json'`}\n />\n );\n },\n InvalidVeloConfigJson: ({ configFilename }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Invalid ${configFilename}, make sure it's configured correctly.`}\n />\n );\n },\n DashboardPageConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Dashboard page config not found at ${configPath}`}\n />\n );\n },\n EmbeddedScriptConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Embedded script config not found at ${configPath}`}\n />\n );\n },\n CustomElementConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Site widget config not found at ${configPath}`}\n />\n );\n },\n SitePluginConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Site plugin config not found at ${configPath}`}\n />\n );\n },\n BlocksWidgetApiNotFound: ({ folderPath }) => {\n return () => (\n <ErrorMessage\n message={`Blocks widget api file not found at ${folderPath}`}\n />\n );\n },\n BlocksWidgetConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Blocks widget config not found at ${configPath}`}\n />\n );\n },\n BlocksWidgetPanelConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Blocks widget panel config not found at ${configPath}`}\n />\n );\n },\n NoExtensionsFound: () => {\n return () => (\n <ErrorMessage\n message=\"Your project doesn't seem to have any extensions.\"\n explanation=\"Extensions are the building blocks of your app.\"\n hint=\"Make sure it is configured properly, or read our documentation (https://wix.to/b7o4Ml0) to start developing your first extension.\"\n />\n );\n },\n NoPagesDirectoryFound: ({ srcDir }) => {\n return () => (\n <ErrorMessage\n message={\n <>\n No <Text bold>pages</Text> directory was found under{' '}\n <Text bold>{srcDir}</Text>.\n </>\n }\n hint={\n <Text>\n Consider re-cloning the project repository or creating a{' '}\n <Text bold>pages</Text> directory under <Text bold>{srcDir}</Text>\n .\n </Text>\n }\n />\n );\n },\n DashboardPluginConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Dashboard plugin config not found at ${configPath}`}\n />\n );\n },\n DashboardMenuPluginConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Dashboard menu plugin config not found at ${configPath}`}\n />\n );\n },\n ServicePluginConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Service plugin config not found at ${configPath}`}\n />\n );\n },\n DashboardModalConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Dashboard modal config not found at ${configPath}`}\n />\n );\n },\n TSConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`TypeScript config not found at \\`${configPath}\\``}\n />\n );\n },\n InvalidTSConfigError: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={outdent`\n Invalid TypeScript configuration found at \\`${configPath}\\``}\n />\n );\n },\n InvalidConfigSchemaError: ({ configPath, zodError }) => {\n return () => (\n <ErrorMessage\n message={outdent`\n Invalid configuration found at \\`${configPath}\\`:\n The following errors were found:\n ${zodError.errors.map(formatZodIssue).join('\\n')}`}\n hint=\"Fix the errors above for your configurations to be applied successfully.\"\n />\n );\n },\n InvalidParamsOverrideSchemaError: ({ paramsOverridePath, zodError }) => {\n return () => (\n <ErrorMessage\n message={outdent`\n Invalid params override found at \\`${paramsOverridePath}\\`:\n The following errors were found:\n ${zodError.errors.map(formatZodIssue).join('\\n')}`}\n hint=\"Fix the errors above for your params override to be applied successfully.\"\n />\n );\n },\n InvalidDependenciesJsonSchemaError: ({ path, zodError }) => {\n return () => (\n <ErrorMessage\n message={outdent`\n Invalid configuration found at \\`${path}\\`:\n The following errors were found:\n ${zodError.errors.map(formatZodIssue).join('\\n')}`}\n hint={\n <Text>\n Try to re-install <Text bold>@wix/cli-app</Text> dependency\n </Text>\n }\n />\n );\n },\n PermissionDenied: () => {\n return () => (\n <ErrorMessage message=\"Forbidden operation. Missing permissions\" />\n );\n },\n FailedToReadProjectFiles: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to read source files: make sure you have an 'src' folder and that it's readable.\"\n />\n );\n },\n GridAppFilesMaxLengthExceeded: ({ maxSizeViolationsData, filePaths }) => {\n let errorMessage =\n 'Found one or more project files that are bigger than the allowed limit';\n\n if (maxSizeViolationsData?.files.length) {\n errorMessage += ` (${\n maxSizeViolationsData.expectedSize\n }KB): ${maxSizeViolationsData.files\n .map((f) => `${filePaths[f.fileIndex]} (${f.receivedSize}KB)`)\n .join(', ')}`;\n }\n\n return () => <ErrorMessage message={errorMessage} />;\n },\n GridAppFailedToUpdateFiles: () => {\n return () => (\n <ErrorMessage\n message={outdent`\n Failed to update files.\n Failed to sync changes from local files to the Dev Editor\n Still watching local files and will continue to sync changes...\n `}\n />\n );\n },\n FailedToWatchFiles: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to watch files.\" />\n );\n },\n FailedToCreateGridApp: ({ error }) => {\n return () => (\n <ErrorMessage\n message=\"Failed to create an isolated environment.\"\n explanation={error}\n />\n );\n },\n DeviceCodeTimedOut: () => {\n return () => (\n <ErrorMessage message=\"The device code has not been approved in the time allocated, please start the login process again.\" />\n );\n },\n DuplicateComponentIdsError: ({ issues }) => {\n const Issue = ({ issue }: { issue: (typeof issues)[0] }) => {\n const typeToName = (type: (typeof issue)['components'][0]['type']) =>\n match(type, {\n page: () => 'page',\n plugin: () => 'plugin',\n 'menu-plugin': () => 'menu plugin',\n 'sidebar-category': () => 'sidebar category',\n 'embedded-script': () => 'embedded script',\n 'custom-element': () => 'custom element',\n 'blocks-widget': () => 'blocks widget',\n 'blocks-widget-panel': () => 'blocks widget panel',\n modal: () => 'modal',\n topology: () => 'topology',\n 'site-plugin': () => 'site plugin',\n monitoring: () => 'monitoring',\n 'site-component': () => 'site component',\n 'site-component-panel': () => 'site component panel',\n });\n return (\n <Box flexDirection=\"column\">\n <Text>\n <Text bold>Duplicate ID: </Text>\n {issue.id}\n </Text>\n <Text bold>Extensions:</Text>\n {issue.components.map(({ name, path, type }) => (\n <Text key={path}>\n [{typeToName(type)}] {name} ({path})\n </Text>\n ))}\n <Text>\n <Text bold>Possible GUID: </Text>\n {issue.suggestedId}\n </Text>\n </Box>\n );\n };\n\n return () => (\n <Box flexDirection=\"column\" rowGap={1}>\n <ErrorMessage\n message=\"Found multiple extensions with the same id, this might happen if you copy paste folders.\"\n hint=\"You can use the provided suggested GUIDs as the ID of the newly created extension.\"\n />\n {issues.map((issue) => (\n <Issue issue={issue} key={issue.id} />\n ))}\n </Box>\n );\n },\n InvalidResponseData: () => {\n return () => (\n <SystemErrorMessage message=\"Got unexpected response from server.\" />\n );\n },\n InvalidCreateAppResponse: () => {\n return () => (\n <ErrorMessage message=\"`createApp` returned an invalid response.\" />\n );\n },\n InvalidDeployAppResponse: () => {\n return () => (\n <ErrorMessage message=\"Got unexpected response from server. Make sure you are running a supported version of the Velo CLI.\" />\n );\n },\n InvalidGetDeploymentResponse: () => {\n return () => (\n <ErrorMessage message=\"Got unexpected response from server. Please try again later..\" />\n );\n },\n InvalidGetDeploymentPipelineDescriptionResponse: () => {\n return () => (\n <SystemErrorMessage message=\"Got unexpected response from server\" />\n );\n },\n FailedToGetPagesDiff: () => {\n return () => <ErrorMessage message=\"Failed to request pages diff.\" />;\n },\n InvalidViteBuildOutput: () => {\n return () => <ErrorMessage message=\"Invalid vite build output\" />;\n },\n ViteModuleBundleNotFound: () => {\n return () => (\n <ErrorMessage message=\"Could not find module bundle in vite build output\" />\n );\n },\n ViteFileNotFoundInOutput: ({ fileName }) => {\n return () => (\n <ErrorMessage\n message={`Could not find ${fileName} in vite build output`}\n />\n );\n },\n FailedToCreateBackendDeployment: () => {\n return () => (\n <ErrorMessage message=\"Failed to create backend deployment\" />\n );\n },\n FailedToUpdateBackendDeployment: () => {\n return () => (\n <ErrorMessage message=\"Failed to update backend deployment\" />\n );\n },\n FailedToGetBackendDeployment: () => {\n return () => <ErrorMessage message=\"Failed to get backend deployment\" />;\n },\n FailedToDeployBackend: () => {\n return () => <ErrorMessage message=\"Failed to deploy backend\" />;\n },\n FailedToGetUserInfo: () => {\n return () => <ErrorMessage message=\"Failed to get user information.\" />;\n },\n FailedToGetMyAccount: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get account information.\" />\n );\n },\n FailedToCreateDevelopmentSite: () => {\n return () => (\n <ErrorMessage message=\"Failed to create a Development Site\" />\n );\n },\n FailedToCreateMetaSiteFromTemplate: () => {\n return () => (\n <ErrorMessage message=\"Failed to create a metasite from template\" />\n );\n },\n FailedToGetDevelopmentSites: () => {\n return () => (\n <ErrorMessage message=\"Failed to request development sites.\" />\n );\n },\n FailedToGetDevelopmentSitesLimit: () => {\n return () => (\n <ErrorMessage message=\"Failed to request development sites limit.\" />\n );\n },\n FailedToGetRequiredApps: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get app requirement info.\" />\n );\n },\n FailedToGetMarketListing: () => {\n return () => <ErrorMessage message=\"Failed to get market listing.\" />;\n },\n FailedToAddRequiredApp: () => {\n return () => <ErrorMessage message=\"Failed to add required app.\" />;\n },\n FailedToQuerySites: () => {\n return () => <ErrorMessage message=\"Failed to request sites list.\" />;\n },\n FailedToGetSite: () => {\n return () => (\n <ErrorMessage message=\"Failed to get information about your configured Development Site\" />\n );\n },\n FailedToDeploySite: () => {\n return () => <ErrorMessage message=\"Failed to deploy site.\" />;\n },\n FailedToDeploySitePreview: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to deploy site preview.\" />\n );\n },\n FailedToPublishDeployment: () => {\n return () => <SystemErrorMessage message=\"Failed to publish site.\" />;\n },\n FailedToSaveDevelopmentSite: ({ path }) => {\n return () => (\n <ErrorMessage\n message=\"Failed to save the current development site.\"\n hint={`Make sure the \\`${path}\\` file has proper permissions and is accessible`}\n />\n );\n },\n FailedToBuildApp: () => {\n return () => (\n <ErrorMessage\n message={\n <>\n Failed to build the application.\n <Newline />\n {cause?.message}\n </>\n }\n hint={'Please check the build output for more information'}\n />\n );\n },\n FailedToGetAppInstallationDetails: ({ appId }) => {\n return () => (\n <SystemErrorMessage\n message={`Failed to fetch site installation details for app ${appId}`}\n />\n );\n },\n FailedToInitializeGitRepo: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to initialize git repo.\" />\n );\n },\n FailedToInstallDependencies: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to install dependencies.\" />\n );\n },\n FailedToCommitChanges: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to commit changes.\" />\n );\n },\n FailedToDeleteAuthData: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to delete auth data.\" />\n );\n },\n FailedToDeleteLegacyAuthData: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to delete legacy auth data.\"\n />\n );\n },\n FailedToSaveAuthData: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to save auth data.\" />\n );\n },\n FailedToSaveApiKeyAuthData: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to save api key auth data.\"\n />\n );\n },\n FailedToWriteJson: ({ filePath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to write JSON at path: ${filePath}.`}\n />\n );\n },\n FailedToWriteFile: ({ filePath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to write file at path: ${filePath}.`}\n />\n );\n },\n FailedToCreateDir: ({ dirPath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to create a directory at path: ${dirPath}.`}\n />\n );\n },\n TemplatePathNotFound: ({ templatePath }) => {\n return () => (\n <SystemErrorMessage\n message={`Template path not found: ${templatePath}`}\n />\n );\n },\n LocalTemplatePathNotFound: ({ path }) => {\n return () => (\n <ErrorMessage message={`Local template path not found: ${path}`} />\n );\n },\n FailedToCloneRepo: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to clone repo.\"\n hint=\"Make sure the Git URL is correct and that your local Git is configured properly to access the remote repository\"\n />\n );\n },\n InvalidGitUrl: ({ url }) => {\n return () => <SystemErrorMessage message={`Invalid Git URL: ${url}`} />;\n },\n AuthenticationRequired: () => {\n return () => (\n <ErrorMessage message=\"You have to already be logged in to run this command.\" />\n );\n },\n InvalidApiKey: () => {\n return () => (\n <ErrorMessage message=\"You used invalid API key to log in.\" />\n );\n },\n AccountWasDeleted: () => {\n return () => (\n <ErrorMessage message=\"The account you are trying to log in to has been deleted.\" />\n );\n },\n SiteConfiguredRequired: () => {\n return () => (\n <ErrorMessage message=\"You must provide a `--site` in the command options.\" />\n );\n },\n FailedAddingPackageToWorkspace: () => {\n return () => (\n <ErrorMessage\n message=\"Could not add package to the workspaces configuration. Please add it as instructed by your package manager.\"\n hint={\n <Text>\n Full error can be found in <Text bold>wix-error.log</Text>\n </Text>\n }\n />\n );\n },\n FailedToGenerateSelfSignedCertificate: () => {\n return () => (\n <ErrorMessage message=\"Failed to generate a self-signed certificate for development.\" />\n );\n },\n NonInteractiveTerminal: () => {\n return () => (\n <ErrorMessage message=\"This command is not supported in non-interactive terminals. Please run the command in an interactive terminal (TTY).\" />\n );\n },\n FailedToResolveViteOrigin: () => {\n return () => (\n <ErrorMessage message=\"Failed to resolve the base url for CSS asset urls\" />\n );\n },\n FailedToCreateAppRelease: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to create an app configuration.\" />\n );\n },\n FailedToParseHttpErrorResponse: () => {\n return () => (\n <SystemErrorMessage message=\"Unexpected response from server.\" />\n );\n },\n FailedToReleaseHeadlessProject: () => {\n return () => (\n <SystemErrorMessage message=\"Failed releasing a headless site and app\" />\n );\n },\n AppReleaseConfigViolations: ({ violations }) => {\n return () => (\n <ErrorMessage\n message=\"App configuration upload failed because of violations.\"\n explanation={outdent`\n Violations:\n ${violations.map(formatFieldViolations).join('\\n')}\n `}\n hint={\n <>\n <Text>\n It may be temporary error, try again shortly. If it fails again,\n reach us on Discord:{' '}\n <Link url=\"https://discord.gg/devs-on-wix\" />\n </Text>\n </>\n }\n />\n );\n },\n FailedToUpdateAppRelease: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to update an app configuration.\" />\n );\n },\n FailedToCreateComponents: () => {\n return () => <SystemErrorMessage message=\"Failed to create components\" />;\n },\n FailedToFetchPackageDetails: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to fetch cli package details.\" />\n );\n },\n FailedToGetResolveNpmDependenciesResult: () => {\n return () => (\n <SystemErrorMessage message={`Failed to resolve \"wix.lock\" file.`} />\n );\n },\n CliAppVersionMismatch: ({ cliVersion, cliAppVersion }) => {\n return () => (\n <ErrorMessage\n message={\n <Text>\n The versions of <Text bold>@wix/cli</Text> ({cliVersion}) and{' '}\n <Text bold>@wix/cli-app</Text> ({cliAppVersion}) dependencies do\n not match\n </Text>\n }\n hint={\n <Text>\n Align their versions in your <Text bold>package.json</Text> and\n re-install dependencies\n </Text>\n }\n />\n );\n },\n InvalidDashboardPageRoute: ({ route, errorMessage }) => {\n return () => (\n <ErrorMessage\n message={`Invalid dashboard page route: ${route}`}\n hint={errorMessage}\n />\n );\n },\n InvalidEmbeddedScriptFolder: ({ path, errorMessage }) => {\n return () => (\n <ErrorMessage\n message={`Invalid embedded script folder: ${path}`}\n hint={errorMessage}\n />\n );\n },\n InvalidEmbeddedScriptTemplate: ({ templateFilename, errorMessage }) => {\n return () => (\n <ErrorMessage\n message={`Invalid embedded script template in ${templateFilename}`}\n hint={errorMessage}\n />\n );\n },\n InvalidCustomElementTagName: ({ tagName, errorMessage }) => {\n return () => (\n <ErrorMessage\n message={\n <Text>\n We use name of folder as tagName for your custom element.\n Unfortunately, <Text bold>{tagName}</Text> is invalid tagName.\n Reason: {errorMessage}\n </Text>\n }\n hint={\n <Text>\n You can find rules for tagName here:{' '}\n <Text bold>\n https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/define#valid_custom_element_names\n </Text>\n </Text>\n }\n />\n );\n },\n InvalidSiteFrontendPackageVersion: ({ packageName, versionRange }) => {\n return () => (\n <ErrorMessage\n message={\n <Text>\n Package <Text bold>{packageName}</Text> has an invalid version\n range <Text bold>{versionRange}</Text> in your{' '}\n <Text bold>package.json</Text> file.\n </Text>\n }\n hint={\n <Text>\n The version range must follow{' '}\n <Text bold>semantic versioning</Text> rules, and it must contain a\n major version.\n <Newline />\n Read more about it here:{' '}\n <Link url=\"https://docs.npmjs.com/about-semantic-versioning\" />\n </Text>\n }\n />\n );\n },\n FailedToCreateSiteOverride: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to create site override configuration\" />\n );\n },\n FailedToGetDeploymentPipelineDescription: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get deployment pipeline details\" />\n );\n },\n FailedToGetDeploymentStatus: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get deployment status\" />\n );\n },\n NetworkError: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Network error occurred.\"\n hint={`Make sure you have an active internet connection and try again shortly.`}\n />\n );\n },\n FailedToGenerateAppMarketQueryParam: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get generate appMarket query parameter\" />\n );\n },\n FailedToParseLog: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to parse log from the server\" />\n );\n },\n AppForVersionNotFound: ({ version }) => {\n return () => (\n <ErrorMessage\n message={`Could not find app configuration for the provided version: \"${version}\"`}\n hint={`Make sure that there is an app for this version.`}\n />\n );\n },\n FailedToFetchAppForVersion: () => {\n return () => (\n <SystemErrorMessage message={`Failed to fetch app configuration`} />\n );\n },\n FailedToGetAppSecret: () => {\n return () => (\n <SystemErrorMessage\n message={`Failed to fetch app keys and configuration`}\n />\n );\n },\n FailedToConnectToLogsService: () => {\n return () => (\n <ErrorMessage message={`Failed to connect to logs service.`} />\n );\n },\n FailedToGetLogsTopology: () => {\n return () => (\n <ErrorMessage\n message={`Failed to fetch logs configuration for the given version.`}\n hint={`Try to use a different version.`}\n />\n );\n },\n FailedInstallCloudflareNoAccess: ({ path }) => {\n return () => (\n <ErrorMessage\n message={`Failed to install required binary in \"${path}\"`}\n hint={`Check that you have required permissions.`}\n />\n );\n },\n LogsConnectionTimeout: () => {\n return () => (\n <ErrorMessage message={`Log session has been closed due to timeout.`} />\n );\n },\n InvalidServicePluginImplementation: () => {\n return () => (\n <ErrorMessage\n message={`Your service plugin implementation is incorrect.`}\n />\n );\n },\n UnknownServicePlugin: ({ name }) => {\n return () => (\n <ErrorMessage\n message={`Unknown service plugin with the name of \\`${name}\\``}\n />\n );\n },\n MultilingualAppNotInstalled: () => {\n return () => (\n <ErrorMessage\n message={`Multilingual app is not installed.`}\n hint={`Please install the \"Wix Multilingual\" app in your site dashboard to use this command.`}\n />\n );\n },\n FailedToFetchPrimaryLanguage: () => {\n return () => (\n <ErrorMessage\n message=\"Failed to fetch the primary language for your site.\"\n hint=\"Please ensure Wix Multilingual is installed and configured on your site.\"\n />\n );\n },\n FailedToPushTranslations: () => {\n return () => (\n <ErrorMessage\n message=\"Failed to push translations to Wix Multilingual.\"\n hint={`Please ensure the \"Wix Multilingual\" app is installed on your site and try again.`}\n />\n );\n },\n FailedToPullTranslations: () => {\n return () => (\n <ErrorMessage\n message=\"Failed to pull translations from Wix Multilingual.\"\n hint=\"Please check your internet connection and try again.\"\n />\n );\n },\n\n InvalidServicePluginFolder: ({ relativePath }) => {\n return () => (\n <ErrorMessage\n message={`Invalid folder for service plugin in \\`${relativePath}\\``}\n />\n );\n },\n InvalidSiteOverrideID: () => {\n return () => (\n <ErrorMessage\n message={`Failed to read devSiteOverrideId from local app configurations.`}\n hint={`Restart the dev environment and make sure that the .wix/app.config.json file exists.`}\n />\n );\n },\n FailedToFindEsbuildOutputFile: () => {\n return () => (\n <ErrorMessage\n message={`Failed to find file in ESBuild output`}\n hint={`Restart the dev environment and try again.`}\n />\n );\n },\n FailedOptimizingWithEsbuild: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Failed to optimize dependency with ESBuild.`}\n explanation={`Restart the dev environment and try again.`}\n />\n );\n },\n FailedReadingEsbuildOutputFile: () => {\n return () => (\n <ErrorMessage\n message={`Failed to read ESBuild's output file`}\n hint={`Restart the dev environment and try again.`}\n />\n );\n },\n CliAppTemplateNotFound: ({ id }) => {\n return () => (\n <ErrorMessage\n message={\n <>\n Template with ID <Text bold>{id}</Text> not found.\n </>\n }\n hint=\"Make sure you are using the correct template ID\"\n />\n );\n },\n FailedToQueryCliAppTemplates: () => {\n return () => (\n <SystemErrorMessage\n message={'Failed to fetch available app templates'}\n />\n );\n },\n FailedToCreateDevCenterAppFromTemplate: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to register your application in Wix\" />\n );\n },\n FailedToQueryApps: () => {\n return () => <SystemErrorMessage message=\"Failed to query apps\" />;\n },\n FailedToGetSiteInstalledApps: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get site installed apps\" />\n );\n },\n FailedToGetSiteInstalledAppInstanceId: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get site installed app instance id\" />\n );\n },\n FailedToGetClientSpecMap: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get site client spec map\" />\n );\n },\n DeniedPermissionToGetAppSecret: () => {\n return () => (\n <ErrorMessage\n message=\"Insufficient permissions\"\n hint=\"Please log in with an account that has the required permissions to access this application\"\n />\n );\n },\n FailedToCreateVeloApp: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to create an isolated environment.\" />\n );\n },\n FailedToUpdateVeloAppFiles: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to update files in the isolated environment\" />\n );\n },\n FailedToGetFilesFromVelo: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to get initial project files\" />\n );\n },\n FailedToOpenBrowser: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to open browser.\"\n hint=\"Please make sure you have a browser installed, and it's appropriately configured\"\n />\n );\n },\n DeprecatedVersion: ({\n currentVersion,\n latestVersion,\n deprecated,\n hasCliAppInstalled,\n }) => {\n return () => (\n <OutdatedVersionMessage\n currentVersion={currentVersion}\n latestVersion={latestVersion}\n deprecated={deprecated}\n hasCliAppInstalled={hasCliAppInstalled}\n />\n );\n },\n FailedToSyncPagesTypes: () => {\n return () => <SystemErrorMessage message=\"Failed to sync pages types\" />;\n },\n FailedToInitializeSiteFsManager: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to initialize site file system manager.\"\n />\n );\n },\n FailedToGetSiteFsManagerCode: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to parse site code in local file system.\"\n />\n );\n },\n FailedToGetSiteFsManagerDocument: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to parse site document in local file system.\"\n />\n );\n },\n FailedToApplySiteFsManagerFsUpdates: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to apply site local file system updates.\"\n />\n );\n },\n FailedToApplySiteFsManagerExternalUpdates: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to apply site external updates.\"\n />\n );\n },\n FailedToSyncVeloCLIServerDocumentUpdate: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to sync local file system document updates with the Editor.\"\n />\n );\n },\n ServeDeprecated: ({ packageManagerRunCmd }) => {\n return () => (\n <ServeDeprecationMessage packageManagerRunCmd={packageManagerRunCmd} />\n );\n },\n CannotFindConfigReferencedAsset: ({ asset, configPath, field }) => {\n return () => (\n <ErrorMessage\n message={`Failed to load asset ${asset}`}\n hint={`Make sure the asset is correctly configured in \\`${configPath}\\` under the field \\`${field}\\``}\n />\n );\n },\n FailedToCreateIntellisenseAdapter: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to create intellisense adapter.\"\n />\n );\n },\n FailedToInitIntellisenseAdapterTypes: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to initialize site types.\"\n />\n );\n },\n FailedToUpdateIntellisenseAdapterTypes: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to update site types.\" />\n );\n },\n WebMethodOutsideOfProjectDirectory: ({ relativeId }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Web method \"${relativeId}\" is outside of the project directory.`}\n />\n );\n },\n FailedToCreateDraftVersion: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to retrieve release options available for your application.\" />\n );\n },\n FailedToReleaseDraftVersion: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to release a new version of your application.\" />\n );\n },\n WaitForEditorInstallationStateFailure: () => {\n return () => (\n <SystemErrorMessage\n message={`Waiting for the Editor to finish installation timed out`}\n />\n );\n },\n EditorPendingInstallationCheckTimedout: () => {\n return () => (\n <SystemErrorMessage\n message={`Editor installation details check timed out`}\n />\n );\n },\n FailedToGetSdkSlotData: () => {\n return () => (\n <SystemErrorMessage\n message={`Unable to retrieve slot details to extend`}\n />\n );\n },\n FailedToListComponentByComponentType: () => {\n return () => (\n <SystemErrorMessage\n message={`Unable to retrieve the list of available extensions for your application`}\n />\n );\n },\n FailedToParseBackofficeExtensionContainer: () => {\n return () => (\n <SystemErrorMessage\n message={`Failed to parse backoffice extension containers data`}\n />\n );\n },\n FailedToParseBackofficePages: () => {\n return () => (\n <SystemErrorMessage message={`Failed to parse backoffice pages data`} />\n );\n },\n FailedToCleanDistFolder: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={'Failed to clean the dist folder.'}\n />\n );\n },\n FailedToDeployDocument: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to deploy site document.\" />\n );\n },\n FailedToEvalBackendExtension: ({ filename, errorMessage }) => {\n return () => (\n <ErrorMessage\n message={`Failed to process file \"${filename}\", error details below:\n${errorMessage}`}\n />\n );\n },\n FailedToGetMonitoringLoaderScript: ({ dsn }) => {\n return () => (\n <SystemErrorMessage\n message={`Failed to get a monitoring loader script for DSN \"${dsn}\".`}\n />\n );\n },\n InsufficientNonInterractiveReleaseParameters: () => {\n return () => (\n <ErrorMessage\n message={`Release command in non-interactive mode requires following parameter: --version-type`}\n />\n );\n },\n DeploymentPipelineFailed: ({ tasksDescriptions }) => {\n return () => (\n <>\n <ErrorMessage\n message={`Errors in your site’s code were found while trying to build your custom code. See output below:`}\n />\n <Box paddingLeft={1} paddingTop={1} flexDirection=\"column\">\n {tasksDescriptions.map((task, index) => (\n <Fragment key={index}>\n <Alert type={task.status === 'SUCCESS' ? 'success' : 'error'}>\n [{index + 1}/{tasksDescriptions.length}] {task.taskName}...\n </Alert>\n {Object.entries(task.description).map(([path, content]) => (\n <Box\n key={path}\n paddingLeft={2}\n paddingBottom={1}\n flexDirection=\"column\"\n >\n <Text bold>{path}</Text>\n <Text>{content.trim()}</Text>\n </Box>\n ))}\n </Fragment>\n ))}\n </Box>\n </>\n );\n },\n FailedToFetchWixLockFile: () => {\n return () => (\n <SystemErrorMessage message={`Failed to fetch \"wix.lock\" file.`} />\n );\n },\n AppNameArgumentIsInvalid: ({ errorMessage }) => {\n return () => (\n <ErrorMessage\n message={errorMessage}\n hint=\"Failed to create a new application with the specified parameters. Please modify the parameters or switch to interactive mode.\"\n />\n );\n },\n ProjectNameArgumentIsInvalid: ({ errorMessage }) => {\n return () => (\n <ErrorMessage\n message={errorMessage}\n hint=\"Failed to create a new application with the specified parameters. Please modify the parameters or switch to interactive mode.\"\n />\n );\n },\n BusinessNameArgumentIsInvalid: ({ errorMessage }) => {\n return () => (\n <ErrorMessage\n message={errorMessage}\n hint=\"Failed to create a new application with provided Business Name. Please modify the parameters or switch to interactive mode.\"\n />\n );\n },\n CannotReleaseMinorInNoninteractive: () => {\n return () => (\n <ErrorMessage\n message={`Minor version release is not allowed.`}\n hint={`Please release major version.`}\n />\n );\n },\n SiteComponentConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Site component config not found at ${configPath}`}\n />\n );\n },\n SiteComponentPanelConfigNotFound: ({ configPath }) => {\n return () => (\n <ErrorMessage\n message={`Site component panel config not found at ${configPath}`}\n />\n );\n },\n SiteComponentPanelDoNotExists: ({ panelName }) => {\n return () => (\n <ErrorMessage\n message={`Site component panel with name ${panelName} do not exist`}\n />\n );\n },\n FailedToImportCliApp: () => {\n return () => (\n <ErrorMessage cause={cause} message=\"Failed to load `@wix/cli-app`.\" />\n );\n },\n FailedToIdentifyProgramFlow: ({ reason }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={reason}\n hint=\"Ensure that you are executing the command from inside a project directory.\"\n />\n );\n },\n FailedToPullEnvironment: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to pull environment variables.\" />\n );\n },\n FailedToSetEnvironmentVariable: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to set/update environment variable.\" />\n );\n },\n FailedToRemoveEnvironmentVariable: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to remove environment variable.\" />\n );\n },\n FailedToUploadStaticFiles: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to upload static files.\" />\n );\n },\n FailedCreatingAppProject: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while creating an app project.\" />\n );\n },\n FailedToGetAppProject: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while getting an app project.\" />\n );\n },\n FailedToCreateCodestoreProject: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while creating a codestore project.\" />\n );\n },\n FailedCreatingAppDeployment: () => {\n return () => (\n <SystemErrorMessage message=\"An error occoured while creating an app deployment.\" />\n );\n },\n FailedFinalizingAppDeployment: () => {\n return () => (\n <SystemErrorMessage message=\"An error occoured while completing app deployment.\" />\n );\n },\n FailedCreatingNewFunnelProject: () => {\n return () => (\n <SystemErrorMessage message=\"An error occurred while creating a new business.\" />\n );\n },\n BuildOutputMissing: ({ reason }) => {\n return () => (\n <ErrorMessage\n message=\"Project build output is missing\"\n explanation={reason}\n hint=\"Build the project before proceeding.\"\n />\n );\n },\n FailedToCreateMonitoringVitePlugin: ({ configPath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"Failed to setup monitoring vite plugin.\"\n hint={`Make sure you have the correct \\`monitoring\\` configuration in \\`${configPath}\\`.`}\n />\n );\n },\n FailedToFindAstroConfig: () => {\n return () => (\n <ErrorMessage message=\"No valid configuration file found. Please ensure that an astro.config.{js,cjs,mjs,ts} file exists in your project directory.\" />\n );\n },\n ProjectIsAlreadyLinked: () => {\n return () => (\n <ErrorMessage message=\"This project is already connected to Wix, so no changes were made.\" />\n );\n },\n ProjectIsNotLinkable: () => {\n return () => (\n <ErrorMessage message=\"Only Astro projects can be linked to Wix. The current project is missing an Astro configuration file.\" />\n );\n },\n MissingPresetCssForSiteComponent: ({\n componentId,\n presetName,\n elementBasePath,\n }) => {\n return () => (\n <ErrorMessage\n message={`Site component \"${componentId}\" is missing preset CSS file for the preset key \"${presetName}\"${\n elementBasePath\n ? ` in the element base path \"${elementBasePath}\".`\n : '.'\n }`}\n />\n );\n },\n AppInstallerSiteNotFound: ({ siteId }) => {\n return () => (\n <ErrorMessage\n message={`Site with ID \"${siteId}\" not found.`}\n hint=\"Please make sure the site exists and you have access to it.\"\n />\n );\n },\n EAccessPermissionDenied: () => {\n return () => (\n <ErrorMessage\n message={`Wix CLI doesn't have enough permission to modify files.`}\n cause={cause}\n />\n );\n },\n FailedToCreateShareUrl: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to create preview URL.\" />\n );\n },\n FailedToListShareUrls: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to list preview URLs.\" />\n );\n },\n FailedToParseNextVersion: ({ version }) => {\n return () => (\n <SystemErrorMessage\n message={`The version \"${version}\" produced by the system does not conform to the expected semantic versioning format and could not be parsed.`}\n />\n );\n },\n FailedToDistributeClientManifestUpdate: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to distribute client manifest update.\" />\n );\n },\n FailedToCreateRoutesWithMetaSiteUrl: () => {\n return () => (\n <SystemErrorMessage message=\"Failed to create routes with meta site URL.\" />\n );\n },\n FailedToGetGitHubOnboardingStatus: ({ projectId }) => {\n return () => (\n <SystemErrorMessage\n message={`Failed to get GitHub onboarding status for project ${projectId}.`}\n />\n );\n },\n FailedToInitGitHubRepository: ({ projectId }) => {\n return () => (\n <SystemErrorMessage\n message={`Failed to initialize GitHub repository for project ${projectId}.`}\n />\n );\n },\n InvalidSiteComponentElementItem: ({ elementPath }) => {\n return () => (\n <ErrorMessage\n cause={cause}\n message={`Site component element config is invalid at ${elementPath}`}\n />\n );\n },\n TrustedAppIsNotMarkedAsInternal: () => {\n return () => (\n <ErrorMessage\n message=\"Your component configuration is incorrect. It's encountering the error 'scriptAsset is not supported'. This typically indicates that your app isn't recognized as a Wix App.\"\n hint=\"To resolve this, please visit your app dashboard in Dev Center and ensure the app is marked as 'Developed by Wix'.\"\n />\n );\n },\n VibeRepositorySetupTimedout: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"The Vibe repository setup timed out. Please try again.\"\n />\n );\n },\n DevCommandFailed: () => {\n return () => (\n <ErrorMessage\n cause={cause}\n message=\"The development command failed to execute. Please review the output log above for details.\"\n />\n );\n },\n });\n}\n\nfunction formatZodIssue(issue: ZodIssue) {\n const path = issue.path.join('.');\n\n if (!path) {\n return `- ${issue.message}`;\n }\n\n return `- \\`${path}\\`: ${issue.message}`;\n}\n\nfunction formatFieldViolations(violation: {\n field: string;\n description: string;\n}) {\n return `- \\`${violation.field}\\`: ${violation.description}`;\n}\n","type TODO = any;\n\n// In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.\nfunction noop(...args: Array<any>) {}\nfunction createWeakMap<K extends object, V>(): MyWeakMap<K, V> {\n if (typeof WeakMap !== \"undefined\") {\n return new WeakMap<K, V>();\n } else {\n return fakeSetOrMap<K, V>();\n }\n}\n\ntype MyWeakMap<K extends object, V> = Pick<\n WeakMap<K, V>,\n \"delete\" | \"get\" | \"set\" | \"has\"\n>;\ntype MyWeakSetMap<K extends object, V> =\n & Pick<WeakMap<K, V>, \"delete\" | \"get\" | \"set\" | \"has\">\n & Pick<WeakSet<K>, \"add\">;\n\n/**\n * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.\n */\nfunction fakeSetOrMap<K extends object, V = any>(): MyWeakSetMap<K, V> {\n return {\n add: noop as WeakSet<K>[\"add\"],\n delete: noop as WeakMap<K, V>[\"delete\"],\n get: noop as WeakMap<K, V>[\"get\"],\n set: noop as WeakMap<K, V>[\"set\"],\n has(k: K) {\n return false;\n },\n };\n}\n\n// Safe hasOwnProperty\nconst hop = Object.prototype.hasOwnProperty;\nconst has = function (obj: object, prop: string): boolean {\n return hop.call(obj, prop);\n};\n\n// Copy all own enumerable properties from source to target\nfunction extend<T, S extends object>(target: T, source: S) {\n type Extended = T & S;\n for (const prop in source) {\n if (has(source, prop)) {\n (target as any)[prop] = source[prop];\n }\n }\n return target as Extended;\n}\n\nconst reLeadingNewline = /^[ \\t]*(?:\\r\\n|\\r|\\n)/;\nconst reTrailingNewline = /(?:\\r\\n|\\r|\\n)[ \\t]*$/;\nconst reStartsWithNewlineOrIsEmpty = /^(?:[\\r\\n]|$)/;\nconst reDetectIndentation = /(?:\\r\\n|\\r|\\n)([ \\t]*)(?:[^ \\t\\r\\n]|$)/;\nconst reOnlyWhitespaceWithAtLeastOneNewline = /^[ \\t]*[\\r\\n][ \\t\\r\\n]*$/;\n\nfunction _outdentArray(\n strings: ReadonlyArray<string>,\n firstInterpolatedValueSetsIndentationLevel: boolean,\n options: Options,\n) {\n // If first interpolated value is a reference to outdent,\n // determine indentation level from the indentation of the interpolated value.\n let indentationLevel = 0;\n\n const match = strings[0].match(reDetectIndentation);\n if (match) {\n indentationLevel = match[1].length;\n }\n\n const reSource = `(\\\\r\\\\n|\\\\r|\\\\n).{0,${indentationLevel}}`;\n const reMatchIndent = new RegExp(reSource, \"g\");\n\n if (firstInterpolatedValueSetsIndentationLevel) {\n strings = strings.slice(1);\n }\n\n const { newline, trimLeadingNewline, trimTrailingNewline } = options;\n const normalizeNewlines = typeof newline === \"string\";\n const l = strings.length;\n const outdentedStrings = strings.map((v, i) => {\n // Remove leading indentation from all lines\n v = v.replace(reMatchIndent, \"$1\");\n // Trim a leading newline from the first string\n if (i === 0 && trimLeadingNewline) {\n v = v.replace(reLeadingNewline, \"\");\n }\n // Trim a trailing newline from the last string\n if (i === l - 1 && trimTrailingNewline) {\n v = v.replace(reTrailingNewline, \"\");\n }\n // Normalize newlines\n if (normalizeNewlines) {\n v = v.replace(/\\r\\n|\\n|\\r/g, (_) => newline as string);\n }\n return v;\n });\n return outdentedStrings;\n}\n\nfunction concatStringsAndValues(\n strings: ReadonlyArray<string>,\n values: ReadonlyArray<any>,\n): string {\n let ret = \"\";\n for (let i = 0, l = strings.length; i < l; i++) {\n ret += strings[i];\n if (i < l - 1) {\n ret += values[i];\n }\n }\n return ret;\n}\n\nfunction isTemplateStringsArray(v: any): v is TemplateStringsArray {\n return has(v, \"raw\") && has(v, \"length\");\n}\n\n/**\n * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to\n * makeInstance\n * @param options\n * @return {outdent}\n */\nfunction createInstance(options: Options): Outdent {\n /** Cache of pre-processed template literal arrays */\n const arrayAutoIndentCache = createWeakMap<\n TemplateStringsArray,\n Array<string>\n >();\n /**\n * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,\n * before interpolated values are injected.\n */\n const arrayFirstInterpSetsIndentCache = createWeakMap<\n TemplateStringsArray,\n Array<string>\n >();\n\n /* tslint:disable:no-shadowed-variable */\n function outdent(\n stringsOrOptions: TemplateStringsArray,\n ...values: Array<any>\n ): string;\n function outdent(stringsOrOptions: Options): Outdent;\n function outdent(\n stringsOrOptions: TemplateStringsArray | Options,\n ...values: Array<any>\n ): string | Outdent {\n /* tslint:enable:no-shadowed-variable */\n if (isTemplateStringsArray(stringsOrOptions)) {\n const strings = stringsOrOptions;\n\n // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?\n const firstInterpolatedValueSetsIndentationLevel =\n (values[0] === outdent || values[0] === defaultOutdent) &&\n reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) &&\n reStartsWithNewlineOrIsEmpty.test(strings[1]);\n\n // Perform outdentation\n const cache = firstInterpolatedValueSetsIndentationLevel\n ? arrayFirstInterpSetsIndentCache\n : arrayAutoIndentCache;\n let renderedArray = cache.get(strings);\n if (!renderedArray) {\n renderedArray = _outdentArray(\n strings,\n firstInterpolatedValueSetsIndentationLevel,\n options,\n );\n cache.set(strings, renderedArray);\n }\n /** If no interpolated values, skip concatenation step */\n if (values.length === 0) {\n return renderedArray[0];\n }\n /** Concatenate string literals with interpolated values */\n const rendered = concatStringsAndValues(\n renderedArray,\n firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values,\n );\n\n return rendered;\n } else {\n // Create and return a new instance of outdent with the given options\n return createInstance(\n extend(extend({}, options), stringsOrOptions || {}),\n );\n }\n }\n\n const fullOutdent = extend(outdent, {\n string(str: string): string {\n return _outdentArray([str], false, options)[0];\n },\n });\n\n return fullOutdent;\n}\n\nconst defaultOutdent = createInstance({\n trimLeadingNewline: true,\n trimTrailingNewline: true,\n});\n\nexport interface Outdent {\n /**\n * Remove indentation from a template literal.\n */\n (strings: TemplateStringsArray, ...values: Array<any>): string;\n /**\n * Create and return a new Outdent instance with the given options.\n */\n (options: Options): Outdent;\n\n /**\n * Remove indentation from a string\n */\n string(str: string): string;\n\n // /**\n // * Remove indentation from a template literal, but return a tuple of the\n // * outdented TemplateStringsArray and\n // */\n // pass(strings: TemplateStringsArray, ...values: Array<any>): [TemplateStringsArray, ...Array<any>];\n}\nexport interface Options {\n trimLeadingNewline?: boolean;\n trimTrailingNewline?: boolean;\n /**\n * Normalize all newlines in the template literal to this value.\n * \n * If `null`, newlines are left untouched.\n * \n * Newlines that get normalized are '\\r\\n', '\\r', and '\\n'.\n * \n * Newlines within interpolated values are *never* normalized.\n * \n * Although intended for normalizing to '\\n' or '\\r\\n',\n * you can also set to any string; for example ' '.\n */\n newline?: string | null;\n}\n\n// Named exports. Simple and preferred.\n// import outdent from 'outdent';\nexport default defaultOutdent;\n// import {outdent} from 'outdent';\nexport { defaultOutdent as outdent };\n\n// In CommonJS environments, enable `var outdent = require('outdent');` by\n// replacing the exports object.\n// Make sure that our replacement includes the named exports from above.\ndeclare var module: any;\nif (typeof module !== \"undefined\") {\n // In webpack harmony-modules environments, module.exports is read-only,\n // so we fail gracefully.\n try {\n module.exports = defaultOutdent;\n Object.defineProperty(defaultOutdent, \"__esModule\", { value: true });\n (defaultOutdent as any).default = defaultOutdent;\n (defaultOutdent as any).outdent = defaultOutdent;\n } catch (e) {}\n}\n","import React from 'react';\nimport type { FC, ReactNode } from 'react';\nimport { ErrorDetails } from '@wix/cli-ui-kit';\nimport { isCliError } from '@wix/cli-error';\n\nfunction getOriginalCause(error?: Error) {\n if (isCliError(error)) {\n return getOriginalCause(error.cause());\n }\n\n return error;\n}\n\nexport const ErrorMessage: FC<{\n message: ReactNode;\n cause?: Error;\n explanation?: ReactNode;\n hint?: ReactNode;\n}> = ({ message, cause, explanation, hint }) => {\n const originalCause = getOriginalCause(cause);\n\n return (\n <ErrorDetails\n message={\n originalCause ? (\n <>\n {message} Cause: {originalCause.message}\n </>\n ) : (\n message\n )\n }\n hint={hint}\n explanation={explanation}\n />\n );\n};\n\nexport const SystemErrorMessage: FC<{\n message: ReactNode;\n explanation?: ReactNode;\n hint?: ReactNode;\n}> = ({ message, explanation, hint }) => (\n <ErrorDetails\n message={message}\n explanation={explanation}\n hint={\n hint ??\n 'This is probably a temporary system error and has been logged. Try again shortly.'\n }\n />\n);\n","import React from 'react';\nimport type { FC } from 'react';\nimport { I18nProvider, Trans } from '@wix/cli-i18n';\nimport { Text, Notification } from '@wix/cli-ui-kit';\nimport messages from '../messages.json' with { type: 'json' };\n\ninterface PackageDetails {\n currentVersion: string;\n latestVersion?: string;\n deprecated?: string;\n hasCliAppInstalled: boolean;\n}\n\nexport const OutdatedVersionMessage: FC<PackageDetails> = ({\n currentVersion,\n latestVersion,\n deprecated,\n hasCliAppInstalled,\n}) => {\n return (\n <I18nProvider messages={messages}>\n <Notification>\n {deprecated && (\n <Trans\n i18nKey=\"version_notifier.deprecated.message\"\n components={[<Text skin=\"secondary\" />, <Text bold />]}\n values={{\n currentVersion,\n }}\n />\n )}\n <Trans\n i18nKey=\"version_notifier.update.message\"\n components={[<Text skin=\"secondary\" />, <Text skin=\"success\" />]}\n values={{\n currentVersion,\n latestVersion,\n }}\n />\n <Trans\n i18nKey=\"version_notifier.update.instructions\"\n components={[<Text skin=\"info\" />]}\n values={{\n packages: hasCliAppInstalled\n ? 'npm i @wix/cli@latest @wix/cli-app@latest'\n : 'npm i -g @wix/cli@latest',\n }}\n />\n </Notification>\n </I18nProvider>\n );\n};\n","{\n \"user_feedback.title\": \"Your experience matters to us. Would you like to submit feedback regarding this incident?\",\n \"user_feedback.subtitle\": \"We may contact you by email in case we need more details.\",\n \"user_feedback.consent.label\": \"Submit feedback?\",\n \"user_feedback.comments.label\": \"Feedback (optional)\",\n \"user_feedback.submitted\": \"Thank you for your cooperation in helping us resolve this issue promptly.\",\n \"user_feedback.declined\": \"Thank you for your feedback.\",\n \"user_feedback.contact_us\": \"Reach us in Discord in case you have more questions: <0 />\",\n \"version_notifier.deprecated.message\": \"Your version of the Wix CLI (<0>{currentVersion}</0>) is <1>deprecated</1>\",\n \"version_notifier.update.message\": \"Update available <0>{currentVersion}</0> -> <1>{latestVersion}</1>\",\n \"version_notifier.update.instructions\": \"Run <0>{packages}</0> to update\"\n}\n","import React from 'react';\nimport type { FC } from 'react';\nimport { Box, Text, Alert } from '@wix/cli-ui-kit';\n\ninterface Props {\n packageManagerRunCmd?: string;\n}\n\nexport const ServeDeprecationMessage: FC<Props> = ({\n packageManagerRunCmd,\n}) => {\n return (\n <Box rowGap={1} paddingBottom={1} flexDirection=\"column\">\n <Alert type=\"error\">Deprecation Notice</Alert>\n <Text>\n <Text skin=\"info\">serve</Text> command is being replaced by{' '}\n <Text skin=\"info\">preview</Text> command.\n </Text>\n <Text>\n Please run{' '}\n <Text skin=\"info\">\n {packageManagerRunCmd\n ? `${packageManagerRunCmd} wix app preview`\n : 'wix app preview'}\n </Text>{' '}\n instead.\n </Text>\n </Box>\n );\n};\n","import { isType, variant, fields } from 'variant';\nimport type { VariantOf } from 'variant';\nimport {\n NodeClient,\n Scope,\n getDefaultIntegrations,\n defaultStackParser,\n makeNodeTransport,\n} from '@sentry/node';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\nimport { extractHttpError, getHttpErrorInfo } from '@wix/cli-http-client';\nimport VError from 'verror';\nimport { outdent } from 'outdent';\nimport type { CliError } from '@wix/cli-error';\nimport {\n isCliSystemError,\n normalizeError,\n CliSystemErrorCode,\n} from '@wix/cli-error';\nimport EventEmitter from 'node:events';\nimport { createEnv } from '@wix/cli-env';\n\ninterface TypedEventEmitter {\n on: (event: 'errorReported', listener: (error: CliError) => void) => this;\n emit: (event: 'errorReported', error: CliError) => boolean;\n}\n\nexport interface ErrorReporterOptions {\n dsn: string;\n release: string;\n}\n\ninterface User {\n id: string;\n}\n\ninterface UserFeedback {\n userId: string;\n eventId: string;\n feedback: string;\n}\n\nexport type ErrorReporter = ReturnType<typeof createErrorReporter>;\n\nexport const ReportErrorResult = variant({\n Reported: fields<{ eventId: string }>(),\n Ignored: {},\n});\nexport type ReportErrorResult = VariantOf<typeof ReportErrorResult>;\n\nconst reportError = (\n scope: Scope,\n originalError: CliError,\n { data }: { data?: unknown } = {}\n) => {\n if (!isCliSystemError(originalError)) {\n return ReportErrorResult.Ignored();\n }\n\n const error = isType(originalError.cliCode, CliSystemErrorCode.UnknownFailure)\n ? originalError.cliCode.error\n : originalError;\n\n const eventId = scope.captureException(error, {\n data,\n captureContext: (localScope) => {\n const httpError = extractHttpError(error);\n if (httpError) {\n localScope.setTag('request.id', httpError.requestId);\n localScope.setContext('Request Info', getHttpErrorInfo(httpError));\n }\n if (error instanceof Error) {\n localScope.setContext('Error Details', {\n Info: VError.info(error),\n 'Full Stack': VError.fullStack(error),\n });\n }\n\n const { isCI, isPR, ciName } = createEnv();\n\n localScope.setTag('ci', yesOrNo(isCI));\n localScope.setTag('ci.name', ciName);\n\n localScope.setContext('CI', {\n Name: ciName,\n 'Is CI': yesOrNo(isCI),\n 'Is PR': yesOrNo(isPR),\n });\n\n return localScope;\n },\n });\n\n return ReportErrorResult.Reported({ eventId });\n};\n\nexport function createErrorReporter({ dsn, release }: ErrorReporterOptions) {\n const { sentryDsn: sentryDsnOverride } = getTestOverrides();\n\n // https://docs.sentry.io/platforms/javascript/best-practices/multiple-sentry-instances/\n const sentryClient = new NodeClient({\n enabled:\n sentryDsnOverride !== undefined || process.env.NODE_ENV === 'production',\n dsn: sentryDsnOverride ?? dsn,\n release,\n integrations: getDefaultIntegrations({}).filter(\n (integration) =>\n integration.name !== 'OnUnhandledRejection' &&\n integration.name !== 'OnUncaughtException' &&\n // By default, @sentry/node adds metadata about installed packages.\n integration.name !== 'Modules'\n ),\n stackParser: defaultStackParser,\n transport: makeNodeTransport,\n beforeSend(event) {\n // By default @sentry/node includes the local hostname as `server_name`\n // which is sensitive and not useful.\n\n delete event.server_name;\n return event;\n },\n // Since we pass `requestInfo`, the default depth of 3\n // redacts most useful info passed from API error responses\n // so we increase it to include more of the potential error http repsonse.\n normalizeDepth: 10,\n });\n\n const sentryScope = new Scope();\n sentryScope.setClient(sentryClient);\n sentryClient.init();\n\n const emitter: TypedEventEmitter = new EventEmitter();\n\n return {\n on: emitter.on.bind(emitter),\n reportError: (\n originalError: unknown,\n { data }: { data?: unknown } = {}\n ) => {\n const error = normalizeError(originalError);\n const result = reportError(sentryScope, error, { data });\n\n emitter.emit('errorReported', error);\n\n return result;\n },\n reportUserFeedback: async ({ userId, eventId, feedback }: UserFeedback) => {\n /**\n * Importing @sentry/browser because it includes the `captureUserFeedback` method\n * which is not available in @sentry/node.\n * This is a workaround until the method is added to @sentry/node.\n * See: https://github.com/getsentry/sentry-javascript/issues/11072\n */\n const { BrowserClient } = await import('@sentry/browser');\n\n const client = new BrowserClient({\n enabled: sentryClient.getOptions().enabled,\n dsn: sentryClient.getOptions().dsn,\n integrations: [],\n transport: makeNodeTransport,\n stackParser: defaultStackParser,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-deprecated\n client.captureUserFeedback({\n event_id: eventId,\n name: '',\n email: `${userId}@wix.com`,\n comments: outdent`\n ---\n user: https://bo.wix.com/um/users/${userId}\n ---\n ${feedback}\n `,\n });\n },\n setContext: (name: string, context: Record<string, unknown>) =>\n sentryScope.setContext(name, context),\n setTag: (key: string, value: string) => sentryScope.setTag(key, value),\n setUser: (user: User) => sentryScope.setUser(user),\n getUser: (): User | undefined => {\n const user = sentryScope.getUser();\n if (typeof user?.id === 'string') {\n return { id: user.id };\n }\n },\n };\n}\n\nfunction yesOrNo(value: boolean | null) {\n if (value == null) {\n return null;\n }\n return value ? 'yes' : 'no';\n}\n","export { httpIntegration } from './integrations/http.js';\nexport { nativeNodeFetchIntegration } from './integrations/node-fetch.js';\nexport { consoleIntegration } from './integrations/console.js';\nexport { nodeContextIntegration } from './integrations/context.js';\nexport { contextLinesIntegration } from './integrations/contextlines.js';\nexport { localVariablesIntegration } from './integrations/local-variables/index.js';\nexport { modulesIntegration } from './integrations/modules.js';\nexport { onUncaughtExceptionIntegration } from './integrations/onuncaughtexception.js';\nexport { onUnhandledRejectionIntegration } from './integrations/onunhandledrejection.js';\nexport { anrIntegration } from './integrations/anr/index.js';\nexport { expressErrorHandler, expressIntegration, setupExpressErrorHandler } from './integrations/tracing/express.js';\nexport { fastifyIntegration, setupFastifyErrorHandler } from './integrations/tracing/fastify.js';\nexport { graphqlIntegration } from './integrations/tracing/graphql.js';\nexport { mongoIntegration } from './integrations/tracing/mongo.js';\nexport { mongooseIntegration } from './integrations/tracing/mongoose.js';\nexport { mysqlIntegration } from './integrations/tracing/mysql.js';\nexport { mysql2Integration } from './integrations/tracing/mysql2.js';\nexport { redisIntegration } from './integrations/tracing/redis.js';\nexport { nestIntegration, setupNestErrorHandler } from './integrations/tracing/nest.js';\nexport { postgresIntegration } from './integrations/tracing/postgres.js';\nexport { prismaIntegration } from './integrations/tracing/prisma.js';\nexport { hapiIntegration, setupHapiErrorHandler } from './integrations/tracing/hapi/index.js';\nexport { koaIntegration, setupKoaErrorHandler } from './integrations/tracing/koa.js';\nexport { connectIntegration, setupConnectErrorHandler } from './integrations/tracing/connect.js';\nexport { spotlightIntegration } from './integrations/spotlight.js';\nexport { SentryContextManager } from './otel/contextManager.js';\nexport { generateInstrumentOnce } from './otel/instrument.js';\nexport { getDefaultIntegrations, getDefaultIntegrationsWithoutPerformance, init, initWithoutDefaultIntegrations, validateOpenTelemetrySetup } from './sdk/index.js';\nexport { initOpenTelemetry, preloadOpenTelemetry } from './sdk/initOtel.js';\nexport { getAutoPerformanceIntegrations } from './integrations/tracing/index.js';\nexport { defaultStackParser, getSentryRelease } from './sdk/api.js';\nexport { createGetModuleFromFilename } from './utils/module.js';\nexport { makeNodeTransport } from './transports/http.js';\nexport { NodeClient } from './sdk/client.js';\nexport { cron } from './cron/index.js';\nexport { DEFAULT_USER_INCLUDES, addRequestDataToEvent, extractRequestData } from '@sentry/utils';\nexport { addOpenTelemetryInstrumentation, continueTrace, setOpenTelemetryContextAsyncContextStrategy as setNodeAsyncContextStrategy } from '@sentry/opentelemetry';\nexport { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, captureSession, close, createTransport, debugIntegration, dedupeIntegration, endSession, extraErrorDataIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentHub, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, inboundFiltersIntegration, isInitialized, lastEventId, linkedErrorsIntegration, metricsDefault as metrics, parameterize, requestDataIntegration, rewriteFramesIntegration, sessionTimingIntegration, setContext, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanToBaggageHeader, spanToJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSession, startSpan, startSpanManual, trpcMiddleware, withActiveSpan, withIsolationScope, withMonitor, withScope, zodErrorsIntegration } from '@sentry/core';\n//# sourceMappingURL=index.js.map\n","import type { SpanKind, SpanStatus } from '@opentelemetry/api';\nimport type { ReadableSpan, TimedEvent } from '@opentelemetry/sdk-trace-base';\n\nimport type { AbstractSpan } from '../types';\n\n/**\n * Check if a given span has attributes.\n * This is necessary because the base `Span` type does not have attributes,\n * so in places where we are passed a generic span, we need to check if we want to access them.\n */\nexport function spanHasAttributes<SpanType extends AbstractSpan>(\n span: SpanType,\n): span is SpanType & { attributes: ReadableSpan['attributes'] } {\n const castSpan = span as ReadableSpan;\n return !!castSpan.attributes && typeof castSpan.attributes === 'object';\n}\n\n/**\n * Check if a given span has a kind.\n * This is necessary because the base `Span` type does not have a kind,\n * so in places where we are passed a generic span, we need to check if we want to access it.\n */\nexport function spanHasKind<SpanType extends AbstractSpan>(span: SpanType): span is SpanType & { kind: SpanKind } {\n const castSpan = span as ReadableSpan;\n return !!castSpan.kind;\n}\n\n/**\n * Check if a given span has a status.\n * This is necessary because the base `Span` type does not have a status,\n * so in places where we are passed a generic span, we need to check if we want to access it.\n */\nexport function spanHasStatus<SpanType extends AbstractSpan>(\n span: SpanType,\n): span is SpanType & { status: SpanStatus } {\n const castSpan = span as ReadableSpan;\n return !!castSpan.status;\n}\n\n/**\n * Check if a given span has a name.\n * This is necessary because the base `Span` type does not have a name,\n * so in places where we are passed a generic span, we need to check if we want to access it.\n */\nexport function spanHasName<SpanType extends AbstractSpan>(span: SpanType): span is SpanType & { name: string } {\n const castSpan = span as ReadableSpan;\n return !!castSpan.name;\n}\n\n/**\n * Check if a given span has a kind.\n * This is necessary because the base `Span` type does not have a kind,\n * so in places where we are passed a generic span, we need to check if we want to access it.\n */\nexport function spanHasParentId<SpanType extends AbstractSpan>(\n span: SpanType,\n): span is SpanType & { parentSpanId: string } {\n const castSpan = span as ReadableSpan;\n return !!castSpan.parentSpanId;\n}\n\n/**\n * Check if a given span has events.\n * This is necessary because the base `Span` type does not have events,\n * so in places where we are passed a generic span, we need to check if we want to access it.\n */\nexport function spanHasEvents<SpanType extends AbstractSpan>(\n span: SpanType,\n): span is SpanType & { events: TimedEvent[] } {\n const castSpan = span as ReadableSpan;\n return Array.isArray(castSpan.events);\n}\n","import type { Span } from '@opentelemetry/api';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL } from '@opentelemetry/semantic-conventions';\nimport type { SanitizedRequestData } from '@sentry/types';\nimport { getSanitizedUrlString, parseUrl } from '@sentry/utils';\n\nimport { spanHasAttributes } from './spanTypes';\n\n/**\n * Get sanitizied request data from an OTEL span.\n */\nexport function getRequestSpanData(span: Span | ReadableSpan): Partial<SanitizedRequestData> {\n // The base `Span` type has no `attributes`, so we need to guard here against that\n if (!spanHasAttributes(span)) {\n return {};\n }\n\n const data: Partial<SanitizedRequestData> = {\n url: span.attributes[SEMATTRS_HTTP_URL] as string | undefined,\n 'http.method': span.attributes[SEMATTRS_HTTP_METHOD] as string | undefined,\n };\n\n // Default to GET if URL is set but method is not\n if (!data['http.method'] && data.url) {\n data['http.method'] = 'GET';\n }\n\n try {\n const urlStr = span.attributes[SEMATTRS_HTTP_URL];\n if (typeof urlStr === 'string') {\n const url = parseUrl(urlStr);\n\n data.url = getSanitizedUrlString(url);\n\n if (url.search) {\n data['http.query'] = url.search;\n }\n if (url.hash) {\n data['http.fragment'] = url.hash;\n }\n }\n } catch {\n // ignore\n }\n\n return data;\n}\n","import type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport type { BaseClient } from '@sentry/core';\nimport { SDK_VERSION } from '@sentry/core';\nimport type { Client } from '@sentry/types';\n\nimport type { OpenTelemetryClient as OpenTelemetryClientInterface } from '../types';\n\n// Typescript complains if we do not use `...args: any[]` for the mixin, with:\n// A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Wrap an Client with things we need for OpenTelemetry support.\n *\n * Usage:\n * const OpenTelemetryClient = getWrappedClientClass(NodeClient);\n * const client = new OpenTelemetryClient(options);\n */\nexport function wrapClientClass<\n ClassConstructor extends new (\n ...args: any[]\n ) => Client & BaseClient<any>,\n WrappedClassConstructor extends new (\n ...args: any[]\n ) => Client & BaseClient<any> & OpenTelemetryClientInterface,\n>(ClientClass: ClassConstructor): WrappedClassConstructor {\n class OpenTelemetryClient extends ClientClass implements OpenTelemetryClientInterface {\n public traceProvider: BasicTracerProvider | undefined;\n private _tracer: Tracer | undefined;\n\n public constructor(...args: any[]) {\n super(...args);\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/opentelemetry';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n /**\n * @inheritDoc\n */\n public async flush(timeout?: number): Promise<boolean> {\n const provider = this.traceProvider;\n const spanProcessor = provider?.activeSpanProcessor;\n\n if (spanProcessor) {\n await spanProcessor.forceFlush();\n }\n\n return super.flush(timeout);\n }\n }\n\n return OpenTelemetryClient as unknown as WrappedClassConstructor;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import { SpanKind } from '@opentelemetry/api';\n\nimport type { AbstractSpan } from '../types';\nimport { spanHasKind } from './spanTypes';\n\n/**\n * Get the span kind from a span.\n * For whatever reason, this is not public API on the generic \"Span\" type,\n * so we need to check if we actually have a `SDKTraceBaseSpan` where we can fetch this from.\n * Otherwise, we fall back to `SpanKind.INTERNAL`.\n */\nexport function getSpanKind(span: AbstractSpan): SpanKind {\n if (spanHasKind(span)) {\n return span.kind;\n }\n\n return SpanKind.INTERNAL;\n}\n","import { createContextKey } from '@opentelemetry/api';\n\nexport const SENTRY_TRACE_HEADER = 'sentry-trace';\nexport const SENTRY_BAGGAGE_HEADER = 'baggage';\n\nexport const SENTRY_TRACE_STATE_DSC = 'sentry.dsc';\nexport const SENTRY_TRACE_STATE_PARENT_SPAN_ID = 'sentry.parent_span_id';\nexport const SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING = 'sentry.sampled_not_recording';\nexport const SENTRY_TRACE_STATE_URL = 'sentry.url';\n\nexport const SENTRY_SCOPES_CONTEXT_KEY = createContextKey('sentry_scopes');\n\nexport const SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_isolation_scope');\n\nexport const SENTRY_FORK_SET_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_set_scope');\n\nexport const SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY = createContextKey('sentry_fork_set_isolation_scope');\n","import type { Context } from '@opentelemetry/api';\nimport type { Scope } from '@sentry/types';\nimport { addNonEnumerableProperty } from '@sentry/utils';\n\nimport { SENTRY_SCOPES_CONTEXT_KEY } from '../constants';\nimport type { CurrentScopes } from '../types';\n\nconst SCOPE_CONTEXT_FIELD = '_scopeContext';\n\n/**\n * Try to get the current scopes from the given OTEL context.\n * This requires a Context Manager that was wrapped with getWrappedContextManager.\n */\nexport function getScopesFromContext(context: Context): CurrentScopes | undefined {\n return context.getValue(SENTRY_SCOPES_CONTEXT_KEY) as CurrentScopes | undefined;\n}\n\n/**\n * Set the current scopes on an OTEL context.\n * This will return a forked context with the Propagation Context set.\n */\nexport function setScopesOnContext(context: Context, scopes: CurrentScopes): Context {\n return context.setValue(SENTRY_SCOPES_CONTEXT_KEY, scopes);\n}\n\n/**\n * Set the context on the scope so we can later look it up.\n * We need this to get the context from the scope in the `trace` functions.\n */\nexport function setContextOnScope(scope: Scope, context: Context): void {\n addNonEnumerableProperty(scope, SCOPE_CONTEXT_FIELD, context);\n}\n\n/**\n * Get the context related to a scope.\n * TODO v8: Use this for the `trace` functions.\n * */\nexport function getContextFromScope(scope: Scope): Context | undefined {\n return (scope as { [SCOPE_CONTEXT_FIELD]?: Context })[SCOPE_CONTEXT_FIELD];\n}\n","import { SEMATTRS_HTTP_URL } from '@opentelemetry/semantic-conventions';\nimport { getClient, isSentryRequestUrl } from '@sentry/core';\n\nimport type { AbstractSpan } from '../types';\nimport { spanHasAttributes } from './spanTypes';\n\n/**\n *\n * @param otelSpan Checks wheter a given OTEL Span is an http request to sentry.\n * @returns boolean\n */\nexport function isSentryRequestSpan(span: AbstractSpan): boolean {\n if (!spanHasAttributes(span)) {\n return false;\n }\n\n const { attributes } = span;\n\n const httpUrl = attributes[SEMATTRS_HTTP_URL];\n\n if (!httpUrl) {\n return false;\n }\n\n return isSentryRequestUrl(httpUrl.toString(), getClient());\n}\n","import type { AttributeValue, Attributes } from '@opentelemetry/api';\nimport { SpanKind } from '@opentelemetry/api';\nimport {\n SEMATTRS_DB_STATEMENT,\n SEMATTRS_DB_SYSTEM,\n SEMATTRS_FAAS_TRIGGER,\n SEMATTRS_HTTP_METHOD,\n SEMATTRS_HTTP_ROUTE,\n SEMATTRS_HTTP_TARGET,\n SEMATTRS_HTTP_URL,\n SEMATTRS_MESSAGING_SYSTEM,\n SEMATTRS_RPC_SERVICE,\n} from '@opentelemetry/semantic-conventions';\nimport type { SpanAttributes, TransactionSource } from '@sentry/types';\nimport { getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment } from '@sentry/utils';\n\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP } from '@sentry/core';\nimport type { AbstractSpan } from '../types';\nimport { getSpanKind } from './getSpanKind';\nimport { spanHasAttributes, spanHasName } from './spanTypes';\n\ninterface SpanDescription {\n op: string | undefined;\n description: string;\n source: TransactionSource;\n data?: Record<string, string | undefined>;\n}\n\n/**\n * Infer the op & description for a set of name, attributes and kind of a span.\n */\nexport function inferSpanData(name: string, attributes: SpanAttributes, kind: SpanKind): SpanDescription {\n // This attribute is intentionally exported as a SEMATTR constant because it should stay intimite API\n if (attributes['sentry.skip_span_data_inference']) {\n return {\n op: undefined,\n description: name,\n source: 'custom',\n data: {\n // Suggest to callers of `parseSpanDescription` to wipe the hint because it is unnecessary data in the end.\n 'sentry.skip_span_data_inference': undefined,\n },\n };\n }\n\n // if http.method exists, this is an http request span\n //\n // TODO: Referencing `http.request.method` is a temporary workaround until the semantic\n // conventions export an attribute key for it.\n const httpMethod = attributes['http.request.method'] || attributes[SEMATTRS_HTTP_METHOD];\n if (httpMethod) {\n return descriptionForHttpMethod({ attributes, name, kind }, httpMethod);\n }\n\n const dbSystem = attributes[SEMATTRS_DB_SYSTEM];\n const opIsCache =\n typeof attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] === 'string' &&\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP].startsWith('cache.');\n\n // If db.type exists then this is a database call span\n // If the Redis DB is used as a cache, the span description should not be changed\n if (dbSystem && !opIsCache) {\n return descriptionForDbSystem({ attributes, name });\n }\n\n // If rpc.service exists then this is a rpc call span.\n const rpcService = attributes[SEMATTRS_RPC_SERVICE];\n if (rpcService) {\n return {\n op: 'rpc',\n description: name,\n source: 'route',\n };\n }\n\n // If messaging.system exists then this is a messaging system span.\n const messagingSystem = attributes[SEMATTRS_MESSAGING_SYSTEM];\n if (messagingSystem) {\n return {\n op: 'message',\n description: name,\n source: 'route',\n };\n }\n\n // If faas.trigger exists then this is a function as a service span.\n const faasTrigger = attributes[SEMATTRS_FAAS_TRIGGER];\n if (faasTrigger) {\n return { op: faasTrigger.toString(), description: name, source: 'route' };\n }\n\n return { op: undefined, description: name, source: 'custom' };\n}\n\n/**\n * Extract better op/description from an otel span.\n *\n * Based on https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/7422ce2a06337f68a59b552b8c5a2ac125d6bae5/exporter/sentryexporter/sentry_exporter.go#L306\n */\nexport function parseSpanDescription(span: AbstractSpan): SpanDescription {\n const attributes = spanHasAttributes(span) ? span.attributes : {};\n const name = spanHasName(span) ? span.name : '<unknown>';\n const kind = getSpanKind(span);\n\n return inferSpanData(name, attributes, kind);\n}\n\nfunction descriptionForDbSystem({ attributes, name }: { attributes: Attributes; name: string }): SpanDescription {\n // Use DB statement (Ex \"SELECT * FROM table\") if possible as description.\n const statement = attributes[SEMATTRS_DB_STATEMENT];\n\n const description = statement ? statement.toString() : name;\n\n return { op: 'db', description, source: 'task' };\n}\n\n/** Only exported for tests. */\nexport function descriptionForHttpMethod(\n { name, kind, attributes }: { name: string; attributes: Attributes; kind: SpanKind },\n httpMethod: AttributeValue,\n): SpanDescription {\n const opParts = ['http'];\n\n switch (kind) {\n case SpanKind.CLIENT:\n opParts.push('client');\n break;\n case SpanKind.SERVER:\n opParts.push('server');\n break;\n }\n\n const { urlPath, url, query, fragment, hasRoute } = getSanitizedUrl(attributes, kind);\n\n if (!urlPath) {\n return { op: opParts.join('.'), description: name, source: 'custom' };\n }\n\n // Ex. description=\"GET /api/users\".\n const description = `${httpMethod} ${urlPath}`;\n\n // If `httpPath` is a root path, then we can categorize the transaction source as route.\n const source: TransactionSource = hasRoute || urlPath === '/' ? 'route' : 'url';\n\n const data: Record<string, string> = {};\n\n if (url) {\n data.url = url;\n }\n if (query) {\n data['http.query'] = query;\n }\n if (fragment) {\n data['http.fragment'] = fragment;\n }\n\n return {\n op: opParts.join('.'),\n description,\n source,\n data,\n };\n}\n\n/** Exported for tests only */\nexport function getSanitizedUrl(\n attributes: Attributes,\n kind: SpanKind,\n): {\n url: string | undefined;\n urlPath: string | undefined;\n query: string | undefined;\n fragment: string | undefined;\n hasRoute: boolean;\n} {\n // This is the relative path of the URL, e.g. /sub\n const httpTarget = attributes[SEMATTRS_HTTP_TARGET];\n // This is the full URL, including host & query params etc., e.g. https://example.com/sub?foo=bar\n const httpUrl = attributes[SEMATTRS_HTTP_URL];\n // This is the normalized route name - may not always be available!\n const httpRoute = attributes[SEMATTRS_HTTP_ROUTE];\n\n const parsedUrl = typeof httpUrl === 'string' ? parseUrl(httpUrl) : undefined;\n const url = parsedUrl ? getSanitizedUrlString(parsedUrl) : undefined;\n const query = parsedUrl && parsedUrl.search ? parsedUrl.search : undefined;\n const fragment = parsedUrl && parsedUrl.hash ? parsedUrl.hash : undefined;\n\n if (typeof httpRoute === 'string') {\n return { urlPath: httpRoute, url, query, fragment, hasRoute: true };\n }\n\n if (kind === SpanKind.SERVER && typeof httpTarget === 'string') {\n return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };\n }\n\n if (parsedUrl) {\n return { urlPath: url, url, query, fragment, hasRoute: false };\n }\n\n // fall back to target even for client spans, if no URL is present\n if (typeof httpTarget === 'string') {\n return { urlPath: stripUrlQueryAndFragment(httpTarget), url, query, fragment, hasRoute: false };\n }\n\n return { urlPath: undefined, url, query, fragment, hasRoute: false };\n}\n","import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, spanToJSON } from '@sentry/core';\nimport type { Client } from '@sentry/types';\nimport { parseSpanDescription } from './parseSpanDescription';\nimport { spanHasName } from './spanTypes';\n\n/**\n * Setup a DSC handler on the passed client,\n * ensuring that the transaction name is inferred from the span correctly.\n */\nexport function enhanceDscWithOpenTelemetryRootSpanName(client: Client): void {\n client.on('createDsc', (dsc, rootSpan) => {\n // We want to overwrite the transaction on the DSC that is created by default in core\n // The reason for this is that we want to infer the span name, not use the initial one\n // Otherwise, we'll get names like \"GET\" instead of e.g. \"GET /foo\"\n // `parseSpanDescription` takes the attributes of the span into account for the name\n // This mutates the passed-in DSC\n if (rootSpan) {\n const jsonSpan = spanToJSON(rootSpan);\n const attributes = jsonSpan.data || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n const { description } = spanHasName(rootSpan) ? parseSpanDescription(rootSpan) : { description: undefined };\n if (source !== 'url' && description) {\n dsc.transaction = description;\n }\n }\n });\n}\n","import { TraceState } from '@opentelemetry/core';\nimport type { DynamicSamplingContext } from '@sentry/types';\nimport { dynamicSamplingContextToSentryBaggageHeader } from '@sentry/utils';\nimport {\n SENTRY_TRACE_STATE_DSC,\n SENTRY_TRACE_STATE_PARENT_SPAN_ID,\n SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING,\n} from '../constants';\n\n/**\n * Generate a TraceState for the given data.\n */\nexport function makeTraceState({\n parentSpanId,\n dsc,\n sampled,\n}: {\n parentSpanId?: string;\n dsc?: Partial<DynamicSamplingContext>;\n sampled?: boolean;\n}): TraceState {\n // We store the DSC as OTEL trace state on the span context\n const dscString = dsc ? dynamicSamplingContextToSentryBaggageHeader(dsc) : undefined;\n\n // We _always_ set the parent span ID, even if it is empty\n // If we'd set this to 'undefined' we could not know if the trace state was set, but there was no parentSpanId,\n // vs the trace state was not set at all (in which case we want to do fallback handling)\n // If `''`, it should be considered \"no parent\"\n const traceStateBase = new TraceState().set(SENTRY_TRACE_STATE_PARENT_SPAN_ID, parentSpanId || '');\n\n const traceStateWithDsc = dscString ? traceStateBase.set(SENTRY_TRACE_STATE_DSC, dscString) : traceStateBase;\n\n // We also specifically want to store if this is sampled to be not recording,\n // or unsampled (=could be either sampled or not)\n return sampled === false ? traceStateWithDsc.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') : traceStateWithDsc;\n}\n","import type { SpanContext } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport type { PropagationContext } from '@sentry/types';\nimport { makeTraceState } from './makeTraceState';\n\n/**\n * Generates a SpanContext that represents a PropagationContext.\n * This can be set on a `context` to make this a (virtual) active span.\n */\nexport function generateSpanContextForPropagationContext(propagationContext: PropagationContext): SpanContext {\n // We store the DSC as OTEL trace state on the span context\n const traceState = makeTraceState({\n parentSpanId: propagationContext.parentSpanId,\n dsc: propagationContext.dsc,\n sampled: propagationContext.sampled,\n });\n\n const spanContext: SpanContext = {\n traceId: propagationContext.traceId,\n spanId: propagationContext.parentSpanId || '',\n isRemote: true,\n traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,\n traceState,\n };\n\n return spanContext;\n}\n","import type { Span } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\n\n/**\n * Returns the currently active span.\n */\nexport function getActiveSpan(): Span | undefined {\n return trace.getActiveSpan();\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import type { SpanContext } from '@opentelemetry/api';\nimport { TraceFlags } from '@opentelemetry/api';\nimport { baggageHeaderToDynamicSamplingContext } from '@sentry/utils';\nimport { SENTRY_TRACE_STATE_DSC, SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING } from '../constants';\n\n/**\n * OpenTelemetry only knows about SAMPLED or NONE decision,\n * but for us it is important to differentiate between unset and unsampled.\n *\n * Both of these are identified as `traceFlags === TracegFlags.NONE`,\n * but we additionally look at a special trace state to differentiate between them.\n */\nexport function getSamplingDecision(spanContext: SpanContext): boolean | undefined {\n const { traceFlags, traceState } = spanContext;\n\n const sampledNotRecording = traceState ? traceState.get(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING) === '1' : false;\n\n // If trace flag is `SAMPLED`, we interpret this as sampled\n // If it is `NONE`, it could mean either it was sampled to be not recorder, or that it was not sampled at all\n // For us this is an important difference, sow e look at the SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING\n // to identify which it is\n if (traceFlags === TraceFlags.SAMPLED) {\n return true;\n }\n\n if (sampledNotRecording) {\n return false;\n }\n\n // Fall back to DSC as a last resort, that may also contain `sampled`...\n const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;\n const dsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;\n\n if (dsc?.sampled === 'true') {\n return true;\n }\n if (dsc?.sampled === 'false') {\n return false;\n }\n\n return undefined;\n}\n","type OpenTelemetryElement = 'SentrySpanProcessor' | 'SentryContextManager' | 'SentryPropagator' | 'SentrySampler';\n\nconst setupElements = new Set<OpenTelemetryElement>();\n\n/** Get all the OpenTelemetry elements that have been set up. */\nexport function openTelemetrySetupCheck(): OpenTelemetryElement[] {\n return Array.from(setupElements);\n}\n\n/** Mark an OpenTelemetry element as setup. */\nexport function setIsSetup(element: OpenTelemetryElement): void {\n setupElements.add(element);\n}\n\n/** Only exported for tests. */\nexport function clearOpenTelemetrySetupCheck(): void {\n setupElements.clear();\n}\n","import type { Baggage, Context, Span, TextMapGetter, TextMapSetter } from '@opentelemetry/api';\nimport { INVALID_TRACEID } from '@opentelemetry/api';\nimport { context } from '@opentelemetry/api';\nimport { propagation, trace } from '@opentelemetry/api';\nimport { W3CBaggagePropagator, isTracingSuppressed } from '@opentelemetry/core';\nimport { SEMATTRS_HTTP_URL } from '@opentelemetry/semantic-conventions';\nimport type { continueTrace } from '@sentry/core';\nimport { hasTracingEnabled } from '@sentry/core';\nimport { getRootSpan } from '@sentry/core';\nimport { spanToJSON } from '@sentry/core';\nimport {\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromClient,\n getDynamicSamplingContextFromSpan,\n getIsolationScope,\n} from '@sentry/core';\nimport type { DynamicSamplingContext, Options, PropagationContext } from '@sentry/types';\nimport {\n LRUMap,\n SENTRY_BAGGAGE_KEY_PREFIX,\n baggageHeaderToDynamicSamplingContext,\n generateSentryTraceHeader,\n logger,\n parseBaggageHeader,\n propagationContextFromHeaders,\n stringMatchesSomePattern,\n} from '@sentry/utils';\n\nimport {\n SENTRY_BAGGAGE_HEADER,\n SENTRY_TRACE_HEADER,\n SENTRY_TRACE_STATE_DSC,\n SENTRY_TRACE_STATE_PARENT_SPAN_ID,\n SENTRY_TRACE_STATE_URL,\n} from './constants';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getScopesFromContext, setScopesOnContext } from './utils/contextData';\nimport { generateSpanContextForPropagationContext } from './utils/generateSpanContextForPropagationContext';\nimport { getSamplingDecision } from './utils/getSamplingDecision';\nimport { setIsSetup } from './utils/setupCheck';\n\n/** Get the Sentry propagation context from a span context. */\nexport function getPropagationContextFromSpan(span: Span): PropagationContext {\n const spanContext = span.spanContext();\n const { traceId, spanId, traceState } = spanContext;\n\n // When we have a dsc trace state, it means this came from the incoming trace\n // Then this takes presedence over the root span\n const dscString = traceState ? traceState.get(SENTRY_TRACE_STATE_DSC) : undefined;\n const traceStateDsc = dscString ? baggageHeaderToDynamicSamplingContext(dscString) : undefined;\n\n const parentSpanId = traceState ? traceState.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID) || undefined : undefined;\n\n const sampled = getSamplingDecision(spanContext);\n\n // No trace state? --> Take DSC from root span\n const dsc = traceStateDsc || getDynamicSamplingContextFromSpan(getRootSpan(span));\n\n return {\n traceId,\n spanId,\n sampled,\n parentSpanId,\n dsc,\n };\n}\n\n/**\n * Injects and extracts `sentry-trace` and `baggage` headers from carriers.\n */\nexport class SentryPropagator extends W3CBaggagePropagator {\n /** A map of URLs that have already been checked for if they match tracePropagationTargets. */\n private _urlMatchesTargetsMap: LRUMap<string, boolean>;\n\n public constructor() {\n super();\n setIsSetup('SentryPropagator');\n\n // We're caching results so we don't have to recompute regexp every time we create a request.\n this._urlMatchesTargetsMap = new LRUMap<string, boolean>(100);\n }\n\n /**\n * @inheritDoc\n */\n public inject(context: Context, carrier: unknown, setter: TextMapSetter): void {\n if (isTracingSuppressed(context)) {\n DEBUG_BUILD && logger.log('[Tracing] Not injecting trace data for url because tracing is suppressed.');\n return;\n }\n\n const activeSpan = trace.getSpan(context);\n const url = activeSpan && getCurrentURL(activeSpan);\n\n const tracePropagationTargets = getClient()?.getOptions()?.tracePropagationTargets;\n if (\n typeof url === 'string' &&\n tracePropagationTargets &&\n !this._shouldInjectTraceData(tracePropagationTargets, url)\n ) {\n DEBUG_BUILD &&\n logger.log(\n '[Tracing] Not injecting trace data for url because it does not match tracePropagationTargets:',\n url,\n );\n return;\n }\n\n const existingBaggageHeader = getExistingBaggage(carrier);\n let baggage = propagation.getBaggage(context) || propagation.createBaggage({});\n\n const { dynamicSamplingContext, traceId, spanId, sampled } = getInjectionData(context);\n\n if (existingBaggageHeader) {\n const baggageEntries = parseBaggageHeader(existingBaggageHeader);\n\n if (baggageEntries) {\n Object.entries(baggageEntries).forEach(([key, value]) => {\n baggage = baggage.setEntry(key, { value });\n });\n }\n }\n\n if (dynamicSamplingContext) {\n baggage = Object.entries(dynamicSamplingContext).reduce<Baggage>((b, [dscKey, dscValue]) => {\n if (dscValue) {\n return b.setEntry(`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`, { value: dscValue });\n }\n return b;\n }, baggage);\n }\n\n // We also want to avoid setting the default OTEL trace ID, if we get that for whatever reason\n if (traceId && traceId !== INVALID_TRACEID) {\n setter.set(carrier, SENTRY_TRACE_HEADER, generateSentryTraceHeader(traceId, spanId, sampled));\n }\n\n super.inject(propagation.setBaggage(context, baggage), carrier, setter);\n }\n\n /**\n * @inheritDoc\n */\n public extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {\n const maybeSentryTraceHeader: string | string[] | undefined = getter.get(carrier, SENTRY_TRACE_HEADER);\n const baggage = getter.get(carrier, SENTRY_BAGGAGE_HEADER);\n\n const sentryTrace = maybeSentryTraceHeader\n ? Array.isArray(maybeSentryTraceHeader)\n ? maybeSentryTraceHeader[0]\n : maybeSentryTraceHeader\n : undefined;\n\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n\n // Add remote parent span context\n const ctxWithSpanContext = getContextWithRemoteActiveSpan(context, { sentryTrace, baggage });\n\n // Also update the scope on the context (to be sure this is picked up everywhere)\n const scopes = getScopesFromContext(ctxWithSpanContext);\n const newScopes = {\n scope: scopes ? scopes.scope.clone() : getCurrentScope().clone(),\n isolationScope: scopes ? scopes.isolationScope : getIsolationScope(),\n };\n newScopes.scope.setPropagationContext(propagationContext);\n\n return setScopesOnContext(ctxWithSpanContext, newScopes);\n }\n\n /**\n * @inheritDoc\n */\n public fields(): string[] {\n return [SENTRY_TRACE_HEADER, SENTRY_BAGGAGE_HEADER];\n }\n\n /** If we want to inject trace data for a given URL. */\n private _shouldInjectTraceData(tracePropagationTargets: Options['tracePropagationTargets'], url: string): boolean {\n if (tracePropagationTargets === undefined) {\n return true;\n }\n\n const cachedDecision = this._urlMatchesTargetsMap.get(url);\n if (cachedDecision !== undefined) {\n return cachedDecision;\n }\n\n const decision = stringMatchesSomePattern(url, tracePropagationTargets);\n this._urlMatchesTargetsMap.set(url, decision);\n return decision;\n }\n}\n\nfunction getInjectionData(context: Context): {\n dynamicSamplingContext: Partial<DynamicSamplingContext> | undefined;\n traceId: string | undefined;\n spanId: string | undefined;\n sampled: boolean | undefined;\n} {\n const span = hasTracingEnabled() ? trace.getSpan(context) : undefined;\n const spanIsRemote = span?.spanContext().isRemote;\n\n // If we have a local span, we can just pick everything from it\n if (span && !spanIsRemote) {\n const spanContext = span.spanContext();\n\n const propagationContext = getPropagationContextFromSpan(span);\n const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, spanContext.traceId);\n return {\n dynamicSamplingContext,\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n sampled: getSamplingDecision(spanContext),\n };\n }\n\n // Else we try to use the propagation context from the scope\n const scope = getScopesFromContext(context)?.scope || getCurrentScope();\n\n const propagationContext = scope.getPropagationContext();\n const dynamicSamplingContext = getDynamicSamplingContext(propagationContext, propagationContext.traceId);\n return {\n dynamicSamplingContext,\n traceId: propagationContext.traceId,\n spanId: propagationContext.spanId,\n sampled: propagationContext.sampled,\n };\n}\n\n/** Get the DSC from a context, or fall back to use the one from the client. */\nfunction getDynamicSamplingContext(\n propagationContext: PropagationContext,\n traceId: string | undefined,\n): Partial<DynamicSamplingContext> | undefined {\n // If we have a DSC on the propagation context, we just use it\n if (propagationContext?.dsc) {\n return propagationContext.dsc;\n }\n\n // Else, we try to generate a new one\n const client = getClient();\n\n if (client) {\n return getDynamicSamplingContextFromClient(traceId || propagationContext.traceId, client);\n }\n\n return undefined;\n}\n\nfunction getContextWithRemoteActiveSpan(\n ctx: Context,\n { sentryTrace, baggage }: Parameters<typeof continueTrace>[0],\n): Context {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n\n const spanContext = generateSpanContextForPropagationContext(propagationContext);\n return trace.setSpanContext(ctx, spanContext);\n}\n\n/**\n * Takes trace strings and propagates them as a remote active span.\n * This should be used in addition to `continueTrace` in OTEL-powered environments.\n */\nexport function continueTraceAsRemoteSpan<T>(\n ctx: Context,\n options: Parameters<typeof continueTrace>[0],\n callback: () => T,\n): T {\n const ctxWithSpanContext = getContextWithRemoteActiveSpan(ctx, options);\n\n return context.with(ctxWithSpanContext, callback);\n}\n\n/** Try to get the existing baggage header so we can merge this in. */\nfunction getExistingBaggage(carrier: unknown): string | undefined {\n try {\n const baggage = (carrier as Record<string, string | string[]>)[SENTRY_BAGGAGE_HEADER];\n return Array.isArray(baggage) ? baggage.join(',') : baggage;\n } catch {\n return undefined;\n }\n}\n\n/**\n * It is pretty tricky to get access to the outgoing request URL of a request in the propagator.\n * As we only have access to the context of the span to be sent and the carrier (=headers),\n * but the span may be unsampled and thus have no attributes.\n *\n * So we use the following logic:\n * 1. If we have an active span, we check if it has a URL attribute.\n * 2. Else, if the active span has no URL attribute (e.g. it is unsampled), we check a special trace state (which we set in our sampler).\n */\nfunction getCurrentURL(span: Span): string | undefined {\n const urlAttribute = spanToJSON(span).data?.[SEMATTRS_HTTP_URL];\n if (urlAttribute) {\n return urlAttribute;\n }\n\n // Also look at the traceState, which we may set in the sampler even for unsampled spans\n const urlTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_URL);\n if (urlTraceState) {\n return urlTraceState;\n }\n\n return undefined;\n}\n","import type { Context, Span, SpanContext, SpanOptions, Tracer } from '@opentelemetry/api';\nimport { INVALID_SPANID, SpanStatusCode, TraceFlags, context, trace } from '@opentelemetry/api';\nimport { suppressTracing } from '@opentelemetry/core';\nimport {\n SDK_VERSION,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n continueTrace as baseContinueTrace,\n getClient,\n getCurrentScope,\n getDynamicSamplingContextFromSpan,\n getRootSpan,\n handleCallbackErrors,\n spanToJSON,\n} from '@sentry/core';\nimport type { Client, Scope, Span as SentrySpan } from '@sentry/types';\nimport { continueTraceAsRemoteSpan } from './propagator';\n\nimport type { OpenTelemetryClient, OpenTelemetrySpanContext } from './types';\nimport { getContextFromScope, getScopesFromContext } from './utils/contextData';\nimport { getSamplingDecision } from './utils/getSamplingDecision';\nimport { makeTraceState } from './utils/makeTraceState';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpan<T>(options: OpenTelemetrySpanContext, callback: (span: Span) => T): T {\n const tracer = getTracer();\n\n const { name, parentSpan: customParentSpan } = options;\n\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper<T>(customParentSpan);\n\n return wrapper(() => {\n const activeCtx = getContext(options.scope, options.forceTransaction);\n const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);\n const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;\n\n const spanOptions = getSpanOptions(options);\n\n return tracer.startActiveSpan(name, spanOptions, ctx, span => {\n return handleCallbackErrors(\n () => callback(span),\n () => {\n // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses\n if (spanToJSON(span).status === undefined) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n },\n () => span.end(),\n );\n });\n });\n}\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a span, but does not finish the span\n * after the function is done automatically. You'll have to call `span.end()` manually.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startSpanManual<T>(\n options: OpenTelemetrySpanContext,\n callback: (span: Span, finish: () => void) => T,\n): T {\n const tracer = getTracer();\n\n const { name, parentSpan: customParentSpan } = options;\n\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper<T>(customParentSpan);\n\n return wrapper(() => {\n const activeCtx = getContext(options.scope, options.forceTransaction);\n const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);\n const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;\n\n const spanOptions = getSpanOptions(options);\n\n return tracer.startActiveSpan(name, spanOptions, ctx, span => {\n return handleCallbackErrors(\n () => callback(span, () => span.end()),\n () => {\n // Only set the span status to ERROR when there wasn't any status set before, in order to avoid stomping useful span statuses\n if (spanToJSON(span).status === undefined) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getActiveSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * This function will always return a span,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nexport function startInactiveSpan(options: OpenTelemetrySpanContext): Span {\n const tracer = getTracer();\n\n const { name, parentSpan: customParentSpan } = options;\n\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper<Span>(customParentSpan);\n\n return wrapper(() => {\n const activeCtx = getContext(options.scope, options.forceTransaction);\n const shouldSkipSpan = options.onlyIfParent && !trace.getSpan(activeCtx);\n const ctx = shouldSkipSpan ? suppressTracing(activeCtx) : activeCtx;\n\n const spanOptions = getSpanOptions(options);\n\n const span = tracer.startSpan(name, spanOptions, ctx);\n\n return span;\n });\n}\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be\n * passed `null` to start an entirely new span tree.\n *\n * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,\n * spans started within the callback will be root spans.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nexport function withActiveSpan<T>(span: Span | null, callback: (scope: Scope) => T): T {\n const newContextWithActiveSpan = span ? trace.setSpan(context.active(), span) : trace.deleteSpan(context.active());\n return context.with(newContextWithActiveSpan, () => callback(getCurrentScope()));\n}\n\nfunction getTracer(): Tracer {\n const client = getClient<Client & OpenTelemetryClient>();\n return (client && client.tracer) || trace.getTracer('@sentry/opentelemetry', SDK_VERSION);\n}\n\nfunction getSpanOptions(options: OpenTelemetrySpanContext): SpanOptions {\n const { startTime, attributes, kind, op } = options;\n\n // OTEL expects timestamps in ms, not seconds\n const fixedStartTime = typeof startTime === 'number' ? ensureTimestampInMilliseconds(startTime) : startTime;\n\n return {\n attributes: op\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n ...attributes,\n }\n : attributes,\n kind,\n startTime: fixedStartTime,\n };\n}\n\nfunction ensureTimestampInMilliseconds(timestamp: number): number {\n const isMs = timestamp < 9999999999;\n return isMs ? timestamp * 1000 : timestamp;\n}\n\nfunction getContext(scope: Scope | undefined, forceTransaction: boolean | undefined): Context {\n const ctx = getContextForScope(scope);\n const actualScope = getScopesFromContext(ctx)?.scope;\n\n const parentSpan = trace.getSpan(ctx);\n\n // In the case that we have no parent span, we need to \"simulate\" one to ensure the propagation context is correct\n if (!parentSpan) {\n const client = getClient();\n\n if (actualScope && client) {\n const propagationContext = actualScope.getPropagationContext();\n\n // We store the DSC as OTEL trace state on the span context\n const traceState = makeTraceState({\n parentSpanId: propagationContext.parentSpanId,\n // Not defined yet, we want to pick this up on-demand only\n dsc: undefined,\n sampled: propagationContext.sampled,\n });\n\n const spanOptions: SpanContext = {\n traceId: propagationContext.traceId,\n spanId: propagationContext.parentSpanId || propagationContext.spanId,\n isRemote: true,\n traceFlags: propagationContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,\n traceState,\n };\n\n // Add remote parent span context,\n return trace.setSpanContext(ctx, spanOptions);\n }\n\n // if we have no scope or client, we just return the context as-is\n return ctx;\n }\n\n // If we don't want to force a transaction, and we have a parent span, all good, we just return as-is!\n if (!forceTransaction) {\n return ctx;\n }\n\n // Else, if we do have a parent span but want to force a transaction, we have to simulate a \"root\" context\n\n // Else, we need to do two things:\n // 1. Unset the parent span from the context, so we'll create a new root span\n // 2. Ensure the propagation context is correct, so we'll continue from the parent span\n const ctxWithoutSpan = trace.deleteSpan(ctx);\n\n const { spanId, traceId } = parentSpan.spanContext();\n const sampled = getSamplingDecision(parentSpan.spanContext());\n\n // In this case, when we are forcing a transaction, we want to treat this like continuing an incoming trace\n // so we set the traceState according to the root span\n const rootSpan = getRootSpan(parentSpan);\n const dsc = getDynamicSamplingContextFromSpan(rootSpan);\n\n const traceState = makeTraceState({\n dsc,\n parentSpanId: spanId !== INVALID_SPANID ? spanId : undefined,\n sampled,\n });\n\n const spanOptions: SpanContext = {\n traceId,\n spanId,\n isRemote: true,\n traceFlags: sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,\n traceState,\n };\n\n const ctxWithSpanContext = trace.setSpanContext(ctxWithoutSpan, spanOptions);\n\n return ctxWithSpanContext;\n}\n\nfunction getContextForScope(scope?: Scope): Context {\n if (scope) {\n const ctx = getContextFromScope(scope);\n if (ctx) {\n return ctx;\n }\n }\n\n return context.active();\n}\n\n/**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from `<meta name=\"sentry-trace\">`\n * and `<meta name=\"baggage\">` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n *\n * This is a custom version of `continueTrace` that is used in OTEL-powered environments.\n * It propagates the trace as a remote span, in addition to setting it on the propagation context.\n */\nexport function continueTrace<T>(options: Parameters<typeof baseContinueTrace>[0], callback: () => T): T {\n return baseContinueTrace(options, () => {\n return continueTraceAsRemoteSpan(context.active(), options, callback);\n });\n}\n\nfunction getActiveSpanWrapper<T>(parentSpan: Span | SentrySpan | undefined | null): (callback: () => T) => T {\n return parentSpan !== undefined\n ? (callback: () => T) => {\n return withActiveSpan(parentSpan, callback);\n }\n : (callback: () => T) => callback();\n}\n","import { context } from '@opentelemetry/api';\nimport { suppressTracing as suppressTracingImpl } from '@opentelemetry/core';\n\n/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */\nexport function suppressTracing<T>(callback: () => T): T {\n const ctx = suppressTracingImpl(context.active());\n return context.with(ctx, callback);\n}\n","import { getDynamicSamplingContextFromSpan, getRootSpan } from '@sentry/core';\nimport type { Client } from '@sentry/types';\nimport { dropUndefinedKeys } from '@sentry/utils';\nimport { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';\nimport { getActiveSpan } from './utils/getActiveSpan';\nimport { spanHasParentId } from './utils/spanTypes';\n\n/** Ensure the `trace` context is set on all events. */\nexport function setupEventContextTrace(client: Client): void {\n client.on('preprocessEvent', event => {\n const span = getActiveSpan();\n // For transaction events, this is handled separately\n // Because the active span may not be the span that is actually the transaction event\n if (!span || event.type === 'transaction') {\n return;\n }\n\n const spanContext = span.spanContext();\n\n // If we have a parent span id from trace state, use that ('' means no parent should be used)\n // Else, pick the one from the span\n const parentSpanIdFromTraceState = spanContext.traceState?.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID);\n const parent_span_id =\n typeof parentSpanIdFromTraceState === 'string'\n ? parentSpanIdFromTraceState || undefined\n : spanHasParentId(span)\n ? span.parentSpanId\n : undefined;\n\n // If event has already set `trace` context, use that one.\n event.contexts = {\n trace: dropUndefinedKeys({\n trace_id: spanContext.traceId,\n span_id: spanContext.spanId,\n parent_span_id,\n }),\n ...event.contexts,\n };\n\n const rootSpan = getRootSpan(span);\n\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(rootSpan),\n ...event.sdkProcessingMetadata,\n };\n\n return event;\n });\n}\n","import * as api from '@opentelemetry/api';\nimport { getDefaultCurrentScope, getDefaultIsolationScope, setAsyncContextStrategy } from '@sentry/core';\nimport type { withActiveSpan as defaultWithActiveSpan } from '@sentry/core';\nimport type { Scope } from '@sentry/types';\n\nimport {\n SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY,\n SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY,\n SENTRY_FORK_SET_SCOPE_CONTEXT_KEY,\n} from './constants';\nimport { startInactiveSpan, startSpan, startSpanManual, withActiveSpan } from './trace';\nimport type { CurrentScopes } from './types';\nimport { getScopesFromContext } from './utils/contextData';\nimport { getActiveSpan } from './utils/getActiveSpan';\nimport { suppressTracing } from './utils/suppressTracing';\n\n/**\n * Sets the async context strategy to use follow the OTEL context under the hood.\n * We handle forking a hub inside of our custom OTEL Context Manager (./otelContextManager.ts)\n */\nexport function setOpenTelemetryContextAsyncContextStrategy(): void {\n function getScopes(): CurrentScopes {\n const ctx = api.context.active();\n const scopes = getScopesFromContext(ctx);\n\n if (scopes) {\n return scopes;\n }\n\n // fallback behavior:\n // if, for whatever reason, we can't find scopes on the context here, we have to fix this somehow\n return {\n scope: getDefaultCurrentScope(),\n isolationScope: getDefaultIsolationScope(),\n };\n }\n\n function withScope<T>(callback: (scope: Scope) => T): T {\n const ctx = api.context.active();\n\n // We depend on the otelContextManager to handle the context/hub\n // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by\n // the OTEL context manager, which uses the presence of this key to determine if it should\n // fork the isolation scope, or not\n // as by default, we don't want to fork this, unless triggered explicitly by `withScope`\n return api.context.with(ctx, () => {\n return callback(getCurrentScope());\n });\n }\n\n function withSetScope<T>(scope: Scope, callback: (scope: Scope) => T): T {\n const ctx = api.context.active();\n\n // We depend on the otelContextManager to handle the context/hub\n // We set the `SENTRY_FORK_SET_SCOPE_CONTEXT_KEY` context value, which is picked up by\n // the OTEL context manager, which picks up this scope as the current scope\n return api.context.with(ctx.setValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY, scope), () => {\n return callback(scope);\n });\n }\n\n function withIsolationScope<T>(callback: (isolationScope: Scope) => T): T {\n const ctx = api.context.active();\n\n // We depend on the otelContextManager to handle the context/hub\n // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by\n // the OTEL context manager, which uses the presence of this key to determine if it should\n // fork the isolation scope, or not\n return api.context.with(ctx.setValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY, true), () => {\n return callback(getIsolationScope());\n });\n }\n\n function withSetIsolationScope<T>(isolationScope: Scope, callback: (isolationScope: Scope) => T): T {\n const ctx = api.context.active();\n\n // We depend on the otelContextManager to handle the context/hub\n // We set the `SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY` context value, which is picked up by\n // the OTEL context manager, which uses the presence of this key to determine if it should\n // fork the isolation scope, or not\n return api.context.with(ctx.setValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY, isolationScope), () => {\n return callback(getIsolationScope());\n });\n }\n\n function getCurrentScope(): Scope {\n return getScopes().scope;\n }\n\n function getIsolationScope(): Scope {\n return getScopes().isolationScope;\n }\n\n setAsyncContextStrategy({\n withScope,\n withSetScope,\n withSetIsolationScope,\n withIsolationScope,\n getCurrentScope,\n getIsolationScope,\n startSpan,\n startSpanManual,\n startInactiveSpan,\n getActiveSpan,\n // The types here don't fully align, because our own `Span` type is narrower\n // than the OTEL one - but this is OK for here, as we now we'll only have OTEL spans passed around\n withActiveSpan: withActiveSpan as typeof defaultWithActiveSpan,\n suppressTracing: suppressTracing,\n });\n}\n","import type { Context, ContextManager } from '@opentelemetry/api';\nimport { getCurrentScope, getIsolationScope } from '@sentry/core';\nimport type { Scope } from '@sentry/types';\n\nimport {\n SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY,\n SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY,\n SENTRY_FORK_SET_SCOPE_CONTEXT_KEY,\n} from './constants';\nimport { getScopesFromContext, setContextOnScope, setScopesOnContext } from './utils/contextData';\nimport { setIsSetup } from './utils/setupCheck';\n\n/**\n * Wrap an OpenTelemetry ContextManager in a way that ensures the context is kept in sync with the Sentry Scope.\n *\n * Usage:\n * import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\n * const SentryContextManager = wrapContextManagerClass(AsyncLocalStorageContextManager);\n * const contextManager = new SentryContextManager();\n */\nexport function wrapContextManagerClass<ContextManagerInstance extends ContextManager>(\n ContextManagerClass: new (...args: unknown[]) => ContextManagerInstance,\n): typeof ContextManagerClass {\n /**\n * This is a custom ContextManager for OpenTelemetry, which extends the default AsyncLocalStorageContextManager.\n * It ensures that we create new scopes per context, so that the OTEL Context & the Sentry Scope are always in sync.\n *\n * Note that we currently only support AsyncHooks with this,\n * but since this should work for Node 14+ anyhow that should be good enough.\n */\n\n // @ts-expect-error TS does not like this, but we know this is fine\n class SentryContextManager extends ContextManagerClass {\n public constructor(...args: unknown[]) {\n super(...args);\n setIsSetup('SentryContextManager');\n }\n /**\n * Overwrite with() of the original AsyncLocalStorageContextManager\n * to ensure we also create new scopes per context.\n */\n public 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 currentScopes = getScopesFromContext(context);\n const currentScope = currentScopes?.scope || getCurrentScope();\n const currentIsolationScope = currentScopes?.isolationScope || getIsolationScope();\n\n const shouldForkIsolationScope = context.getValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY) === true;\n const scope = context.getValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY) as Scope | undefined;\n const isolationScope = context.getValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY) as Scope | undefined;\n\n const newCurrentScope = scope || currentScope.clone();\n const newIsolationScope =\n isolationScope || (shouldForkIsolationScope ? currentIsolationScope.clone() : currentIsolationScope);\n const scopes = { scope: newCurrentScope, isolationScope: newIsolationScope };\n\n const ctx1 = setScopesOnContext(context, scopes);\n\n // Remove the unneeded values again\n const ctx2 = ctx1\n .deleteValue(SENTRY_FORK_ISOLATION_SCOPE_CONTEXT_KEY)\n .deleteValue(SENTRY_FORK_SET_SCOPE_CONTEXT_KEY)\n .deleteValue(SENTRY_FORK_SET_ISOLATION_SCOPE_CONTEXT_KEY);\n\n setContextOnScope(newCurrentScope, ctx2);\n\n return super.with(ctx2, fn, thisArg, ...args);\n }\n }\n\n return SentryContextManager as unknown as typeof ContextManagerClass;\n}\n","/** If this attribute is true, it means that the parent is a remote span. */\nexport const SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE = 'sentry.parentIsRemote';\n","import type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from '../semanticAttributes';\n\nexport interface SpanNode {\n id: string;\n span?: ReadableSpan;\n parentNode?: SpanNode | undefined;\n children: SpanNode[];\n}\n\ntype SpanMap = Map<string, SpanNode>;\n\n/**\n * This function runs through a list of OTEL Spans, and wraps them in an `SpanNode`\n * where each node holds a reference to their parent node.\n */\nexport function groupSpansWithParents(spans: ReadableSpan[]): SpanNode[] {\n const nodeMap: SpanMap = new Map<string, SpanNode>();\n\n for (const span of spans) {\n createOrUpdateSpanNodeAndRefs(nodeMap, span);\n }\n\n return Array.from(nodeMap, function ([_id, spanNode]) {\n return spanNode;\n });\n}\n\n/**\n * This returns the _local_ parent ID - `parentId` on the span may point to a remote span.\n */\nexport function getLocalParentId(span: ReadableSpan): string | undefined {\n const parentIsRemote = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE] === true;\n // If the parentId is the trace parent ID, we pretend it's undefined\n // As this means the parent exists somewhere else\n return !parentIsRemote ? span.parentSpanId : undefined;\n}\n\nfunction createOrUpdateSpanNodeAndRefs(nodeMap: SpanMap, span: ReadableSpan): void {\n const id = span.spanContext().spanId;\n const parentId = getLocalParentId(span);\n\n if (!parentId) {\n createOrUpdateNode(nodeMap, { id, span, children: [] });\n return;\n }\n\n // Else make sure to create parent node as well\n // Note that the parent may not know it's parent _yet_, this may be updated in a later pass\n const parentNode = createOrGetParentNode(nodeMap, parentId);\n const node = createOrUpdateNode(nodeMap, { id, span, parentNode, children: [] });\n parentNode.children.push(node);\n}\n\nfunction createOrGetParentNode(nodeMap: SpanMap, id: string): SpanNode {\n const existing = nodeMap.get(id);\n\n if (existing) {\n return existing;\n }\n\n return createOrUpdateNode(nodeMap, { id, children: [] });\n}\n\nfunction createOrUpdateNode(nodeMap: SpanMap, spanNode: SpanNode): SpanNode {\n const existing = nodeMap.get(spanNode.id);\n\n // If span is already set, nothing to do here\n if (existing && existing.span) {\n return existing;\n }\n\n // If it exists but span is not set yet, we update it\n if (existing && !existing.span) {\n existing.span = spanNode.span;\n existing.parentNode = spanNode.parentNode;\n return existing;\n }\n\n // Else, we create a new one...\n nodeMap.set(spanNode.id, spanNode);\n return spanNode;\n}\n","import { SpanStatusCode } from '@opentelemetry/api';\nimport { SEMATTRS_HTTP_STATUS_CODE, SEMATTRS_RPC_GRPC_STATUS_CODE } from '@opentelemetry/semantic-conventions';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, getSpanStatusFromHttpCode } from '@sentry/core';\nimport type { SpanAttributes, SpanStatus } from '@sentry/types';\n\nimport type { AbstractSpan } from '../types';\nimport { spanHasAttributes, spanHasStatus } from './spanTypes';\n\n// canonicalCodesGrpcMap maps some GRPC codes to Sentry's span statuses. See description in grpc documentation.\nconst canonicalGrpcErrorCodesMap: Record<string, SpanStatus['message']> = {\n '1': 'cancelled',\n '2': 'unknown_error',\n '3': 'invalid_argument',\n '4': 'deadline_exceeded',\n '5': 'not_found',\n '6': 'already_exists',\n '7': 'permission_denied',\n '8': 'resource_exhausted',\n '9': 'failed_precondition',\n '10': 'aborted',\n '11': 'out_of_range',\n '12': 'unimplemented',\n '13': 'internal_error',\n '14': 'unavailable',\n '15': 'data_loss',\n '16': 'unauthenticated',\n} as const;\n\nconst isStatusErrorMessageValid = (message: string): boolean => {\n return Object.values(canonicalGrpcErrorCodesMap).includes(message as SpanStatus['message']);\n};\n\n/**\n * Get a Sentry span status from an otel span.\n */\nexport function mapStatus(span: AbstractSpan): SpanStatus {\n const attributes = spanHasAttributes(span) ? span.attributes : {};\n const status = spanHasStatus(span) ? span.status : undefined;\n\n if (status) {\n // Since span status OK is not set by default, we give it priority: https://opentelemetry.io/docs/concepts/signals/traces/#span-status\n if (status.code === SpanStatusCode.OK) {\n return { code: SPAN_STATUS_OK };\n // If the span is already marked as erroneous we return that exact status\n } else if (status.code === SpanStatusCode.ERROR) {\n if (typeof status.message === 'undefined') {\n const inferredStatus = inferStatusFromAttributes(attributes);\n if (inferredStatus) {\n return inferredStatus;\n }\n }\n\n if (status.message && isStatusErrorMessageValid(status.message)) {\n return { code: SPAN_STATUS_ERROR, message: status.message };\n } else {\n return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };\n }\n }\n }\n\n // If the span status is UNSET, we try to infer it from HTTP or GRPC status codes.\n const inferredStatus = inferStatusFromAttributes(attributes);\n\n if (inferredStatus) {\n return inferredStatus;\n }\n\n // We default to setting the spans status to ok.\n if (status && status.code === SpanStatusCode.UNSET) {\n return { code: SPAN_STATUS_OK };\n } else {\n return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };\n }\n}\n\nfunction inferStatusFromAttributes(attributes: SpanAttributes): SpanStatus | undefined {\n // If the span status is UNSET, we try to infer it from HTTP or GRPC status codes.\n\n const httpCodeAttribute = attributes[SEMATTRS_HTTP_STATUS_CODE];\n const grpcCodeAttribute = attributes[SEMATTRS_RPC_GRPC_STATUS_CODE];\n\n const numberHttpCode =\n typeof httpCodeAttribute === 'number'\n ? httpCodeAttribute\n : typeof httpCodeAttribute === 'string'\n ? parseInt(httpCodeAttribute)\n : undefined;\n\n if (typeof numberHttpCode === 'number') {\n return getSpanStatusFromHttpCode(numberHttpCode);\n }\n\n if (typeof grpcCodeAttribute === 'string') {\n return { code: SPAN_STATUS_ERROR, message: canonicalGrpcErrorCodesMap[grpcCodeAttribute] || 'unknown_error' };\n }\n\n return undefined;\n}\n","import type { Span } from '@opentelemetry/api';\nimport { SpanKind } from '@opentelemetry/api';\nimport type { ReadableSpan } from '@opentelemetry/sdk-trace-base';\nimport { SEMATTRS_HTTP_STATUS_CODE } from '@opentelemetry/semantic-conventions';\nimport {\n captureEvent,\n getCapturedScopesOnSpan,\n getDynamicSamplingContextFromSpan,\n getMetricSummaryJsonForSpan,\n timedEventsToMeasurements,\n} from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n getStatusMessage,\n spanTimeInputToSeconds,\n} from '@sentry/core';\nimport type { SpanJSON, SpanOrigin, TraceContext, TransactionEvent, TransactionSource } from '@sentry/types';\nimport { dropUndefinedKeys, logger } from '@sentry/utils';\nimport { SENTRY_TRACE_STATE_PARENT_SPAN_ID } from './constants';\n\nimport { DEBUG_BUILD } from './debug-build';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';\nimport { getRequestSpanData } from './utils/getRequestSpanData';\nimport type { SpanNode } from './utils/groupSpansWithParents';\nimport { getLocalParentId } from './utils/groupSpansWithParents';\nimport { groupSpansWithParents } from './utils/groupSpansWithParents';\nimport { mapStatus } from './utils/mapStatus';\nimport { parseSpanDescription } from './utils/parseSpanDescription';\n\ntype SpanNodeCompleted = SpanNode & { span: ReadableSpan };\n\nconst MAX_SPAN_COUNT = 1000;\nconst DEFAULT_TIMEOUT = 300; // 5 min\n\n/**\n * A Sentry-specific exporter that converts OpenTelemetry Spans to Sentry Spans & Transactions.\n */\nexport class SentrySpanExporter {\n private _flushTimeout: ReturnType<typeof setTimeout> | undefined;\n private _finishedSpans: ReadableSpan[];\n private _timeout: number;\n\n public constructor(options?: { timeout?: number }) {\n this._finishedSpans = [];\n this._timeout = options?.timeout || DEFAULT_TIMEOUT;\n }\n\n /** Export a single span. */\n public export(span: ReadableSpan): void {\n this._finishedSpans.push(span);\n\n // If the span has a local parent ID, we don't need to export anything just yet\n if (getLocalParentId(span)) {\n const openSpanCount = this._finishedSpans.length;\n DEBUG_BUILD && logger.log(`SpanExporter has ${openSpanCount} unsent spans remaining`);\n this._cleanupOldSpans();\n return;\n }\n\n this._clearTimeout();\n\n // If we got a parent span, we try to send the span tree\n // Wait a tick for this, to ensure we avoid race conditions\n this._flushTimeout = setTimeout(() => {\n this.flush();\n }, 1);\n }\n\n /** Try to flush any pending spans immediately. */\n public flush(): void {\n this._clearTimeout();\n\n const openSpanCount = this._finishedSpans.length;\n\n const remainingSpans = maybeSend(this._finishedSpans);\n\n const remainingOpenSpanCount = remainingSpans.length;\n const sentSpanCount = openSpanCount - remainingOpenSpanCount;\n\n DEBUG_BUILD &&\n logger.log(`SpanExporter exported ${sentSpanCount} spans, ${remainingOpenSpanCount} unsent spans remaining`);\n\n this._cleanupOldSpans(remainingSpans);\n }\n\n /** Clear the exporter. */\n public clear(): void {\n this._finishedSpans = [];\n this._clearTimeout();\n }\n\n /** Clear the flush timeout. */\n private _clearTimeout(): void {\n if (this._flushTimeout) {\n clearTimeout(this._flushTimeout);\n this._flushTimeout = undefined;\n }\n }\n\n /**\n * Remove any span that is older than 5min.\n * We do this to avoid leaking memory.\n */\n private _cleanupOldSpans(spans = this._finishedSpans): void {\n this._finishedSpans = spans.filter(span => {\n const shouldDrop = shouldCleanupSpan(span, this._timeout);\n DEBUG_BUILD &&\n shouldDrop &&\n logger.log(\n `SpanExporter dropping span ${span.name} (${\n span.spanContext().spanId\n }) because it is pending for more than 5 minutes.`,\n );\n return !shouldDrop;\n });\n }\n}\n\n/**\n * Send the given spans, but only if they are part of a finished transaction.\n *\n * Returns the unsent spans.\n * Spans remain unsent when their parent span is not yet finished.\n * This will happen regularly, as child spans are generally finished before their parents.\n * But it _could_ also happen because, for whatever reason, a parent span was lost.\n * In this case, we'll eventually need to clean this up.\n */\nfunction maybeSend(spans: ReadableSpan[]): ReadableSpan[] {\n const grouped = groupSpansWithParents(spans);\n const remaining = new Set(grouped);\n\n const rootNodes = getCompletedRootNodes(grouped);\n\n rootNodes.forEach(root => {\n remaining.delete(root);\n const span = root.span;\n const transactionEvent = createTransactionForOtelSpan(span);\n\n // We'll recursively add all the child spans to this array\n const spans = transactionEvent.spans || [];\n\n root.children.forEach(child => {\n createAndFinishSpanForOtelSpan(child, spans, remaining);\n });\n\n // spans.sort() mutates the array, but we do not use this anymore after this point\n // so we can safely mutate it here\n transactionEvent.spans =\n spans.length > MAX_SPAN_COUNT\n ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)\n : spans;\n\n const measurements = timedEventsToMeasurements(span.events);\n if (measurements) {\n transactionEvent.measurements = measurements;\n }\n\n captureEvent(transactionEvent);\n });\n\n return Array.from(remaining)\n .map(node => node.span)\n .filter((span): span is ReadableSpan => !!span);\n}\n\nfunction nodeIsCompletedRootNode(node: SpanNode): node is SpanNodeCompleted {\n return !!node.span && !node.parentNode;\n}\n\nfunction getCompletedRootNodes(nodes: SpanNode[]): SpanNodeCompleted[] {\n return nodes.filter(nodeIsCompletedRootNode);\n}\n\nfunction shouldCleanupSpan(span: ReadableSpan, maxStartTimeOffsetSeconds: number): boolean {\n const cutoff = Date.now() / 1000 - maxStartTimeOffsetSeconds;\n return spanTimeInputToSeconds(span.startTime) < cutoff;\n}\n\nfunction parseSpan(span: ReadableSpan): { op?: string; origin?: SpanOrigin; source?: TransactionSource } {\n const attributes = span.attributes;\n\n const origin = attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] as SpanOrigin | undefined;\n const op = attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] as string | undefined;\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] as TransactionSource | undefined;\n\n return { origin, op, source };\n}\n\nfunction createTransactionForOtelSpan(span: ReadableSpan): TransactionEvent {\n const { op, description, data, origin = 'manual', source } = getSpanData(span);\n const capturedSpanScopes = getCapturedScopesOnSpan(span as unknown as Span);\n\n const sampleRate = span.attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] as number | undefined;\n\n const attributes = dropUndefinedKeys({\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,\n [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n ...data,\n ...removeSentryAttributes(span.attributes),\n });\n\n const { traceId: trace_id, spanId: span_id } = span.spanContext();\n\n const parentSpanIdFromTraceState = span.spanContext().traceState?.get(SENTRY_TRACE_STATE_PARENT_SPAN_ID);\n\n // If parentSpanIdFromTraceState is defined at all, we want it to take presedence\n // In that case, an empty string should be interpreted as \"no parent span id\",\n // even if `span.parentSpanId` is set\n // this is the case when we are starting a new trace, where we have a virtual span based on the propagationContext\n // We only want to continue the traceId in this case, but ignore the parent span\n const parent_span_id =\n typeof parentSpanIdFromTraceState === 'string' ? parentSpanIdFromTraceState || undefined : span.parentSpanId;\n\n const status = mapStatus(span);\n\n const traceContext: TraceContext = dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n data: attributes,\n origin,\n op,\n status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined\n });\n\n const transactionEvent: TransactionEvent = {\n contexts: {\n trace: traceContext,\n otel: {\n resource: span.resource.attributes,\n },\n },\n spans: [],\n start_timestamp: spanTimeInputToSeconds(span.startTime),\n timestamp: spanTimeInputToSeconds(span.endTime),\n transaction: description,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...dropUndefinedKeys({\n capturedSpanScope: capturedSpanScopes.scope,\n capturedSpanIsolationScope: capturedSpanScopes.isolationScope,\n sampleRate,\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span as unknown as Span),\n }),\n },\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n _metrics_summary: getMetricSummaryJsonForSpan(span as unknown as Span),\n };\n\n return transactionEvent;\n}\n\nfunction createAndFinishSpanForOtelSpan(node: SpanNode, spans: SpanJSON[], remaining: Set<SpanNode>): void {\n remaining.delete(node);\n const span = node.span;\n\n const shouldDrop = !span;\n\n // If this span should be dropped, we still want to create spans for the children of this\n if (shouldDrop) {\n node.children.forEach(child => {\n createAndFinishSpanForOtelSpan(child, spans, remaining);\n });\n return;\n }\n\n const span_id = span.spanContext().spanId;\n const trace_id = span.spanContext().traceId;\n\n const { attributes, startTime, endTime, parentSpanId } = span;\n\n const { op, description, data, origin = 'manual' } = getSpanData(span);\n const allData = dropUndefinedKeys({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n ...removeSentryAttributes(attributes),\n ...data,\n });\n\n const status = mapStatus(span);\n\n const spanJSON: SpanJSON = dropUndefinedKeys({\n span_id,\n trace_id,\n data: allData,\n description,\n parent_span_id: parentSpanId,\n start_timestamp: spanTimeInputToSeconds(startTime),\n // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n timestamp: spanTimeInputToSeconds(endTime) || undefined,\n status: getStatusMessage(status), // As per protocol, span status is allowed to be undefined\n op,\n origin,\n _metrics_summary: getMetricSummaryJsonForSpan(span as unknown as Span),\n measurements: timedEventsToMeasurements(span.events),\n });\n\n spans.push(spanJSON);\n\n node.children.forEach(child => {\n createAndFinishSpanForOtelSpan(child, spans, remaining);\n });\n}\n\nfunction getSpanData(span: ReadableSpan): {\n data: Record<string, unknown>;\n op?: string;\n description: string;\n source?: TransactionSource;\n origin?: SpanOrigin;\n} {\n const { op: definedOp, source: definedSource, origin } = parseSpan(span);\n const { op: inferredOp, description, source: inferredSource, data: inferredData } = parseSpanDescription(span);\n\n const op = definedOp || inferredOp;\n const source = definedSource || inferredSource;\n\n const data = { ...inferredData, ...getData(span) };\n\n return {\n op,\n description,\n source,\n origin,\n data,\n };\n}\n\n/**\n * Remove custom `sentry.` attribtues we do not need to send.\n * These are more carrier attributes we use inside of the SDK, we do not need to send them to the API.\n */\nfunction removeSentryAttributes(data: Record<string, unknown>): Record<string, unknown> {\n const cleanedData = { ...data };\n\n /* eslint-disable @typescript-eslint/no-dynamic-delete */\n delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];\n delete cleanedData[SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE];\n /* eslint-enable @typescript-eslint/no-dynamic-delete */\n\n return cleanedData;\n}\n\nfunction getData(span: ReadableSpan): Record<string, unknown> {\n const attributes = span.attributes;\n const data: Record<string, unknown> = {};\n\n if (span.kind !== SpanKind.INTERNAL) {\n data['otel.kind'] = SpanKind[span.kind];\n }\n\n if (attributes[SEMATTRS_HTTP_STATUS_CODE]) {\n const statusCode = attributes[SEMATTRS_HTTP_STATUS_CODE] as string;\n data['http.response.status_code'] = statusCode;\n }\n\n const requestData = getRequestSpanData(span);\n\n if (requestData.url) {\n data.url = requestData.url;\n }\n\n if (requestData['http.query']) {\n data['http.query'] = requestData['http.query'].slice(1);\n }\n if (requestData['http.fragment']) {\n data['http.fragment'] = requestData['http.fragment'].slice(1);\n }\n\n return data;\n}\n","import type { Context } from '@opentelemetry/api';\nimport { ROOT_CONTEXT, trace } from '@opentelemetry/api';\nimport type { ReadableSpan, Span, SpanProcessor as SpanProcessorInterface } from '@opentelemetry/sdk-trace-base';\nimport {\n addChildSpanToSpan,\n getClient,\n getDefaultCurrentScope,\n getDefaultIsolationScope,\n logSpanEnd,\n logSpanStart,\n setCapturedScopesOnSpan,\n} from '@sentry/core';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE } from './semanticAttributes';\nimport { SentrySpanExporter } from './spanExporter';\nimport { getScopesFromContext } from './utils/contextData';\nimport { setIsSetup } from './utils/setupCheck';\n\nfunction onSpanStart(span: Span, parentContext: Context): void {\n // This is a reliable way to get the parent span - because this is exactly how the parent is identified in the OTEL SDK\n const parentSpan = trace.getSpan(parentContext);\n\n let scopes = getScopesFromContext(parentContext);\n\n // We need access to the parent span in order to be able to move up the span tree for breadcrumbs\n if (parentSpan && !parentSpan.spanContext().isRemote) {\n addChildSpanToSpan(parentSpan, span);\n }\n\n // We need this in the span exporter\n if (parentSpan && parentSpan.spanContext().isRemote) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_PARENT_IS_REMOTE, true);\n }\n\n // The root context does not have scopes stored, so we check for this specifically\n // As fallback we attach the global scopes\n if (parentContext === ROOT_CONTEXT) {\n scopes = {\n scope: getDefaultCurrentScope(),\n isolationScope: getDefaultIsolationScope(),\n };\n }\n\n // We need the scope at time of span creation in order to apply it to the event when the span is finished\n if (scopes) {\n setCapturedScopesOnSpan(span, scopes.scope, scopes.isolationScope);\n }\n\n logSpanStart(span);\n\n const client = getClient();\n client?.emit('spanStart', span);\n}\n\nfunction onSpanEnd(span: Span): void {\n logSpanEnd(span);\n\n const client = getClient();\n client?.emit('spanEnd', span);\n}\n\n/**\n * Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via\n * the Sentry SDK.\n */\nexport class SentrySpanProcessor implements SpanProcessorInterface {\n private _exporter: SentrySpanExporter;\n\n public constructor(options?: { timeout?: number }) {\n setIsSetup('SentrySpanProcessor');\n this._exporter = new SentrySpanExporter(options);\n }\n\n /**\n * @inheritDoc\n */\n public async forceFlush(): Promise<void> {\n this._exporter.flush();\n }\n\n /**\n * @inheritDoc\n */\n public async shutdown(): Promise<void> {\n this._exporter.clear();\n }\n\n /**\n * @inheritDoc\n */\n public onStart(span: Span, parentContext: Context): void {\n onSpanStart(span, parentContext);\n }\n\n /** @inheritDoc */\n public onEnd(span: Span & ReadableSpan): void {\n onSpanEnd(span);\n\n this._exporter.export(span);\n }\n}\n","import type { Attributes, Context, Span, TraceState as TraceStateInterface } from '@opentelemetry/api';\nimport { SpanKind } from '@opentelemetry/api';\nimport { isSpanContextValid, trace } from '@opentelemetry/api';\nimport { TraceState } from '@opentelemetry/core';\nimport type { Sampler, SamplingResult } from '@opentelemetry/sdk-trace-base';\nimport { SamplingDecision } from '@opentelemetry/sdk-trace-base';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE,\n hasTracingEnabled,\n sampleSpan,\n} from '@sentry/core';\nimport type { Client, SpanAttributes } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport { SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, SENTRY_TRACE_STATE_URL } from './constants';\n\nimport { SEMATTRS_HTTP_METHOD, SEMATTRS_HTTP_URL } from '@opentelemetry/semantic-conventions';\nimport { DEBUG_BUILD } from './debug-build';\nimport { getPropagationContextFromSpan } from './propagator';\nimport { getSamplingDecision } from './utils/getSamplingDecision';\nimport { inferSpanData } from './utils/parseSpanDescription';\nimport { setIsSetup } from './utils/setupCheck';\n\n/**\n * A custom OTEL sampler that uses Sentry sampling rates to make its decision\n */\nexport class SentrySampler implements Sampler {\n private _client: Client;\n\n public constructor(client: Client) {\n this._client = client;\n setIsSetup('SentrySampler');\n }\n\n /** @inheritDoc */\n public shouldSample(\n context: Context,\n traceId: string,\n spanName: string,\n spanKind: SpanKind,\n spanAttributes: SpanAttributes,\n _links: unknown,\n ): SamplingResult {\n const options = this._client.getOptions();\n\n const parentSpan = trace.getSpan(context);\n const parentContext = parentSpan?.spanContext();\n\n if (!hasTracingEnabled(options)) {\n return wrapSamplingDecision({ decision: undefined, context, spanAttributes });\n }\n\n // If we have a http.client span that has no local parent, we never want to sample it\n // but we want to leave downstream sampling decisions up to the server\n if (\n spanKind === SpanKind.CLIENT &&\n spanAttributes[SEMATTRS_HTTP_METHOD] &&\n (!parentSpan || parentContext?.isRemote)\n ) {\n return wrapSamplingDecision({ decision: undefined, context, spanAttributes });\n }\n\n const parentSampled = parentSpan ? getParentSampled(parentSpan, traceId, spanName) : undefined;\n\n // We want to pass the inferred name & attributes to the sampler method\n const {\n description: inferredSpanName,\n data: inferredAttributes,\n op,\n } = inferSpanData(spanName, spanAttributes, spanKind);\n\n const mergedAttributes = {\n ...inferredAttributes,\n ...spanAttributes,\n };\n\n if (op) {\n mergedAttributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = op;\n }\n\n const mutableSamplingDecision = { decision: true };\n this._client.emit(\n 'beforeSampling',\n {\n spanAttributes: mergedAttributes,\n spanName: inferredSpanName,\n parentSampled: parentSampled,\n parentContext: parentContext,\n },\n mutableSamplingDecision,\n );\n if (!mutableSamplingDecision.decision) {\n return wrapSamplingDecision({ decision: undefined, context, spanAttributes });\n }\n\n const [sampled, sampleRate] = sampleSpan(options, {\n name: inferredSpanName,\n attributes: mergedAttributes,\n transactionContext: {\n name: inferredSpanName,\n parentSampled,\n },\n parentSampled,\n });\n\n const attributes: Attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]: sampleRate,\n };\n\n const method = `${spanAttributes[SEMATTRS_HTTP_METHOD]}`.toUpperCase();\n if (method === 'OPTIONS' || method === 'HEAD') {\n DEBUG_BUILD && logger.log(`[Tracing] Not sampling span because HTTP method is '${method}' for ${spanName}`);\n\n return {\n ...wrapSamplingDecision({ decision: SamplingDecision.NOT_RECORD, context, spanAttributes }),\n attributes,\n };\n }\n\n if (!sampled) {\n return {\n ...wrapSamplingDecision({ decision: SamplingDecision.NOT_RECORD, context, spanAttributes }),\n attributes,\n };\n }\n return {\n ...wrapSamplingDecision({ decision: SamplingDecision.RECORD_AND_SAMPLED, context, spanAttributes }),\n attributes,\n };\n }\n\n /** Returns the sampler name or short description with the configuration. */\n public toString(): string {\n return 'SentrySampler';\n }\n}\n\nfunction getParentRemoteSampled(parentSpan: Span): boolean | undefined {\n const traceId = parentSpan.spanContext().traceId;\n const traceparentData = getPropagationContextFromSpan(parentSpan);\n\n // Only inherit sampled if `traceId` is the same\n return traceparentData && traceId === traceparentData.traceId ? traceparentData.sampled : undefined;\n}\n\nfunction getParentSampled(parentSpan: Span, traceId: string, spanName: string): boolean | undefined {\n const parentContext = parentSpan.spanContext();\n\n // Only inherit sample rate if `traceId` is the same\n // Note for testing: `isSpanContextValid()` checks the format of the traceId/spanId, so we need to pass valid ones\n if (isSpanContextValid(parentContext) && parentContext.traceId === traceId) {\n if (parentContext.isRemote) {\n const parentSampled = getParentRemoteSampled(parentSpan);\n DEBUG_BUILD &&\n logger.log(`[Tracing] Inheriting remote parent's sampled decision for ${spanName}: ${parentSampled}`);\n return parentSampled;\n }\n\n const parentSampled = getSamplingDecision(parentContext);\n DEBUG_BUILD && logger.log(`[Tracing] Inheriting parent's sampled decision for ${spanName}: ${parentSampled}`);\n return parentSampled;\n }\n\n return undefined;\n}\n\n/**\n * Wrap a sampling decision with data that Sentry needs to work properly with it.\n * If you pass `decision: undefined`, it will be treated as `NOT_RECORDING`, but in contrast to passing `NOT_RECORDING`\n * it will not propagate this decision to downstream Sentry SDKs.\n */\nexport function wrapSamplingDecision({\n decision,\n context,\n spanAttributes,\n}: { decision: SamplingDecision | undefined; context: Context; spanAttributes: SpanAttributes }): SamplingResult {\n const traceState = getBaseTraceState(context, spanAttributes);\n\n // If the decision is undefined, we treat it as NOT_RECORDING, but we don't propagate this decision to downstream SDKs\n // Which is done by not setting `SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING` traceState\n if (decision == undefined) {\n return { decision: SamplingDecision.NOT_RECORD, traceState };\n }\n\n if (decision === SamplingDecision.NOT_RECORD) {\n return { decision, traceState: traceState.set(SENTRY_TRACE_STATE_SAMPLED_NOT_RECORDING, '1') };\n }\n\n return { decision, traceState };\n}\n\nfunction getBaseTraceState(context: Context, spanAttributes: SpanAttributes): TraceStateInterface {\n const parentSpan = trace.getSpan(context);\n const parentContext = parentSpan?.spanContext();\n\n let traceState = parentContext?.traceState || new TraceState();\n\n // We always keep the URL on the trace state, so we can access it in the propagator\n const url = spanAttributes[SEMATTRS_HTTP_URL];\n if (url && typeof url === 'string') {\n traceState = traceState.set(SENTRY_TRACE_STATE_URL, url);\n }\n\n return traceState;\n}\n","import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\n\n/**\n * This method takes an OpenTelemetry instrumentation or\n * array of instrumentations and registers them with OpenTelemetry.\n */\nexport function addOpenTelemetryInstrumentation(...instrumentations: Instrumentation[]): void {\n registerInstrumentations({\n instrumentations,\n });\n}\n","import { context } from '@opentelemetry/api';\nimport { getScopesFromContext } from '@sentry/opentelemetry';\nimport type { Scope } from '@sentry/types';\n\n/**\n * Update the active isolation scope.\n * Should be used with caution!\n */\nexport function setIsolationScope(isolationScope: Scope): void {\n const scopes = getScopesFromContext(context.active());\n if (scopes) {\n scopes.isolationScope = isolationScope;\n }\n}\n","import type { Span } from '@opentelemetry/api';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';\nimport type { SpanOrigin } from '@sentry/types';\n\n/** Adds an origin to an OTEL Span. */\nexport function addOriginToSpan(span: Span, origin: SpanOrigin): void {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n}\n","import type { RequestOptions } from 'node:http';\n\n/** Build a full URL from request options. */\nexport function getRequestUrl(requestOptions: RequestOptions): string {\n const protocol = requestOptions.protocol || '';\n const hostname = requestOptions.hostname || requestOptions.host || '';\n // Don't log standard :80 (http) and :443 (https) ports to reduce the noise\n // Also don't add port if the hostname already includes a port\n const port =\n !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 || /^(.*):(\\d+)$/.test(hostname)\n ? ''\n : `:${requestOptions.port}`;\n const path = requestOptions.path ? requestOptions.path : '/';\n return `${protocol}//${hostname}${port}${path}`;\n}\n","import type { ClientRequest, IncomingMessage, RequestOptions, ServerResponse } from 'node:http';\nimport type { Span } from '@opentelemetry/api';\nimport { HttpInstrumentation } from '@opentelemetry/instrumentation-http';\nimport { addOpenTelemetryInstrumentation } from '@sentry/opentelemetry';\n\nimport {\n addBreadcrumb,\n defineIntegration,\n getCapturedScopesOnSpan,\n getCurrentScope,\n getIsolationScope,\n isSentryRequestUrl,\n setCapturedScopesOnSpan,\n} from '@sentry/core';\nimport { getClient } from '@sentry/opentelemetry';\nimport type { IntegrationFn, SanitizedRequestData } from '@sentry/types';\n\nimport { getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment } from '@sentry/utils';\nimport type { NodeClient } from '../sdk/client';\nimport { setIsolationScope } from '../sdk/scope';\nimport type { HTTPModuleRequestIncomingMessage } from '../transports/http-module';\nimport { addOriginToSpan } from '../utils/addOriginToSpan';\nimport { getRequestUrl } from '../utils/getRequestUrl';\n\nconst INTEGRATION_NAME = 'Http';\n\ninterface HttpOptions {\n /**\n * Whether breadcrumbs should be recorded for requests.\n * Defaults to true\n */\n breadcrumbs?: boolean;\n\n /**\n * Do not capture spans or breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n *\n * The `url` param contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * For example: `'https://someService.com/users/details?id=123'`\n *\n * The `request` param contains the original {@type RequestOptions} object used to make the outgoing request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Do not capture spans or breadcrumbs for incoming HTTP requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n *\n * The `urlPath` param consists of the URL path and query string (if any) of the incoming request.\n * For example: `'/users/details?id=123'`\n *\n * The `request` param contains the original {@type IncomingMessage} object of the incoming request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreIncomingRequests?: (urlPath: string, request: IncomingMessage) => boolean;\n\n /**\n * Additional instrumentation options that are passed to the underlying HttpInstrumentation.\n */\n instrumentation?: {\n requestHook?: (span: Span, req: ClientRequest | HTTPModuleRequestIncomingMessage) => void;\n responseHook?: (span: Span, response: HTTPModuleRequestIncomingMessage | ServerResponse) => void;\n applyCustomAttributesOnSpan?: (\n span: Span,\n request: ClientRequest | HTTPModuleRequestIncomingMessage,\n response: HTTPModuleRequestIncomingMessage | ServerResponse,\n ) => void;\n\n /**\n * You can pass any configuration through to the underlying instrumention.\n * Note that there are no semver guarantees for this!\n */\n _experimentalConfig?: ConstructorParameters<typeof HttpInstrumentation>[0];\n };\n\n /** Allows to pass a custom version of HttpInstrumentation. We use this for Next.js. */\n _instrumentation?: typeof HttpInstrumentation;\n}\n\nlet _httpOptions: HttpOptions = {};\nlet _httpInstrumentation: HttpInstrumentation | undefined;\n\n/**\n * Instrument the HTTP module.\n * This can only be instrumented once! If this called again later, we just update the options.\n */\nexport const instrumentHttp = Object.assign(\n function (): void {\n if (_httpInstrumentation) {\n return;\n }\n\n const _InstrumentationClass = _httpOptions._instrumentation || HttpInstrumentation;\n\n _httpInstrumentation = new _InstrumentationClass({\n ..._httpOptions.instrumentation?._experimentalConfig,\n ignoreOutgoingRequestHook: request => {\n const url = getRequestUrl(request);\n\n if (!url) {\n return false;\n }\n\n if (isSentryRequestUrl(url, getClient())) {\n return true;\n }\n\n const _ignoreOutgoingRequests = _httpOptions.ignoreOutgoingRequests;\n if (_ignoreOutgoingRequests && _ignoreOutgoingRequests(url, request)) {\n return true;\n }\n\n return false;\n },\n\n ignoreIncomingRequestHook: request => {\n // request.url is the only property that holds any information about the url\n // it only consists of the URL path and query string (if any)\n const urlPath = request.url;\n\n const method = request.method?.toUpperCase();\n // We do not capture OPTIONS/HEAD requests as transactions\n if (method === 'OPTIONS' || method === 'HEAD') {\n return true;\n }\n\n const _ignoreIncomingRequests = _httpOptions.ignoreIncomingRequests;\n if (urlPath && _ignoreIncomingRequests && _ignoreIncomingRequests(urlPath, request)) {\n return true;\n }\n\n return false;\n },\n\n requireParentforOutgoingSpans: false,\n requireParentforIncomingSpans: false,\n requestHook: (span, req) => {\n addOriginToSpan(span, 'auto.http.otel.http');\n\n // both, incoming requests and \"client\" requests made within the app trigger the requestHook\n // we only want to isolate and further annotate incoming requests (IncomingMessage)\n if (_isClientRequest(req)) {\n _httpOptions.instrumentation?.requestHook?.(span, req);\n return;\n }\n\n const scopes = getCapturedScopesOnSpan(span);\n\n const isolationScope = (scopes.isolationScope || getIsolationScope()).clone();\n const scope = scopes.scope || getCurrentScope();\n\n // Update the isolation scope, isolate this request\n isolationScope.setSDKProcessingMetadata({ request: req });\n\n const client = getClient<NodeClient>();\n if (client && client.getOptions().autoSessionTracking) {\n isolationScope.setRequestSession({ status: 'ok' });\n }\n setIsolationScope(isolationScope);\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n // attempt to update the scope's `transactionName` based on the request URL\n // Ideally, framework instrumentations coming after the HttpInstrumentation\n // update the transactionName once we get a parameterized route.\n const httpMethod = (req.method || 'GET').toUpperCase();\n const httpTarget = stripUrlQueryAndFragment(req.url || '/');\n\n const bestEffortTransactionName = `${httpMethod} ${httpTarget}`;\n\n isolationScope.setTransactionName(bestEffortTransactionName);\n\n _httpOptions.instrumentation?.requestHook?.(span, req);\n },\n responseHook: (span, res) => {\n const client = getClient<NodeClient>();\n if (client && client.getOptions().autoSessionTracking) {\n setImmediate(() => {\n client['_captureRequestSession']();\n });\n }\n\n _httpOptions.instrumentation?.responseHook?.(span, res);\n },\n applyCustomAttributesOnSpan: (\n span: Span,\n request: ClientRequest | HTTPModuleRequestIncomingMessage,\n response: HTTPModuleRequestIncomingMessage | ServerResponse,\n ) => {\n const _breadcrumbs = typeof _httpOptions.breadcrumbs === 'undefined' ? true : _httpOptions.breadcrumbs;\n if (_breadcrumbs) {\n _addRequestBreadcrumb(request, response);\n }\n\n _httpOptions.instrumentation?.applyCustomAttributesOnSpan?.(span, request, response);\n },\n });\n\n addOpenTelemetryInstrumentation(_httpInstrumentation);\n },\n {\n id: INTEGRATION_NAME,\n },\n);\n\nconst _httpIntegration = ((options: HttpOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n _httpOptions = options;\n instrumentHttp();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * The http integration instruments Node's internal http and https modules.\n * It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.\n */\nexport const httpIntegration = defineIntegration(_httpIntegration);\n\n/** Add a breadcrumb for outgoing requests. */\nfunction _addRequestBreadcrumb(\n request: ClientRequest | HTTPModuleRequestIncomingMessage,\n response: HTTPModuleRequestIncomingMessage | ServerResponse,\n): void {\n // Only generate breadcrumbs for outgoing requests\n if (!_isClientRequest(request)) {\n return;\n }\n\n const data = getBreadcrumbData(request);\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: response.statusCode,\n ...data,\n },\n type: 'http',\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: ClientRequest): Partial<SanitizedRequestData> {\n try {\n // `request.host` does not contain the port, but the host header does\n const host = request.getHeader('host') || request.host;\n const url = new URL(request.path, `${request.protocol}//${host}`);\n const parsedUrl = parseUrl(url.toString());\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\n/**\n * Determines if @param req is a ClientRequest, meaning the request was created within the express app\n * and it's an outgoing request.\n * Checking for properties instead of using `instanceOf` to avoid importing the request classes.\n */\nfunction _isClientRequest(req: ClientRequest | HTTPModuleRequestIncomingMessage): req is ClientRequest {\n return 'outputData' in req && 'outputSize' in req && !('client' in req) && !('statusCode' in req);\n}\n","declare const __DEBUG_BUILD__: boolean;\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nexport const DEBUG_BUILD = __DEBUG_BUILD__;\n","import { parseSemver } from '@sentry/utils';\n\nexport const NODE_VERSION = parseSemver(process.versions.node) as { major: number; minor: number; patch: number };\nexport const NODE_MAJOR = NODE_VERSION.major;\n","import type { Span } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport { context, propagation } from '@opentelemetry/api';\nimport { addBreadcrumb, defineIntegration, getCurrentScope, hasTracingEnabled } from '@sentry/core';\nimport {\n addOpenTelemetryInstrumentation,\n generateSpanContextForPropagationContext,\n getPropagationContextFromSpan,\n} from '@sentry/opentelemetry';\nimport type { IntegrationFn, SanitizedRequestData } from '@sentry/types';\nimport { getSanitizedUrlString, logger, parseUrl } from '@sentry/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { NODE_MAJOR } from '../nodeVersion';\n\nimport type { FetchInstrumentation } from 'opentelemetry-instrumentation-fetch-node';\n\nimport { addOriginToSpan } from '../utils/addOriginToSpan';\n\ninterface FetchRequest {\n method: string;\n origin: string;\n path: string;\n headers: string | string[];\n}\n\ninterface FetchResponse {\n headers: Buffer[];\n statusCode: number;\n}\n\ninterface NodeFetchOptions {\n /**\n * Whether breadcrumbs should be recorded for requests.\n * Defaults to true\n */\n breadcrumbs?: boolean;\n\n /**\n * Do not capture spans or breadcrumbs for outgoing fetch requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n */\n ignoreOutgoingRequests?: (url: string) => boolean;\n}\n\nconst _nativeNodeFetchIntegration = ((options: NodeFetchOptions = {}) => {\n const _breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs;\n const _ignoreOutgoingRequests = options.ignoreOutgoingRequests;\n\n async function getInstrumentation(): Promise<FetchInstrumentation | void> {\n // Only add NodeFetch if Node >= 18, as previous versions do not support it\n if (NODE_MAJOR < 18) {\n DEBUG_BUILD && logger.log('NodeFetch is not supported on Node < 18, skipping instrumentation...');\n return;\n }\n\n try {\n const pkg = await import('opentelemetry-instrumentation-fetch-node');\n const { FetchInstrumentation } = pkg;\n\n class SentryNodeFetchInstrumentation extends FetchInstrumentation {\n // We extend this method so we have access to request _and_ response for the breadcrumb\n public onHeaders({ request, response }: { request: FetchRequest; response: FetchResponse }): void {\n if (_breadcrumbs) {\n _addRequestBreadcrumb(request, response);\n }\n\n return super.onHeaders({ request, response });\n }\n }\n\n return new SentryNodeFetchInstrumentation({\n ignoreRequestHook: (request: FetchRequest) => {\n const url = getAbsoluteUrl(request.origin, request.path);\n const tracingDisabled = !hasTracingEnabled();\n const shouldIgnore = _ignoreOutgoingRequests && url && _ignoreOutgoingRequests(url);\n\n if (shouldIgnore) {\n return true;\n }\n\n // If tracing is disabled, we still want to propagate traces\n // So we do that manually here, matching what the instrumentation does otherwise\n if (tracingDisabled) {\n const ctx = context.active();\n const addedHeaders: Record<string, string> = {};\n\n // We generate a virtual span context from the active one,\n // Where we attach the URL to the trace state, so the propagator can pick it up\n const activeSpan = trace.getSpan(ctx);\n const propagationContext = activeSpan\n ? getPropagationContextFromSpan(activeSpan)\n : getCurrentScope().getPropagationContext();\n\n const spanContext = generateSpanContextForPropagationContext(propagationContext);\n // We know that in practice we'll _always_ haven a traceState here\n spanContext.traceState = spanContext.traceState?.set('sentry.url', url);\n const ctxWithUrlTraceState = trace.setSpanContext(ctx, spanContext);\n\n propagation.inject(ctxWithUrlTraceState, addedHeaders);\n\n const requestHeaders = request.headers;\n if (Array.isArray(requestHeaders)) {\n Object.entries(addedHeaders).forEach(headers => requestHeaders.push(...headers));\n } else {\n request.headers += Object.entries(addedHeaders)\n .map(([k, v]) => `${k}: ${v}\\r\\n`)\n .join('');\n }\n\n // Prevent starting a span for this request\n return true;\n }\n\n return false;\n },\n onRequest: ({ span }: { span: Span }) => {\n _updateSpan(span);\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any);\n } catch (error) {\n // Could not load instrumentation\n DEBUG_BUILD && logger.log('Error while loading NodeFetch instrumentation: \\n', error);\n }\n }\n\n return {\n name: 'NodeFetch',\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n getInstrumentation().then(instrumentation => {\n if (instrumentation) {\n addOpenTelemetryInstrumentation(instrumentation);\n }\n });\n },\n };\n}) satisfies IntegrationFn;\n\nexport const nativeNodeFetchIntegration = defineIntegration(_nativeNodeFetchIntegration);\n\n/** Update the span with data we need. */\nfunction _updateSpan(span: Span): void {\n addOriginToSpan(span, 'auto.http.otel.node_fetch');\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction _addRequestBreadcrumb(request: FetchRequest, response: FetchResponse): void {\n const data = getBreadcrumbData(request);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: response.statusCode,\n ...data,\n },\n type: 'http',\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: FetchRequest): Partial<SanitizedRequestData> {\n try {\n const url = new URL(request.path, request.origin);\n const parsedUrl = parseUrl(url.toString());\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\n// Matching the behavior of the base instrumentation\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n const url = `${origin}`;\n\n if (origin.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!origin.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path.slice(1)}`;\n }\n\n return `${url}${path}`;\n}\n","import * as util from 'node:util';\nimport { addBreadcrumb, defineIntegration, getClient } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { addConsoleInstrumentationHandler, severityLevelFromString } from '@sentry/utils';\n\nconst INTEGRATION_NAME = 'Console';\n\nconst _consoleIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: 'console',\n level: severityLevelFromString(level),\n message: util.format.apply(undefined, args),\n },\n {\n input: [...args],\n level,\n },\n );\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture console logs as breadcrumbs.\n */\nexport const consoleIntegration = defineIntegration(_consoleIntegration);\n","/* eslint-disable max-lines */\nimport { execFile } from 'node:child_process';\nimport { readFile, readdir } from 'node:fs';\nimport * as os from 'node:os';\nimport { join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { defineIntegration } from '@sentry/core';\nimport type {\n AppContext,\n CloudResourceContext,\n Contexts,\n CultureContext,\n DeviceContext,\n Event,\n IntegrationFn,\n OsContext,\n} from '@sentry/types';\n\nexport const readFileAsync = promisify(readFile);\nexport const readDirAsync = promisify(readdir);\n\n// Process enhanced with methods from Node 18, 20, 22 as @types/node\n// is on `14.18.0` to match minimum version requirements of the SDK\ninterface ProcessWithCurrentValues extends NodeJS.Process {\n availableMemory?(): number;\n}\n\nconst INTEGRATION_NAME = 'Context';\n\ninterface DeviceContextOptions {\n cpu?: boolean;\n memory?: boolean;\n}\n\ninterface ContextOptions {\n app?: boolean;\n os?: boolean;\n device?: DeviceContextOptions | boolean;\n culture?: boolean;\n cloudResource?: boolean;\n}\n\nconst _nodeContextIntegration = ((options: ContextOptions = {}) => {\n let cachedContext: Promise<Contexts> | undefined;\n\n const _options = {\n app: true,\n os: true,\n device: true,\n culture: true,\n cloudResource: true,\n ...options,\n };\n\n /** Add contexts to the event. Caches the context so we only look it up once. */\n async function addContext(event: Event): Promise<Event> {\n if (cachedContext === undefined) {\n cachedContext = _getContexts();\n }\n\n const updatedContext = _updateContext(await cachedContext);\n\n event.contexts = {\n ...event.contexts,\n app: { ...updatedContext.app, ...event.contexts?.app },\n os: { ...updatedContext.os, ...event.contexts?.os },\n device: { ...updatedContext.device, ...event.contexts?.device },\n culture: { ...updatedContext.culture, ...event.contexts?.culture },\n cloud_resource: { ...updatedContext.cloud_resource, ...event.contexts?.cloud_resource },\n };\n\n return event;\n }\n\n /** Get the contexts from node. */\n async function _getContexts(): Promise<Contexts> {\n const contexts: Contexts = {};\n\n if (_options.os) {\n contexts.os = await getOsContext();\n }\n\n if (_options.app) {\n contexts.app = getAppContext();\n }\n\n if (_options.device) {\n contexts.device = getDeviceContext(_options.device);\n }\n\n if (_options.culture) {\n const culture = getCultureContext();\n\n if (culture) {\n contexts.culture = culture;\n }\n }\n\n if (_options.cloudResource) {\n contexts.cloud_resource = getCloudResourceContext();\n }\n\n return contexts;\n }\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addContext(event);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture context about the environment and the device that the client is running on, to events.\n */\nexport const nodeContextIntegration = defineIntegration(_nodeContextIntegration);\n\n/**\n * Updates the context with dynamic values that can change\n */\nfunction _updateContext(contexts: Contexts): Contexts {\n // Only update properties if they exist\n\n if (contexts?.app?.app_memory) {\n contexts.app.app_memory = process.memoryUsage().rss;\n }\n\n if (contexts?.app?.free_memory && typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n contexts.app.free_memory = freeMemory;\n }\n }\n\n if (contexts?.device?.free_memory) {\n contexts.device.free_memory = os.freemem();\n }\n\n return contexts;\n}\n\n/**\n * Returns the operating system context.\n *\n * Based on the current platform, this uses a different strategy to provide the\n * most accurate OS information. Since this might involve spawning subprocesses\n * or accessing the file system, this should only be executed lazily and cached.\n *\n * - On macOS (Darwin), this will execute the `sw_vers` utility. The context\n * has a `name`, `version`, `build` and `kernel_version` set.\n * - On Linux, this will try to load a distribution release from `/etc` and set\n * the `name`, `version` and `kernel_version` fields.\n * - On all other platforms, only a `name` and `version` will be returned. Note\n * that `version` might actually be the kernel version.\n */\nasync function getOsContext(): Promise<OsContext> {\n const platformId = os.platform();\n switch (platformId) {\n case 'darwin':\n return getDarwinInfo();\n case 'linux':\n return getLinuxInfo();\n default:\n return {\n name: PLATFORM_NAMES[platformId] || platformId,\n version: os.release(),\n };\n }\n}\n\nfunction getCultureContext(): CultureContext | undefined {\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if (typeof (process.versions as unknown as any).icu !== 'string') {\n // Node was built without ICU support\n return;\n }\n\n // Check that node was built with full Intl support. Its possible it was built without support for non-English\n // locales which will make resolvedOptions inaccurate\n //\n // https://nodejs.org/api/intl.html#detecting-internationalization-support\n const january = new Date(9e8);\n const spanish = new Intl.DateTimeFormat('es', { month: 'long' });\n if (spanish.format(january) === 'enero') {\n const options = Intl.DateTimeFormat().resolvedOptions();\n\n return {\n locale: options.locale,\n timezone: options.timeZone,\n };\n }\n } catch (err) {\n //\n }\n\n return;\n}\n\n/**\n * Get app context information from process\n */\nexport function getAppContext(): AppContext {\n const app_memory = process.memoryUsage().rss;\n const app_start_time = new Date(Date.now() - process.uptime() * 1000).toISOString();\n // https://nodejs.org/api/process.html#processavailablememory\n const appContext: AppContext = { app_start_time, app_memory };\n\n if (typeof (process as ProcessWithCurrentValues).availableMemory === 'function') {\n const freeMemory = (process as ProcessWithCurrentValues).availableMemory?.();\n if (freeMemory != null) {\n appContext.free_memory = freeMemory;\n }\n }\n\n return appContext;\n}\n\n/**\n * Gets device information from os\n */\nexport function getDeviceContext(deviceOpt: DeviceContextOptions | true): DeviceContext {\n const device: DeviceContext = {};\n\n // Sometimes os.uptime() throws due to lacking permissions: https://github.com/getsentry/sentry-javascript/issues/8202\n let uptime;\n try {\n uptime = os.uptime && os.uptime();\n } catch (e) {\n // noop\n }\n\n // os.uptime or its return value seem to be undefined in certain environments (e.g. Azure functions).\n // Hence, we only set boot time, if we get a valid uptime value.\n // @see https://github.com/getsentry/sentry-javascript/issues/5856\n if (typeof uptime === 'number') {\n device.boot_time = new Date(Date.now() - uptime * 1000).toISOString();\n }\n\n device.arch = os.arch();\n\n if (deviceOpt === true || deviceOpt.memory) {\n device.memory_size = os.totalmem();\n device.free_memory = os.freemem();\n }\n\n if (deviceOpt === true || deviceOpt.cpu) {\n const cpuInfo: os.CpuInfo[] | undefined = os.cpus();\n const firstCpu = cpuInfo && cpuInfo[0];\n if (firstCpu) {\n device.processor_count = cpuInfo.length;\n device.cpu_description = firstCpu.model;\n device.processor_frequency = firstCpu.speed;\n }\n }\n\n return device;\n}\n\n/** Mapping of Node's platform names to actual OS names. */\nconst PLATFORM_NAMES: { [platform: string]: string } = {\n aix: 'IBM AIX',\n freebsd: 'FreeBSD',\n openbsd: 'OpenBSD',\n sunos: 'SunOS',\n win32: 'Windows',\n};\n\n/** Linux version file to check for a distribution. */\ninterface DistroFile {\n /** The file name, located in `/etc`. */\n name: string;\n /** Potential distributions to check. */\n distros: [string, ...string[]];\n}\n\n/** Mapping of linux release files located in /etc to distributions. */\nconst LINUX_DISTROS: DistroFile[] = [\n { name: 'fedora-release', distros: ['Fedora'] },\n { name: 'redhat-release', distros: ['Red Hat Linux', 'Centos'] },\n { name: 'redhat_version', distros: ['Red Hat Linux'] },\n { name: 'SuSE-release', distros: ['SUSE Linux'] },\n { name: 'lsb-release', distros: ['Ubuntu Linux', 'Arch Linux'] },\n { name: 'debian_version', distros: ['Debian'] },\n { name: 'debian_release', distros: ['Debian'] },\n { name: 'arch-release', distros: ['Arch Linux'] },\n { name: 'gentoo-release', distros: ['Gentoo Linux'] },\n { name: 'novell-release', distros: ['SUSE Linux'] },\n { name: 'alpine-release', distros: ['Alpine Linux'] },\n];\n\n/** Functions to extract the OS version from Linux release files. */\nconst LINUX_VERSIONS: {\n [identifier: string]: (content: string) => string | undefined;\n} = {\n alpine: content => content,\n arch: content => matchFirst(/distrib_release=(.*)/, content),\n centos: content => matchFirst(/release ([^ ]+)/, content),\n debian: content => content,\n fedora: content => matchFirst(/release (..)/, content),\n mint: content => matchFirst(/distrib_release=(.*)/, content),\n red: content => matchFirst(/release ([^ ]+)/, content),\n suse: content => matchFirst(/VERSION = (.*)\\n/, content),\n ubuntu: content => matchFirst(/distrib_release=(.*)/, content),\n};\n\n/**\n * Executes a regular expression with one capture group.\n *\n * @param regex A regular expression to execute.\n * @param text Content to execute the RegEx on.\n * @returns The captured string if matched; otherwise undefined.\n */\nfunction matchFirst(regex: RegExp, text: string): string | undefined {\n const match = regex.exec(text);\n return match ? match[1] : undefined;\n}\n\n/** Loads the macOS operating system context. */\nasync function getDarwinInfo(): Promise<OsContext> {\n // Default values that will be used in case no operating system information\n // can be loaded. The default version is computed via heuristics from the\n // kernel version, but the build ID is missing.\n const darwinInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Mac OS X',\n version: `10.${Number(os.release().split('.')[0]) - 4}`,\n };\n\n try {\n // We try to load the actual macOS version by executing the `sw_vers` tool.\n // This tool should be available on every standard macOS installation. In\n // case this fails, we stick with the values computed above.\n\n const output = await new Promise<string>((resolve, reject) => {\n execFile('/usr/bin/sw_vers', (error: Error | null, stdout: string) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(stdout);\n });\n });\n\n darwinInfo.name = matchFirst(/^ProductName:\\s+(.*)$/m, output);\n darwinInfo.version = matchFirst(/^ProductVersion:\\s+(.*)$/m, output);\n darwinInfo.build = matchFirst(/^BuildVersion:\\s+(.*)$/m, output);\n } catch (e) {\n // ignore\n }\n\n return darwinInfo;\n}\n\n/** Returns a distribution identifier to look up version callbacks. */\nfunction getLinuxDistroId(name: string): string {\n return (name.split(' ') as [string])[0].toLowerCase();\n}\n\n/** Loads the Linux operating system context. */\nasync function getLinuxInfo(): Promise<OsContext> {\n // By default, we cannot assume anything about the distribution or Linux\n // version. `os.release()` returns the kernel version and we assume a generic\n // \"Linux\" name, which will be replaced down below.\n const linuxInfo: OsContext = {\n kernel_version: os.release(),\n name: 'Linux',\n };\n\n try {\n // We start guessing the distribution by listing files in the /etc\n // directory. This is were most Linux distributions (except Knoppix) store\n // release files with certain distribution-dependent meta data. We search\n // for exactly one known file defined in `LINUX_DISTROS` and exit if none\n // are found. In case there are more than one file, we just stick with the\n // first one.\n const etcFiles = await readDirAsync('/etc');\n const distroFile = LINUX_DISTROS.find(file => etcFiles.includes(file.name));\n if (!distroFile) {\n return linuxInfo;\n }\n\n // Once that file is known, load its contents. To make searching in those\n // files easier, we lowercase the file contents. Since these files are\n // usually quite small, this should not allocate too much memory and we only\n // hold on to it for a very short amount of time.\n const distroPath = join('/etc', distroFile.name);\n const contents = ((await readFileAsync(distroPath, { encoding: 'utf-8' })) as string).toLowerCase();\n\n // Some Linux distributions store their release information in the same file\n // (e.g. RHEL and Centos). In those cases, we scan the file for an\n // identifier, that basically consists of the first word of the linux\n // distribution name (e.g. \"red\" for Red Hat). In case there is no match, we\n // just assume the first distribution in our list.\n const { distros } = distroFile;\n linuxInfo.name = distros.find(d => contents.indexOf(getLinuxDistroId(d)) >= 0) || distros[0];\n\n // Based on the found distribution, we can now compute the actual version\n // number. This is different for every distribution, so several strategies\n // are computed in `LINUX_VERSIONS`.\n const id = getLinuxDistroId(linuxInfo.name);\n linuxInfo.version = LINUX_VERSIONS[id]?.(contents);\n } catch (e) {\n // ignore\n }\n\n return linuxInfo;\n}\n\n/**\n * Grabs some information about hosting provider based on best effort.\n */\nfunction getCloudResourceContext(): CloudResourceContext | undefined {\n if (process.env.VERCEL) {\n // https://vercel.com/docs/concepts/projects/environment-variables/system-environment-variables#system-environment-variables\n return {\n 'cloud.provider': 'vercel',\n 'cloud.region': process.env.VERCEL_REGION,\n };\n } else if (process.env.AWS_REGION) {\n // https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html\n return {\n 'cloud.provider': 'aws',\n 'cloud.region': process.env.AWS_REGION,\n 'cloud.platform': process.env.AWS_EXECUTION_ENV,\n };\n } else if (process.env.GCP_PROJECT) {\n // https://cloud.google.com/composer/docs/how-to/managing/environment-variables#reserved_variables\n return {\n 'cloud.provider': 'gcp',\n };\n } else if (process.env.ALIYUN_REGION_ID) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'alibaba_cloud',\n 'cloud.region': process.env.ALIYUN_REGION_ID,\n };\n } else if (process.env.WEBSITE_SITE_NAME && process.env.REGION_NAME) {\n // https://learn.microsoft.com/en-us/azure/app-service/reference-app-settings?tabs=kudu%2Cdotnet#app-environment\n return {\n 'cloud.provider': 'azure',\n 'cloud.region': process.env.REGION_NAME,\n };\n } else if (process.env.IBM_CLOUD_REGION) {\n // TODO: find where I found these environment variables - at least gc.github.com returns something\n return {\n 'cloud.provider': 'ibm_cloud',\n 'cloud.region': process.env.IBM_CLOUD_REGION,\n };\n } else if (process.env.TENCENTCLOUD_REGION) {\n // https://www.tencentcloud.com/document/product/583/32748\n return {\n 'cloud.provider': 'tencent_cloud',\n 'cloud.region': process.env.TENCENTCLOUD_REGION,\n 'cloud.account.id': process.env.TENCENTCLOUD_APPID,\n 'cloud.availability_zone': process.env.TENCENTCLOUD_ZONE,\n };\n } else if (process.env.NETLIFY) {\n // https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables\n return {\n 'cloud.provider': 'netlify',\n };\n } else if (process.env.FLY_REGION) {\n // https://fly.io/docs/reference/runtime-environment/\n return {\n 'cloud.provider': 'fly.io',\n 'cloud.region': process.env.FLY_REGION,\n };\n } else if (process.env.DYNO) {\n // https://devcenter.heroku.com/articles/dynos#local-environment-variables\n return {\n 'cloud.provider': 'heroku',\n };\n } else {\n return undefined;\n }\n}\n","import { createReadStream } from 'node:fs';\nimport { createInterface } from 'node:readline';\nimport { defineIntegration } from '@sentry/core';\nimport type { Event, IntegrationFn, StackFrame } from '@sentry/types';\nimport { LRUMap, logger, snipLine } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap<string, 1>(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst INTEGRATION_NAME = 'ContextLines';\n// Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be\n// minified code while large lineno values are likely to be bundled code.\n// Exported for testing purposes.\nexport const MAX_CONTEXTLINES_COLNO: number = 1000;\nexport const MAX_CONTEXTLINES_LINENO: number = 10000;\n\ninterface ContextLinesOptions {\n /**\n * Sets the number of context lines for each frame when loading a file.\n * Defaults to 7.\n *\n * Set to 0 to disable loading and inclusion of source files.\n **/\n frameContextLines?: number;\n}\n\n/**\n * Exported for testing purposes.\n */\nexport function resetFileContentCache(): void {\n LRU_FILE_CONTENTS_CACHE.clear();\n}\n\n/**\n * Get or init map value\n */\nfunction emplace<T extends LRUMap<K, V>, K extends string, V>(map: T, key: K, contents: V): V {\n const value = map.get(key);\n\n if (value === undefined) {\n map.set(key, contents);\n return contents;\n }\n\n return value;\n}\n\n/**\n * Determines if context lines should be skipped for a file.\n * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source\n * - node: prefixed modules are part of the runtime and cannot be resolved to a file\n * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports\n */\nfunction shouldSkipContextLinesForFile(path: string): boolean {\n // Test the most common prefix and extension first. These are the ones we\n // are most likely to see in user applications and are the ones we can break out of first.\n if (path.startsWith('node:')) return true;\n if (path.endsWith('.min.js')) return true;\n if (path.endsWith('.min.cjs')) return true;\n if (path.endsWith('.min.mjs')) return true;\n if (path.startsWith('data:')) return true;\n return false;\n}\n\n/**\n * Determines if we should skip contextlines based off the max lineno and colno values.\n */\nfunction shouldSkipContextLinesForFrame(frame: StackFrame): boolean {\n if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\n/**\n * Checks if we have all the contents that we need in the cache.\n */\nfunction rangeExistsInContentCache(file: string, range: ReadlineRange): boolean {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (contents === undefined) return false;\n\n for (let i = range[0]; i <= range[1]; i++) {\n if (contents[i] === undefined) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,\n * the ranges are merged to create a single range.\n */\nfunction makeLineReaderRanges(lines: number[], linecontext: number): ReadlineRange[] {\n if (!lines.length) {\n return [];\n }\n\n let i = 0;\n const line = lines[0];\n\n if (typeof line !== 'number') {\n return [];\n }\n\n let current = makeContextRange(line, linecontext);\n const out: ReadlineRange[] = [];\n // eslint-disable-next-line no-constant-condition\n while (true) {\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n\n // If the next line falls into the current range, extend the current range to lineno + linecontext.\n const next = lines[i + 1];\n if (typeof next !== 'number') {\n break;\n }\n if (next <= current[1]) {\n current[1] = next + linecontext;\n } else {\n out.push(current);\n current = makeContextRange(next, linecontext);\n }\n\n i++;\n }\n\n return out;\n}\n\n/**\n * Extracts lines from a file and stores them in a cache.\n */\nfunction getContextLinesFromFile(path: string, ranges: ReadlineRange[], output: Record<number, string>): Promise<void> {\n return new Promise((resolve, _reject) => {\n // It is important *not* to have any async code between createInterface and the 'line' event listener\n // as it will cause the 'line' event to\n // be emitted before the listener is attached.\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream,\n });\n\n // Init at zero and increment at the start of the loop because lines are 1 indexed.\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.\n resolve();\n return;\n }\n let rangeStart = range[0];\n let rangeEnd = range[1];\n\n // We use this inside Promise.all, so we need to resolve the promise even if there is an error\n // to prevent Promise.all from short circuiting the rest.\n function onStreamError(e: Error): void {\n // Mark file path as failed to read and prevent multiple read attempts.\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n DEBUG_BUILD && logger.error(`Failed to read file: ${path}. Error: ${e}`);\n lineReaded.close();\n lineReaded.removeAllListeners();\n resolve();\n }\n\n // We need to handle the error event to prevent the process from crashing in < Node 16\n // https://github.com/nodejs/node/pull/31603\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', resolve);\n\n lineReaded.on('line', line => {\n lineNumber++;\n if (lineNumber < rangeStart) return;\n\n // !Warning: This mutates the cache by storing the snipped line into the cache.\n output[lineNumber] = snipLine(line, 0);\n\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n // We need to close the file stream and remove listeners, else the reader will continue to run our listener;\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (range === undefined) {\n // This should never happen as it means we have a bug in the context.\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\n\n/**\n * Adds surrounding (context) lines of the line that an exception occurred on to the event.\n * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in\n * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple\n * failing reads from happening.\n */\n/* eslint-disable complexity */\nasync function addSourceContext(event: Event, contextLines: number): Promise<Event> {\n // keep a lookup map of which files we've already enqueued to read,\n // so we don't enqueue the same file multiple times which would cause multiple i/o reads\n const filesToLines: Record<string, number[]> = {};\n\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (!exception.stacktrace?.frames?.length) {\n continue;\n }\n\n // Maps preserve insertion order, so we iterate in reverse, starting at the\n // outermost frame and closer to where the exception has occurred (poor mans priority)\n for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {\n const frame: StackFrame | undefined = exception.stacktrace.frames[i];\n const filename = frame?.filename;\n\n if (\n !frame ||\n typeof filename !== 'string' ||\n typeof frame.lineno !== 'number' ||\n shouldSkipContextLinesForFile(filename) ||\n shouldSkipContextLinesForFrame(frame)\n ) {\n continue;\n }\n\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n // @ts-expect-error this is defined above\n filesToLines[filename].push(frame.lineno);\n }\n }\n }\n\n const files = Object.keys(filesToLines);\n if (files.length == 0) {\n return event;\n }\n\n const readlinePromises: Promise<void>[] = [];\n for (const file of files) {\n // If we failed to read this before, dont try reading it again.\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {\n continue;\n }\n\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) {\n continue;\n }\n\n // Sort ranges so that they are sorted by line increasing order and match how the file is read.\n filesToLineRanges.sort((a, b) => a - b);\n // Check if the contents are already in the cache and if we can avoid reading the file again.\n const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);\n if (ranges.every(r => rangeExistsInContentCache(file, r))) {\n continue;\n }\n\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n\n // The promise rejections are caught in order to prevent them from short circuiting Promise.all\n await Promise.all(readlinePromises).catch(() => {\n DEBUG_BUILD && logger.log('Failed to read one or more source files and resolve context lines');\n });\n\n // Perform the same loop as above, but this time we can assume all files are in the cache\n // and attempt to add source context to frames.\n if (contextLines > 0 && event.exception?.values) {\n for (const exception of event.exception.values) {\n if (exception.stacktrace && exception.stacktrace.frames && exception.stacktrace.frames.length > 0) {\n addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);\n }\n }\n }\n\n return event;\n}\n/* eslint-enable complexity */\n\n/** Adds context lines to frames */\nfunction addSourceContextToFrames(\n frames: StackFrame[],\n contextLines: number,\n cache: LRUMap<string, Record<number, string>>,\n): void {\n for (const frame of frames) {\n // Only add context if we have a filename and it hasn't already been added\n if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {\n const contents = cache.get(frame.filename);\n if (contents === undefined) {\n continue;\n }\n\n addContextToFrame(frame.lineno, frame, contextLines, contents);\n }\n }\n}\n\n/**\n * Clears the context lines from a frame, used to reset a frame to its original state\n * if we fail to resolve all context lines for it.\n */\nfunction clearLineContext(frame: StackFrame): void {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\n\n/**\n * Resolves context lines before and after the given line number and appends them to the frame;\n */\nexport function addContextToFrame(\n lineno: number,\n frame: StackFrame,\n contextLines: number,\n contents: Record<number, string> | undefined,\n): void {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.\n // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.\n if (frame.lineno === undefined || contents === undefined) {\n DEBUG_BUILD && logger.error('Cannot resolve context for frame with no lineno or file contents');\n return;\n }\n\n frame.pre_context = [];\n for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {\n // We always expect the start context as line numbers cannot be negative. If we dont find a line, then\n // something went wrong somewhere. Clear the context and return without adding any linecontext.\n const line = contents[i];\n if (line === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${i} in file ${frame.filename}`);\n return;\n }\n\n frame.pre_context.push(line);\n }\n\n // We should always have the context line. If we dont, something went wrong, so we clear the context and return\n // without adding any linecontext.\n if (contents[lineno] === undefined) {\n clearLineContext(frame);\n DEBUG_BUILD && logger.error(`Could not find line ${lineno} in file ${frame.filename}`);\n return;\n }\n\n frame.context_line = contents[lineno];\n\n const end = makeRangeEnd(lineno, contextLines);\n frame.post_context = [];\n for (let i = lineno + 1; i <= end; i++) {\n // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could\n // just be that we reached the end of the file.\n const line = contents[i];\n if (line === undefined) {\n break;\n }\n frame.post_context.push(line);\n }\n}\n\n// Helper functions for generating line context ranges. They take a line number and the number of lines of context to\n// include before and after the line and generate an inclusive range of indices.\ntype ReadlineRange = [start: number, end: number];\n// Compute inclusive end context range\nfunction makeRangeStart(line: number, linecontext: number): number {\n return Math.max(1, line - linecontext);\n}\n// Compute inclusive start context range\nfunction makeRangeEnd(line: number, linecontext: number): number {\n return line + linecontext;\n}\n// Determine start and end indices for context range (inclusive);\nfunction makeContextRange(line: number, linecontext: number): [start: number, end: number] {\n return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];\n}\n\n/** Exported only for tests, as a type-safe variant. */\nexport const _contextLinesIntegration = ((options: ContextLinesOptions = {}) => {\n const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n return addSourceContext(event, contextLines);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Capture the lines before and after the frame's context.\n */\nexport const contextLinesIntegration = defineIntegration(_contextLinesIntegration);\n","import type { Debugger } from 'node:inspector';\nimport type { StackFrame, StackParser } from '@sentry/types';\n\nexport type Variables = Record<string, unknown>;\n\nexport type RateLimitIncrement = () => void;\n\n/**\n * Creates a rate limiter that will call the disable callback when the rate limit is reached and the enable callback\n * when a timeout has occurred.\n * @param maxPerSecond Maximum number of calls per second\n * @param enable Callback to enable capture\n * @param disable Callback to disable capture\n * @returns A function to call to increment the rate limiter count\n */\nexport function createRateLimiter(\n maxPerSecond: number,\n enable: () => void,\n disable: (seconds: number) => void,\n): RateLimitIncrement {\n let count = 0;\n let retrySeconds = 5;\n let disabledTimeout = 0;\n\n setInterval(() => {\n if (disabledTimeout === 0) {\n if (count > maxPerSecond) {\n retrySeconds *= 2;\n disable(retrySeconds);\n\n // Cap at one day\n if (retrySeconds > 86400) {\n retrySeconds = 86400;\n }\n disabledTimeout = retrySeconds;\n }\n } else {\n disabledTimeout -= 1;\n\n if (disabledTimeout === 0) {\n enable();\n }\n }\n\n count = 0;\n }, 1_000).unref();\n\n return () => {\n count += 1;\n };\n}\n\n// Add types for the exception event data\nexport type PausedExceptionEvent = Debugger.PausedEventDataType & {\n data: {\n // This contains error.stack\n description: string;\n };\n};\n\n/** Could this be an anonymous function? */\nexport function isAnonymous(name: string | undefined): boolean {\n return name !== undefined && (name.length === 0 || name === '?' || name === '<anonymous>');\n}\n\n/** Do the function names appear to match? */\nexport function functionNamesMatch(a: string | undefined, b: string | undefined): boolean {\n return a === b || (isAnonymous(a) && isAnonymous(b));\n}\n\n/** Creates a unique hash from stack frames */\nexport function hashFrames(frames: StackFrame[] | undefined): string | undefined {\n if (frames === undefined) {\n return;\n }\n\n // Only hash the 10 most recent frames (ie. the last 10)\n return frames.slice(-10).reduce((acc, frame) => `${acc},${frame.function},${frame.lineno},${frame.colno}`, '');\n}\n\n/**\n * We use the stack parser to create a unique hash from the exception stack trace\n * This is used to lookup vars when the exception passes through the event processor\n */\nexport function hashFromStack(stackParser: StackParser, stack: string | undefined): string | undefined {\n if (stack === undefined) {\n return undefined;\n }\n\n return hashFrames(stackParser(stack, 1));\n}\n\nexport interface FrameVariables {\n function: string;\n vars?: Variables;\n}\n\nexport interface LocalVariablesIntegrationOptions {\n /**\n * Capture local variables for both caught and uncaught exceptions\n *\n * - When false, only uncaught exceptions will have local variables\n * - When true, both caught and uncaught exceptions will have local variables.\n *\n * Defaults to `true`.\n *\n * Capturing local variables for all exceptions can be expensive since the debugger pauses for every throw to collect\n * local variables.\n *\n * To reduce the likelihood of this feature impacting app performance or throughput, this feature is rate-limited.\n * Once the rate limit is reached, local variables will only be captured for uncaught exceptions until a timeout has\n * been reached.\n */\n captureAllExceptions?: boolean;\n /**\n * Maximum number of exceptions to capture local variables for per second before rate limiting is triggered.\n */\n maxExceptionsPerSecond?: number;\n}\n\nexport interface LocalVariablesWorkerArgs extends LocalVariablesIntegrationOptions {\n /**\n * Whether to enable debug logging.\n */\n debug: boolean;\n /**\n * Base path used to calculate module name.\n *\n * Defaults to `dirname(process.argv[1])` and falls back to `process.cwd()`\n */\n basePath?: string;\n}\n","import { Worker } from 'node:worker_threads';\nimport { defineIntegration } from '@sentry/core';\nimport type { Event, Exception, IntegrationFn } from '@sentry/types';\nimport { LRUMap, logger } from '@sentry/utils';\n\nimport type { NodeClient } from '../../sdk/client';\nimport type { FrameVariables, LocalVariablesIntegrationOptions, LocalVariablesWorkerArgs } from './common';\nimport { functionNamesMatch, hashFrames } from './common';\n\n// This string is a placeholder that gets overwritten with the worker code.\nexport const base64WorkerScript = '###LocalVariablesWorkerScript###';\n\nfunction log(...args: unknown[]): void {\n logger.log('[LocalVariables]', ...args);\n}\n\n/**\n * Adds local variables to exception frames\n */\nexport const localVariablesAsyncIntegration = defineIntegration(((\n integrationOptions: LocalVariablesIntegrationOptions = {},\n) => {\n const cachedFrames: LRUMap<string, FrameVariables[]> = new LRUMap(20);\n\n function addLocalVariablesToException(exception: Exception): void {\n const hash = hashFrames(exception?.stacktrace?.frames);\n\n if (hash === undefined) {\n return;\n }\n\n // Check if we have local variables for an exception that matches the hash\n // remove is identical to get but also removes the entry from the cache\n const cachedFrame = cachedFrames.remove(hash);\n\n if (cachedFrame === undefined) {\n return;\n }\n\n // Filter out frames where the function name is `new Promise` since these are in the error.stack frames\n // but do not appear in the debugger call frames\n const frames = (exception.stacktrace?.frames || []).filter(frame => frame.function !== 'new Promise');\n\n for (let i = 0; i < frames.length; i++) {\n // Sentry frames are in reverse order\n const frameIndex = frames.length - i - 1;\n\n const cachedFrameVariable = cachedFrame[i];\n const frameVariable = frames[frameIndex];\n\n if (!frameVariable || !cachedFrameVariable) {\n // Drop out if we run out of frames to match up\n break;\n }\n\n if (\n // We need to have vars to add\n cachedFrameVariable.vars === undefined ||\n // We're not interested in frames that are not in_app because the vars are not relevant\n frameVariable.in_app === false ||\n // The function names need to match\n !functionNamesMatch(frameVariable.function, cachedFrameVariable.function)\n ) {\n continue;\n }\n\n frameVariable.vars = cachedFrameVariable.vars;\n }\n }\n\n function addLocalVariablesToEvent(event: Event): Event {\n for (const exception of event.exception?.values || []) {\n addLocalVariablesToException(exception);\n }\n\n return event;\n }\n\n async function startInspector(): Promise<void> {\n // We load inspector dynamically because on some platforms Node is built without inspector support\n const inspector = await import('node:inspector');\n if (!inspector.url()) {\n inspector.open(0);\n }\n }\n\n function startWorker(options: LocalVariablesWorkerArgs): void {\n const worker = new Worker(new URL(`data:application/javascript;base64,${base64WorkerScript}`), {\n workerData: options,\n // We don't want any Node args to be passed to the worker\n execArgv: [],\n });\n\n process.on('exit', () => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n });\n\n worker.on('message', ({ exceptionHash, frames }) => {\n cachedFrames.set(exceptionHash, frames);\n });\n\n worker.once('error', (err: Error) => {\n log('Worker error', err);\n });\n\n worker.once('exit', (code: number) => {\n log('Worker exit', code);\n });\n\n // Ensure this thread can't block app exit\n worker.unref();\n }\n\n return {\n name: 'LocalVariablesAsync',\n setup(client: NodeClient) {\n const clientOptions = client.getOptions();\n\n if (!clientOptions.includeLocalVariables) {\n return;\n }\n\n const options: LocalVariablesWorkerArgs = {\n ...integrationOptions,\n debug: logger.isEnabled(),\n };\n\n startInspector().then(\n () => {\n try {\n startWorker(options);\n } catch (e) {\n logger.error('Failed to start worker', e);\n }\n },\n e => {\n logger.error('Failed to start inspector', e);\n },\n );\n },\n processEvent(event: Event): Event {\n return addLocalVariablesToEvent(event);\n },\n };\n}) satisfies IntegrationFn);\n","import type { Debugger, InspectorNotification, Runtime, Session } from 'node:inspector';\nimport { defineIntegration, getClient } from '@sentry/core';\nimport type { Event, Exception, IntegrationFn, StackParser } from '@sentry/types';\nimport { LRUMap, logger } from '@sentry/utils';\n\nimport { NODE_MAJOR } from '../../nodeVersion';\nimport type { NodeClient } from '../../sdk/client';\nimport type {\n FrameVariables,\n LocalVariablesIntegrationOptions,\n PausedExceptionEvent,\n RateLimitIncrement,\n Variables,\n} from './common';\nimport { createRateLimiter, functionNamesMatch, hashFrames, hashFromStack } from './common';\n\ntype OnPauseEvent = InspectorNotification<Debugger.PausedEventDataType>;\nexport interface DebugSession {\n /** Configures and connects to the debug session */\n configureAndConnect(onPause: (message: OnPauseEvent, complete: () => void) => void, captureAll: boolean): void;\n /** Updates which kind of exceptions to capture */\n setPauseOnExceptions(captureAll: boolean): void;\n /** Gets local variables for an objectId */\n getLocalVariables(objectId: string, callback: (vars: Variables) => void): void;\n}\n\ntype Next<T> = (result: T) => void;\ntype Add<T> = (fn: Next<T>) => void;\ntype CallbackWrapper<T> = { add: Add<T>; next: Next<T> };\n\n/** Creates a container for callbacks to be called sequentially */\nexport function createCallbackList<T>(complete: Next<T>): CallbackWrapper<T> {\n // A collection of callbacks to be executed last to first\n let callbacks: Next<T>[] = [];\n\n let completedCalled = false;\n function checkedComplete(result: T): void {\n callbacks = [];\n if (completedCalled) {\n return;\n }\n completedCalled = true;\n complete(result);\n }\n\n // complete should be called last\n callbacks.push(checkedComplete);\n\n function add(fn: Next<T>): void {\n callbacks.push(fn);\n }\n\n function next(result: T): void {\n const popped = callbacks.pop() || checkedComplete;\n\n try {\n popped(result);\n } catch (_) {\n // If there is an error, we still want to call the complete callback\n checkedComplete(result);\n }\n }\n\n return { add, next };\n}\n\n/**\n * Promise API is available as `Experimental` and in Node 19 only.\n *\n * Callback-based API is `Stable` since v14 and `Experimental` since v8.\n * Because of that, we are creating our own `AsyncSession` class.\n *\n * https://nodejs.org/docs/latest-v19.x/api/inspector.html#promises-api\n * https://nodejs.org/docs/latest-v14.x/api/inspector.html\n */\nclass AsyncSession implements DebugSession {\n /** Throws if inspector API is not available */\n private constructor(private readonly _session: Session) {\n //\n }\n\n public static async create(orDefault?: DebugSession | undefined): Promise<DebugSession> {\n if (orDefault) {\n return orDefault;\n }\n\n const inspector = await import('node:inspector');\n return new AsyncSession(new inspector.Session());\n }\n\n /** @inheritdoc */\n public configureAndConnect(onPause: (event: OnPauseEvent, complete: () => void) => void, captureAll: boolean): void {\n this._session.connect();\n\n this._session.on('Debugger.paused', event => {\n onPause(event, () => {\n // After the pause work is complete, resume execution or the exception context memory is leaked\n this._session.post('Debugger.resume');\n });\n });\n\n this._session.post('Debugger.enable');\n this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' });\n }\n\n public setPauseOnExceptions(captureAll: boolean): void {\n this._session.post('Debugger.setPauseOnExceptions', { state: captureAll ? 'all' : 'uncaught' });\n }\n\n /** @inheritdoc */\n public getLocalVariables(objectId: string, complete: (vars: Variables) => void): void {\n this._getProperties(objectId, props => {\n const { add, next } = createCallbackList<Variables>(complete);\n\n for (const prop of props) {\n if (prop?.value?.objectId && prop?.value.className === 'Array') {\n const id = prop.value.objectId;\n add(vars => this._unrollArray(id, prop.name, vars, next));\n } else if (prop?.value?.objectId && prop?.value?.className === 'Object') {\n const id = prop.value.objectId;\n add(vars => this._unrollObject(id, prop.name, vars, next));\n } else if (prop?.value) {\n add(vars => this._unrollOther(prop, vars, next));\n }\n }\n\n next({});\n });\n }\n\n /**\n * Gets all the PropertyDescriptors of an object\n */\n private _getProperties(objectId: string, next: (result: Runtime.PropertyDescriptor[]) => void): void {\n this._session.post(\n 'Runtime.getProperties',\n {\n objectId,\n ownProperties: true,\n },\n (err, params) => {\n if (err) {\n next([]);\n } else {\n next(params.result);\n }\n },\n );\n }\n\n /**\n * Unrolls an array property\n */\n private _unrollArray(objectId: string, name: string, vars: Variables, next: (vars: Variables) => void): void {\n this._getProperties(objectId, props => {\n vars[name] = props\n .filter(v => v.name !== 'length' && !isNaN(parseInt(v.name, 10)))\n .sort((a, b) => parseInt(a.name, 10) - parseInt(b.name, 10))\n .map(v => v?.value?.value);\n\n next(vars);\n });\n }\n\n /**\n * Unrolls an object property\n */\n private _unrollObject(objectId: string, name: string, vars: Variables, next: (obj: Variables) => void): void {\n this._getProperties(objectId, props => {\n vars[name] = props\n .map<[string, unknown]>(v => [v.name, v?.value?.value])\n .reduce((obj, [key, val]) => {\n obj[key] = val;\n return obj;\n }, {} as Variables);\n\n next(vars);\n });\n }\n\n /**\n * Unrolls other properties\n */\n private _unrollOther(prop: Runtime.PropertyDescriptor, vars: Variables, next: (vars: Variables) => void): void {\n if (prop.value) {\n if ('value' in prop.value) {\n if (prop.value.value === undefined || prop.value.value === null) {\n vars[prop.name] = `<${prop.value.value}>`;\n } else {\n vars[prop.name] = prop.value.value;\n }\n } else if ('description' in prop.value && prop.value.type !== 'function') {\n vars[prop.name] = `<${prop.value.description}>`;\n } else if (prop.value.type === 'undefined') {\n vars[prop.name] = '<undefined>';\n }\n }\n\n next(vars);\n }\n}\n\nconst INTEGRATION_NAME = 'LocalVariables';\n\n/**\n * Adds local variables to exception frames\n */\nconst _localVariablesSyncIntegration = ((\n options: LocalVariablesIntegrationOptions = {},\n sessionOverride?: DebugSession,\n) => {\n const cachedFrames: LRUMap<string, FrameVariables[]> = new LRUMap(20);\n let rateLimiter: RateLimitIncrement | undefined;\n let shouldProcessEvent = false;\n\n function addLocalVariablesToException(exception: Exception): void {\n const hash = hashFrames(exception?.stacktrace?.frames);\n\n if (hash === undefined) {\n return;\n }\n\n // Check if we have local variables for an exception that matches the hash\n // remove is identical to get but also removes the entry from the cache\n const cachedFrame = cachedFrames.remove(hash);\n\n if (cachedFrame === undefined) {\n return;\n }\n\n // Filter out frames where the function name is `new Promise` since these are in the error.stack frames\n // but do not appear in the debugger call frames\n const frames = (exception.stacktrace?.frames || []).filter(frame => frame.function !== 'new Promise');\n\n for (let i = 0; i < frames.length; i++) {\n // Sentry frames are in reverse order\n const frameIndex = frames.length - i - 1;\n\n const cachedFrameVariable = cachedFrame[i];\n const frameVariable = frames[frameIndex];\n\n // Drop out if we run out of frames to match up\n if (!frameVariable || !cachedFrameVariable) {\n break;\n }\n\n if (\n // We need to have vars to add\n cachedFrameVariable.vars === undefined ||\n // We're not interested in frames that are not in_app because the vars are not relevant\n frameVariable.in_app === false ||\n // The function names need to match\n !functionNamesMatch(frameVariable.function, cachedFrameVariable.function)\n ) {\n continue;\n }\n\n frameVariable.vars = cachedFrameVariable.vars;\n }\n }\n\n function addLocalVariablesToEvent(event: Event): Event {\n for (const exception of event?.exception?.values || []) {\n addLocalVariablesToException(exception);\n }\n\n return event;\n }\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n const client = getClient<NodeClient>();\n const clientOptions = client?.getOptions();\n\n if (!clientOptions?.includeLocalVariables) {\n return;\n }\n\n // Only setup this integration if the Node version is >= v18\n // https://github.com/getsentry/sentry-javascript/issues/7697\n const unsupportedNodeVersion = NODE_MAJOR < 18;\n\n if (unsupportedNodeVersion) {\n logger.log('The `LocalVariables` integration is only supported on Node >= v18.');\n return;\n }\n\n AsyncSession.create(sessionOverride).then(\n session => {\n function handlePaused(\n stackParser: StackParser,\n { params: { reason, data, callFrames } }: InspectorNotification<PausedExceptionEvent>,\n complete: () => void,\n ): void {\n if (reason !== 'exception' && reason !== 'promiseRejection') {\n complete();\n return;\n }\n\n rateLimiter?.();\n\n // data.description contains the original error.stack\n const exceptionHash = hashFromStack(stackParser, data?.description);\n\n if (exceptionHash == undefined) {\n complete();\n return;\n }\n\n const { add, next } = createCallbackList<FrameVariables[]>(frames => {\n cachedFrames.set(exceptionHash, frames);\n complete();\n });\n\n // Because we're queuing up and making all these calls synchronously, we can potentially overflow the stack\n // For this reason we only attempt to get local variables for the first 5 frames\n for (let i = 0; i < Math.min(callFrames.length, 5); i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { scopeChain, functionName, this: obj } = callFrames[i]!;\n\n const localScope = scopeChain.find(scope => scope.type === 'local');\n\n // obj.className is undefined in ESM modules\n const fn =\n obj.className === 'global' || !obj.className ? functionName : `${obj.className}.${functionName}`;\n\n if (localScope?.object.objectId === undefined) {\n add(frames => {\n frames[i] = { function: fn };\n next(frames);\n });\n } else {\n const id = localScope.object.objectId;\n add(frames =>\n session?.getLocalVariables(id, vars => {\n frames[i] = { function: fn, vars };\n next(frames);\n }),\n );\n }\n }\n\n next([]);\n }\n\n const captureAll = options.captureAllExceptions !== false;\n\n session.configureAndConnect(\n (ev, complete) =>\n handlePaused(clientOptions.stackParser, ev as InspectorNotification<PausedExceptionEvent>, complete),\n captureAll,\n );\n\n if (captureAll) {\n const max = options.maxExceptionsPerSecond || 50;\n\n rateLimiter = createRateLimiter(\n max,\n () => {\n logger.log('Local variables rate-limit lifted.');\n session?.setPauseOnExceptions(true);\n },\n seconds => {\n logger.log(\n `Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`,\n );\n session?.setPauseOnExceptions(false);\n },\n );\n }\n\n shouldProcessEvent = true;\n },\n error => {\n logger.log('The `LocalVariables` integration failed to start.', error);\n },\n );\n },\n processEvent(event: Event): Event {\n if (shouldProcessEvent) {\n return addLocalVariablesToEvent(event);\n }\n\n return event;\n },\n // These are entirely for testing\n _getCachedFramesCount(): number {\n return cachedFrames.size;\n },\n _getFirstCachedFrame(): FrameVariables[] | undefined {\n return cachedFrames.values()[0];\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds local variables to exception frames.\n */\nexport const localVariablesSyncIntegration = defineIntegration(_localVariablesSyncIntegration);\n","import type { Integration } from '@sentry/types';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport type { LocalVariablesIntegrationOptions } from './common';\nimport { localVariablesAsyncIntegration } from './local-variables-async';\nimport { localVariablesSyncIntegration } from './local-variables-sync';\n\nexport const localVariablesIntegration = (options: LocalVariablesIntegrationOptions = {}): Integration => {\n return NODE_VERSION.major < 19 ? localVariablesSyncIntegration(options) : localVariablesAsyncIntegration(options);\n};\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\n\nlet moduleCache: { [key: string]: string };\n\nconst INTEGRATION_NAME = 'Modules';\n\nconst _modulesIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event) {\n event.modules = {\n ...event.modules,\n ..._getModules(),\n };\n\n return event;\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Add node modules / packages to the event.\n */\nexport const modulesIntegration = defineIntegration(_modulesIntegration);\n\n/** Extract information about paths */\nfunction getPaths(): string[] {\n try {\n return require.cache ? Object.keys(require.cache as Record<string, unknown>) : [];\n } catch (e) {\n return [];\n }\n}\n\n/** Extract information about package.json modules */\nfunction collectModules(): {\n [name: string]: string;\n} {\n const mainPaths = (require.main && require.main.paths) || [];\n const paths = getPaths();\n const infos: {\n [name: string]: string;\n } = {};\n const seen: {\n [path: string]: boolean;\n } = {};\n\n paths.forEach(path => {\n let dir = path;\n\n /** Traverse directories upward in the search of package.json file */\n const updir = (): void | (() => void) => {\n const orig = dir;\n dir = dirname(orig);\n\n if (!dir || orig === dir || seen[orig]) {\n return undefined;\n }\n if (mainPaths.indexOf(dir) < 0) {\n return updir();\n }\n\n const pkgfile = join(orig, 'package.json');\n seen[orig] = true;\n\n if (!existsSync(pkgfile)) {\n return updir();\n }\n\n try {\n const info = JSON.parse(readFileSync(pkgfile, 'utf8')) as {\n name: string;\n version: string;\n };\n infos[info.name] = info.version;\n } catch (_oO) {\n // no-empty\n }\n };\n\n updir();\n });\n\n return infos;\n}\n\n/** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */\nfunction _getModules(): { [key: string]: string } {\n if (!moduleCache) {\n moduleCache = collectModules();\n }\n return moduleCache;\n}\n","import { getClient } from '@sentry/core';\nimport { consoleSandbox, logger } from '@sentry/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClient } from '../sdk/client';\n\nconst DEFAULT_SHUTDOWN_TIMEOUT = 2000;\n\n/**\n * @hidden\n */\nexport function logAndExitProcess(error: Error): void {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(error);\n });\n\n const client = getClient<NodeClient>();\n\n if (client === undefined) {\n DEBUG_BUILD && logger.warn('No NodeClient was defined, we are exiting the process now.');\n global.process.exit(1);\n return;\n }\n\n const options = client.getOptions();\n const timeout =\n (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) ||\n DEFAULT_SHUTDOWN_TIMEOUT;\n client.close(timeout).then(\n (result: boolean) => {\n if (!result) {\n DEBUG_BUILD && logger.warn('We reached the timeout for emptying the request buffer, still exiting now!');\n }\n global.process.exit(1);\n },\n error => {\n DEBUG_BUILD && logger.error(error);\n },\n );\n}\n","import { captureException, defineIntegration } from '@sentry/core';\nimport { getClient } from '@sentry/core';\nimport { logger } from '@sentry/utils';\n\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClient } from '../sdk/client';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype OnFatalErrorHandler = (firstError: Error, secondError?: Error) => void;\n\ntype TaggedListener = NodeJS.UncaughtExceptionListener & {\n tag?: string;\n};\n\ninterface OnUncaughtExceptionOptions {\n /**\n * Controls if the SDK should register a handler to exit the process on uncaught errors:\n * - `true`: The SDK will exit the process on all uncaught errors.\n * - `false`: The SDK will only exit the process when there are no other `uncaughtException` handlers attached.\n *\n * Default: `false`\n */\n exitEvenIfOtherHandlersAreRegistered: boolean;\n\n /**\n * This is called when an uncaught error would cause the process to exit.\n *\n * @param firstError Uncaught error causing the process to exit\n * @param secondError Will be set if the handler was called multiple times. This can happen either because\n * `onFatalError` itself threw, or because an independent error happened somewhere else while `onFatalError`\n * was running.\n */\n onFatalError?(this: void, firstError: Error, secondError?: Error): void;\n}\n\nconst INTEGRATION_NAME = 'OnUncaughtException';\n\n/**\n * Add a global exception handler.\n */\nexport const onUncaughtExceptionIntegration = defineIntegration((options: Partial<OnUncaughtExceptionOptions> = {}) => {\n const optionsWithDefaults = {\n exitEvenIfOtherHandlersAreRegistered: false,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n global.process.on('uncaughtException', makeErrorHandler(client, optionsWithDefaults));\n },\n };\n});\n\ntype ErrorHandler = { _errorHandler: boolean } & ((error: Error) => void);\n\n/** Exported only for tests */\nexport function makeErrorHandler(client: NodeClient, options: OnUncaughtExceptionOptions): ErrorHandler {\n const timeout = 2000;\n let caughtFirstError: boolean = false;\n let caughtSecondError: boolean = false;\n let calledFatalError: boolean = false;\n let firstError: Error;\n\n const clientOptions = client.getOptions();\n\n return Object.assign(\n (error: Error): void => {\n let onFatalError: OnFatalErrorHandler = logAndExitProcess;\n\n if (options.onFatalError) {\n onFatalError = options.onFatalError;\n } else if (clientOptions.onFatalError) {\n onFatalError = clientOptions.onFatalError as OnFatalErrorHandler;\n }\n\n // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not\n // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust\n // exit behaviour of the SDK accordingly:\n // - If other listeners are attached, do not exit.\n // - If the only listener attached is ours, exit.\n const userProvidedListenersCount = (global.process.listeners('uncaughtException') as TaggedListener[]).filter(\n listener => {\n // There are 3 listeners we ignore:\n return (\n // as soon as we're using domains this listener is attached by node itself\n listener.name !== 'domainUncaughtExceptionClear' &&\n // the handler we register for tracing\n listener.tag !== 'sentry_tracingErrorCallback' &&\n // the handler we register in this integration\n (listener as ErrorHandler)._errorHandler !== true\n );\n },\n ).length;\n\n const processWouldExit = userProvidedListenersCount === 0;\n const shouldApplyFatalHandlingLogic = options.exitEvenIfOtherHandlersAreRegistered || processWouldExit;\n\n if (!caughtFirstError) {\n // this is the first uncaught error and the ultimate reason for shutting down\n // we want to do absolutely everything possible to ensure it gets captured\n // also we want to make sure we don't go recursion crazy if more errors happen after this one\n firstError = error;\n caughtFirstError = true;\n\n if (getClient() === client) {\n captureException(error, {\n originalException: error,\n captureContext: {\n level: 'fatal',\n },\n mechanism: {\n handled: false,\n type: 'onuncaughtexception',\n },\n });\n }\n\n if (!calledFatalError && shouldApplyFatalHandlingLogic) {\n calledFatalError = true;\n onFatalError(error);\n }\n } else {\n if (shouldApplyFatalHandlingLogic) {\n if (calledFatalError) {\n // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down\n DEBUG_BUILD &&\n logger.warn(\n 'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown',\n );\n logAndExitProcess(error);\n } else if (!caughtSecondError) {\n // two cases for how we can hit this branch:\n // - capturing of first error blew up and we just caught the exception from that\n // - quit trying to capture, proceed with shutdown\n // - a second independent error happened while waiting for first error to capture\n // - want to avoid causing premature shutdown before first error capture finishes\n // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff\n // so let's instead just delay a bit before we proceed with our action here\n // in case 1, we just wait a bit unnecessarily but ultimately do the same thing\n // in case 2, the delay hopefully made us wait long enough for the capture to finish\n // two potential nonideal outcomes:\n // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError\n // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error\n // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError)\n // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish\n caughtSecondError = true;\n setTimeout(() => {\n if (!calledFatalError) {\n // it was probably case 1, let's treat err as the sendErr and call onFatalError\n calledFatalError = true;\n onFatalError(firstError, error);\n } else {\n // it was probably case 2, our first error finished capturing while we waited, cool, do nothing\n }\n }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc\n }\n }\n }\n },\n { _errorHandler: true },\n );\n}\n","import { captureException, defineIntegration, getClient } from '@sentry/core';\nimport type { Client, IntegrationFn } from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\ninterface OnUnhandledRejectionOptions {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n}\n\nconst INTEGRATION_NAME = 'OnUnhandledRejection';\n\nconst _onUnhandledRejectionIntegration = ((options: Partial<OnUnhandledRejectionOptions> = {}) => {\n const mode = options.mode || 'warn';\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, { mode }));\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Add a global promise rejection handler.\n */\nexport const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration);\n\n/**\n * Send an exception with reason\n * @param reason string\n * @param promise promise\n *\n * Exported only for tests.\n */\nexport function makeUnhandledPromiseHandler(\n client: Client,\n options: OnUnhandledRejectionOptions,\n): (reason: unknown, promise: unknown) => void {\n return function sendUnhandledPromise(reason: unknown, promise: unknown): void {\n if (getClient() !== client) {\n return;\n }\n\n captureException(reason, {\n originalException: promise,\n captureContext: {\n extra: { unhandledPromiseRejection: true },\n },\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n\n handleRejection(reason, options);\n };\n}\n\n/**\n * Handler for `mode` option\n\n */\nfunction handleRejection(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n reason: any,\n options: OnUnhandledRejectionOptions,\n): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (options.mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.error(reason && reason.stack ? reason.stack : reason);\n });\n } else if (options.mode === 'strict') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n}\n","import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { addOpenTelemetryInstrumentation } from '@sentry/opentelemetry';\n\nconst INSTRUMENTED: Record<string, Instrumentation> = {};\n\n/**\n * Instrument an OpenTelemetry instrumentation once.\n * This will skip running instrumentation again if it was already instrumented.\n */\nexport function generateInstrumentOnce<Options = unknown>(\n name: string,\n creator: (options?: Options) => Instrumentation,\n): ((options?: Options) => void) & { id: string } {\n return Object.assign(\n (options?: Options) => {\n const instrumented = INSTRUMENTED[name];\n if (instrumented) {\n // If options are provided, ensure we update them\n if (options) {\n instrumented.setConfig(options);\n }\n return;\n }\n\n const instrumentation = creator(options);\n INSTRUMENTED[name] = instrumentation;\n\n addOpenTelemetryInstrumentation(instrumentation);\n },\n { id: name },\n );\n}\n","/** Detect CommonJS. */\nexport function isCjs(): boolean {\n return typeof require !== 'undefined';\n}\n","import type * as http from 'node:http';\nimport { ExpressInstrumentation } from '@opentelemetry/instrumentation-express';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, defineIntegration, getDefaultIsolationScope, spanToJSON } from '@sentry/core';\nimport { captureException, getClient, getIsolationScope } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { generateInstrumentOnce } from '../../otel/instrument';\nimport type { NodeClient } from '../../sdk/client';\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\nimport { ensureIsWrapped } from '../../utils/ensureIsWrapped';\n\nconst INTEGRATION_NAME = 'Express';\n\nexport const instrumentExpress = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new ExpressInstrumentation({\n requestHook(span) {\n addOriginToSpan(span, 'auto.http.otel.express');\n\n const attributes = spanToJSON(span).data || {};\n // this is one of: middleware, request_handler, router\n const type = attributes['express.type'];\n\n if (type) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, `${type}.express`);\n }\n\n // Also update the name, we don't need to \"middleware - \" prefix\n const name = attributes['express.name'];\n if (typeof name === 'string') {\n span.updateName(name);\n }\n },\n spanNameHook(info, defaultName) {\n if (getIsolationScope() === getDefaultIsolationScope()) {\n DEBUG_BUILD &&\n logger.warn('Isolation scope is still default isolation scope - skipping setting transactionName');\n return defaultName;\n }\n if (info.layerType === 'request_handler') {\n // type cast b/c Otel unfortunately types info.request as any :(\n const req = info.request as { method?: string };\n const method = req.method ? req.method.toUpperCase() : 'GET';\n getIsolationScope().setTransactionName(`${method} ${info.route}`);\n }\n return defaultName;\n },\n }),\n);\n\nconst _expressIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentExpress();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Express integration\n *\n * Capture tracing data for express.\n * In order to capture exceptions, you have to call `setupExpressErrorHandler(app)` before any other middleware and after all controllers.\n */\nexport const expressIntegration = defineIntegration(_expressIntegration);\n\ninterface MiddlewareError extends Error {\n status?: number | string;\n statusCode?: number | string;\n status_code?: number | string;\n output?: {\n statusCode?: number | string;\n };\n}\n\ntype ExpressMiddleware = (\n error: MiddlewareError,\n req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n) => void;\n\ninterface ExpressHandlerOptions {\n /**\n * Callback method deciding whether error should be captured and sent to Sentry\n * @param error Captured middleware error\n */\n shouldHandleError?(this: void, error: MiddlewareError): boolean;\n}\n\n/**\n * An Express-compatible error handler.\n */\nexport function expressErrorHandler(options?: ExpressHandlerOptions): ExpressMiddleware {\n return function sentryErrorMiddleware(\n error: MiddlewareError,\n _req: http.IncomingMessage,\n res: http.ServerResponse,\n next: (error: MiddlewareError) => void,\n ): void {\n const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError;\n\n if (shouldHandleError(error)) {\n const client = getClient<NodeClient>();\n if (client && client.getOptions().autoSessionTracking) {\n // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the\n // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only\n // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be\n // running in SessionAggregates mode\n const isSessionAggregatesMode = client['_sessionFlusher'] !== undefined;\n if (isSessionAggregatesMode) {\n const requestSession = getIsolationScope().getRequestSession();\n // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a\n // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within\n // the bounds of a request, and if so the status is updated\n if (requestSession && requestSession.status !== undefined) {\n requestSession.status = 'crashed';\n }\n }\n }\n\n const eventId = captureException(error, { mechanism: { type: 'middleware', handled: false } });\n (res as { sentry?: string }).sentry = eventId;\n next(error);\n\n return;\n }\n\n next(error);\n };\n}\n\n/**\n * Setup an error handler for Express.\n * The error handler must be before any other middleware and after all controllers.\n */\nexport function setupExpressErrorHandler(\n app: { use: (middleware: ExpressMiddleware) => unknown },\n options?: ExpressHandlerOptions,\n): void {\n app.use(expressErrorHandler(options));\n ensureIsWrapped(app.use, 'express');\n}\n\nfunction getStatusCodeFromResponse(error: MiddlewareError): number {\n const statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode);\n return statusCode ? parseInt(statusCode as string, 10) : 500;\n}\n\n/** Returns true if response code is internal server error */\nfunction defaultShouldHandleError(error: MiddlewareError): boolean {\n const status = getStatusCodeFromResponse(error);\n return status >= 500;\n}\n","import { FastifyInstrumentation } from '@opentelemetry/instrumentation-fastify';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n captureException,\n defineIntegration,\n getClient,\n getIsolationScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn, Span } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\nimport { ensureIsWrapped } from '../../utils/ensureIsWrapped';\n\n// We inline the types we care about here\ninterface Fastify {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n register: (plugin: any) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n addHook: (hook: string, handler: (request: any, reply: any, error: Error) => void) => void;\n}\n\n/**\n * Minimal request type containing properties around route information.\n * Works for Fastify 3, 4 and presumably 5.\n */\ninterface FastifyRequestRouteInfo {\n // since fastify@4.10.0\n routeOptions?: {\n url?: string;\n method?: string;\n };\n routerPath?: string;\n}\n\nconst INTEGRATION_NAME = 'Fastify';\n\nexport const instrumentFastify = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new FastifyInstrumentation({\n requestHook(span) {\n addFastifySpanAttributes(span);\n },\n }),\n);\n\nconst _fastifyIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentFastify();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Express integration\n *\n * Capture tracing data for fastify.\n */\nexport const fastifyIntegration = defineIntegration(_fastifyIntegration);\n\n/**\n * Setup an error handler for Fastify.\n */\nexport function setupFastifyErrorHandler(fastify: Fastify): void {\n const plugin = Object.assign(\n function (fastify: Fastify, _options: unknown, done: () => void): void {\n fastify.addHook('onError', async (_request, _reply, error) => {\n captureException(error);\n });\n\n // registering `onRequest` hook here instead of using Otel `onRequest` callback b/c `onRequest` hook\n // is ironically called in the fastify `preHandler` hook which is called later in the lifecycle:\n // https://fastify.dev/docs/latest/Reference/Lifecycle/\n fastify.addHook('onRequest', async (request, _reply) => {\n const reqWithRouteInfo = request as FastifyRequestRouteInfo;\n\n // Taken from Otel Fastify instrumentation:\n // https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/plugins/node/opentelemetry-instrumentation-fastify/src/instrumentation.ts#L94-L96\n const routeName = reqWithRouteInfo.routeOptions?.url || reqWithRouteInfo.routerPath;\n const method = reqWithRouteInfo.routeOptions?.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n });\n\n done();\n },\n {\n [Symbol.for('skip-override')]: true,\n [Symbol.for('fastify.display-name')]: 'sentry-fastify-error-handler',\n },\n );\n\n fastify.register(plugin);\n\n // Sadly, middleware spans do not go through `requestHook`, so we handle those here\n // We register this hook in this method, because if we register it in the integration `setup`,\n // it would always run even for users that are not even using fastify\n const client = getClient();\n if (client) {\n client.on('spanStart', span => {\n addFastifySpanAttributes(span);\n });\n }\n\n ensureIsWrapped(fastify.addHook, 'fastify');\n}\n\nfunction addFastifySpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data || {};\n\n // this is one of: middleware, request_handler\n const type = attributes['fastify.type'];\n\n // If this is already set, or we have no fastify span, no need to process again...\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.fastify',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.fastify`,\n });\n\n // Also update the name, we don't need to \"middleware - \" prefix\n const name = attributes['fastify.name'] || attributes['plugin.name'] || attributes['hook.name'];\n if (typeof name === 'string') {\n // Also remove `fastify -> ` prefix\n span.updateName(name.replace(/^fastify -> /, ''));\n }\n}\n","import { GraphQLInstrumentation } from '@opentelemetry/instrumentation-graphql';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\n\ninterface GraphqlOptions {\n /** Do not create spans for resolvers. */\n ignoreResolveSpans?: boolean;\n\n /**\n * Don't create spans for the execution of the default resolver on object properties.\n *\n * When a resolver function is not defined on the schema for a field, graphql will\n * use the default resolver which just looks for a property with that name on the object.\n * If the property is not a function, it's not very interesting to trace.\n * This option can reduce noise and number of spans created.\n */\n ignoreTrivalResolveSpans?: boolean;\n}\n\nconst INTEGRATION_NAME = 'Graphql';\n\nexport const instrumentGraphql = generateInstrumentOnce<GraphqlOptions>(\n INTEGRATION_NAME,\n (_options: GraphqlOptions = {}) => {\n const options = {\n ignoreResolveSpans: true,\n ignoreTrivialResolveSpans: true,\n ..._options,\n };\n\n return new GraphQLInstrumentation({\n ...options,\n responseHook(span) {\n addOriginToSpan(span, 'auto.graphql.otel.graphql');\n },\n });\n },\n);\n\nconst _graphqlIntegration = ((options: GraphqlOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentGraphql(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * GraphQL integration\n *\n * Capture tracing data for GraphQL.\n */\nexport const graphqlIntegration = defineIntegration(_graphqlIntegration);\n","import { MongoDBInstrumentation } from '@opentelemetry/instrumentation-mongodb';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\n\nconst INTEGRATION_NAME = 'Mongo';\n\nexport const instrumentMongo = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new MongoDBInstrumentation({\n responseHook(span) {\n addOriginToSpan(span, 'auto.db.otel.mongo');\n },\n }),\n);\n\nconst _mongoIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentMongo();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * MongoDB integration\n *\n * Capture tracing data for MongoDB.\n */\nexport const mongoIntegration = defineIntegration(_mongoIntegration);\n","import { MongooseInstrumentation } from '@opentelemetry/instrumentation-mongoose';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\n\nconst INTEGRATION_NAME = 'Mongoose';\n\nexport const instrumentMongoose = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new MongooseInstrumentation({\n responseHook(span) {\n addOriginToSpan(span, 'auto.db.otel.mongoose');\n },\n }),\n);\n\nconst _mongooseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentMongoose();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Mongoose integration\n *\n * Capture tracing data for Mongoose.\n */\nexport const mongooseIntegration = defineIntegration(_mongooseIntegration);\n","import { MySQLInstrumentation } from '@opentelemetry/instrumentation-mysql';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nconst INTEGRATION_NAME = 'Mysql';\n\nexport const instrumentMysql = generateInstrumentOnce(INTEGRATION_NAME, () => new MySQLInstrumentation({}));\n\nconst _mysqlIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentMysql();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * MySQL integration\n *\n * Capture tracing data for mysql.\n */\nexport const mysqlIntegration = defineIntegration(_mysqlIntegration);\n","import { MySQL2Instrumentation } from '@opentelemetry/instrumentation-mysql2';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\n\nconst INTEGRATION_NAME = 'Mysql2';\n\nexport const instrumentMysql2 = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new MySQL2Instrumentation({\n responseHook(span) {\n addOriginToSpan(span, 'auto.db.otel.mysql2');\n },\n }),\n);\n\nconst _mysql2Integration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentMysql2();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * MySQL2 integration\n *\n * Capture tracing data for mysql2\n */\nexport const mysql2Integration = defineIntegration(_mysql2Integration);\n","import type { CommandArgs as IORedisCommandArgs } from '@opentelemetry/instrumentation-ioredis';\nimport { flatten } from '@sentry/utils';\n\nconst SINGLE_ARG_COMMANDS = ['get', 'set', 'setex'];\n\nexport const GET_COMMANDS = ['get', 'mget'];\nexport const SET_COMMANDS = ['set', 'setex'];\n// todo: del, expire\n\n/** Checks if a given command is in the list of redis commands.\n * Useful because commands can come in lowercase or uppercase (depending on the library). */\nexport function isInCommands(redisCommands: string[], command: string): boolean {\n return redisCommands.includes(command.toLowerCase());\n}\n\n/** Determine cache operation based on redis statement */\nexport function getCacheOperation(\n command: string,\n): 'cache.get' | 'cache.put' | 'cache.remove' | 'cache.flush' | undefined {\n if (isInCommands(GET_COMMANDS, command)) {\n return 'cache.get';\n } else if (isInCommands(SET_COMMANDS, command)) {\n return 'cache.put';\n } else {\n return undefined;\n }\n}\n\nfunction keyHasPrefix(key: string, prefixes: string[]): boolean {\n return prefixes.some(prefix => key.startsWith(prefix));\n}\n\n/** Safely converts a redis key to a string (comma-separated if there are multiple keys) */\nexport function getCacheKeySafely(redisCommand: string, cmdArgs: IORedisCommandArgs): string[] | undefined {\n try {\n if (cmdArgs.length === 0) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const processArg = (arg: string | Buffer | number | any[]): string[] => {\n if (typeof arg === 'string' || typeof arg === 'number' || Buffer.isBuffer(arg)) {\n return [arg.toString()];\n } else if (Array.isArray(arg)) {\n return flatten(arg.map(arg => processArg(arg)));\n } else {\n return ['<unknown>'];\n }\n };\n\n const firstArg = cmdArgs[0];\n if (isInCommands(SINGLE_ARG_COMMANDS, redisCommand) && firstArg != null) {\n return processArg(firstArg);\n }\n\n return flatten(cmdArgs.map(arg => processArg(arg)));\n } catch (e) {\n return undefined;\n }\n}\n\n/** Determines whether a redis operation should be considered as \"cache operation\" by checking if a key is prefixed.\n * We only support certain commands (such as 'set', 'get', 'mget'). */\nexport function shouldConsiderForCache(redisCommand: string, keys: string[], prefixes: string[]): boolean {\n if (!getCacheOperation(redisCommand)) {\n return false;\n }\n\n for (const key of keys) {\n if (keyHasPrefix(key, prefixes)) {\n return true;\n }\n }\n return false;\n}\n\n/** Calculates size based on the cache response value */\nexport function calculateCacheItemSize(response: unknown): number | undefined {\n const getSize = (value: unknown): number | undefined => {\n try {\n if (Buffer.isBuffer(value)) return value.byteLength;\n else if (typeof value === 'string') return value.length;\n else if (typeof value === 'number') return value.toString().length;\n else if (value === null || value === undefined) return 0;\n return JSON.stringify(value).length;\n } catch (e) {\n return undefined;\n }\n };\n\n return Array.isArray(response)\n ? response.reduce((acc: number | undefined, curr) => {\n const size = getSize(curr);\n return typeof size === 'number' ? (acc !== undefined ? acc + size : size) : acc;\n }, 0)\n : getSize(response);\n}\n","import type { Span } from '@opentelemetry/api';\nimport type { RedisResponseCustomAttributeFunction } from '@opentelemetry/instrumentation-ioredis';\nimport { IORedisInstrumentation } from '@opentelemetry/instrumentation-ioredis';\nimport { RedisInstrumentation } from '@opentelemetry/instrumentation-redis-4';\nimport {\n SEMANTIC_ATTRIBUTE_CACHE_HIT,\n SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE,\n SEMANTIC_ATTRIBUTE_CACHE_KEY,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n defineIntegration,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { truncate } from '@sentry/utils';\nimport { generateInstrumentOnce } from '../../otel/instrument';\nimport {\n GET_COMMANDS,\n calculateCacheItemSize,\n getCacheKeySafely,\n getCacheOperation,\n isInCommands,\n shouldConsiderForCache,\n} from '../../utils/redisCache';\n\ninterface RedisOptions {\n cachePrefixes?: string[];\n}\n\nconst INTEGRATION_NAME = 'Redis';\n\nlet _redisOptions: RedisOptions = {};\n\nconst cacheResponseHook: RedisResponseCustomAttributeFunction = (span: Span, redisCommand, cmdArgs, response) => {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.otel.redis');\n\n const safeKey = getCacheKeySafely(redisCommand, cmdArgs);\n const cacheOperation = getCacheOperation(redisCommand);\n\n if (\n !safeKey ||\n !cacheOperation ||\n !_redisOptions?.cachePrefixes ||\n !shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)\n ) {\n // not relevant for cache\n return;\n }\n\n // otel/ioredis seems to be using the old standard, as there was a change to those params: https://github.com/open-telemetry/opentelemetry-specification/issues/3199\n // We are using params based on the docs: https://opentelemetry.io/docs/specs/semconv/attributes-registry/network/\n const networkPeerAddress = spanToJSON(span).data?.['net.peer.name'];\n const networkPeerPort = spanToJSON(span).data?.['net.peer.port'];\n if (networkPeerPort && networkPeerAddress) {\n span.setAttributes({ 'network.peer.address': networkPeerAddress, 'network.peer.port': networkPeerPort });\n }\n\n const cacheItemSize = calculateCacheItemSize(response);\n\n if (cacheItemSize) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);\n }\n\n if (isInCommands(GET_COMMANDS, redisCommand) && cacheItemSize !== undefined) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,\n [SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey,\n });\n\n const spanDescription = safeKey.join(', ');\n\n span.updateName(truncate(spanDescription, 1024));\n};\n\nconst instrumentIORedis = generateInstrumentOnce('IORedis', () => {\n return new IORedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\nconst instrumentRedis4 = generateInstrumentOnce('Redis-4', () => {\n return new RedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\n/** To be able to preload all Redis OTel instrumentations with just one ID (\"Redis\"), all the instrumentations are generated in this one function */\nexport const instrumentRedis = Object.assign(\n (): void => {\n instrumentIORedis();\n instrumentRedis4();\n\n // todo: implement them gradually\n // new LegacyRedisInstrumentation({}),\n },\n { id: INTEGRATION_NAME },\n);\n\nconst _redisIntegration = ((options: RedisOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n _redisOptions = options;\n instrumentRedis();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Redis integration for \"ioredis\"\n *\n * Capture tracing data for redis and ioredis.\n */\nexport const redisIntegration = defineIntegration(_redisIntegration);\n","import { NestInstrumentation } from '@opentelemetry/instrumentation-nestjs-core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n captureException,\n defineIntegration,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn, Span } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\ninterface MinimalNestJsExecutionContext {\n getType: () => string;\n\n switchToHttp: () => {\n // minimal request object\n // according to official types, all properties are required but\n // let's play it safe and assume they're optional\n getRequest: () => {\n route?: {\n path?: string;\n };\n method?: string;\n };\n };\n}\n\ninterface NestJsErrorFilter {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n catch(exception: any, host: any): void;\n}\n\ninterface MinimalNestJsApp {\n useGlobalFilters: (arg0: NestJsErrorFilter) => void;\n useGlobalInterceptors: (interceptor: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n intercept: (context: MinimalNestJsExecutionContext, next: { handle: () => any }) => any;\n }) => void;\n}\n\nconst INTEGRATION_NAME = 'Nest';\n\nexport const instrumentNest = generateInstrumentOnce(INTEGRATION_NAME, () => new NestInstrumentation());\n\nconst _nestIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentNest();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Nest framework integration\n *\n * Capture tracing data for nest.\n */\nexport const nestIntegration = defineIntegration(_nestIntegration);\n\n/**\n * Setup an error handler for Nest.\n */\nexport function setupNestErrorHandler(app: MinimalNestJsApp, baseFilter: NestJsErrorFilter): void {\n // Sadly, NestInstrumentation has no requestHook, so we need to add the attributes here\n // We register this hook in this method, because if we register it in the integration `setup`,\n // it would always run even for users that are not even using Nest.js\n const client = getClient();\n if (client) {\n client.on('spanStart', span => {\n addNestSpanAttributes(span);\n });\n }\n\n app.useGlobalInterceptors({\n intercept(context, next) {\n if (getIsolationScope() === getDefaultIsolationScope()) {\n logger.warn('Isolation scope is still the default isolation scope, skipping setting transactionName.');\n return next.handle();\n }\n\n if (context.getType() === 'http') {\n const req = context.switchToHttp().getRequest();\n if (req.route) {\n getIsolationScope().setTransactionName(`${req.method?.toUpperCase() || 'GET'} ${req.route.path}`);\n }\n }\n\n return next.handle();\n },\n });\n\n const wrappedFilter = new Proxy(baseFilter, {\n get(target, prop, receiver) {\n if (prop === 'catch') {\n const originalCatch = Reflect.get(target, prop, receiver);\n\n return (exception: unknown, host: unknown) => {\n const status_code = (exception as { status?: number }).status;\n\n // don't report expected errors\n if (status_code !== undefined && status_code >= 400 && status_code < 500) {\n return originalCatch.apply(target, [exception, host]);\n }\n\n captureException(exception);\n return originalCatch.apply(target, [exception, host]);\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n\n app.useGlobalFilters(wrappedFilter);\n}\n\nfunction addNestSpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data || {};\n\n // this is one of: app_creation, request_context, handler\n const type = attributes['nestjs.type'];\n\n // If this is already set, or we have no nest.js span, no need to process again...\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.nestjs',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.nestjs`,\n });\n}\n","import { PgInstrumentation } from '@opentelemetry/instrumentation-pg';\nimport { defineIntegration } from '@sentry/core';\nimport type { IntegrationFn } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\n\nimport { addOriginToSpan } from '../../utils/addOriginToSpan';\n\nconst INTEGRATION_NAME = 'Postgres';\n\nexport const instrumentPostgres = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new PgInstrumentation({\n requireParentSpan: true,\n requestHook(span) {\n addOriginToSpan(span, 'auto.db.otel.postgres');\n },\n }),\n);\n\nconst _postgresIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPostgres();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Postgres integration\n *\n * Capture tracing data for pg.\n */\nexport const postgresIntegration = defineIntegration(_postgresIntegration);\n","import { HapiInstrumentation } from '@opentelemetry/instrumentation-hapi';\nimport {\n SDK_VERSION,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n captureException,\n defineIntegration,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn, Span } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport { generateInstrumentOnce } from '../../../otel/instrument';\nimport { ensureIsWrapped } from '../../../utils/ensureIsWrapped';\nimport type { Request, RequestEvent, Server } from './types';\n\nconst INTEGRATION_NAME = 'Hapi';\n\nexport const instrumentHapi = generateInstrumentOnce(INTEGRATION_NAME, () => new HapiInstrumentation());\n\nconst _hapiIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentHapi();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Hapi integration\n *\n * Capture tracing data for Hapi.\n * If you also want to capture errors, you need to call `setupHapiErrorHandler(server)` after you set up your server.\n */\nexport const hapiIntegration = defineIntegration(_hapiIntegration);\n\nfunction isErrorEvent(event: RequestEvent): event is RequestEvent {\n return event && (event as RequestEvent).error !== undefined;\n}\n\nfunction sendErrorToSentry(errorData: object): void {\n captureException(errorData, {\n mechanism: {\n type: 'hapi',\n handled: false,\n data: {\n function: 'hapiErrorPlugin',\n },\n },\n });\n}\n\nexport const hapiErrorPlugin = {\n name: 'SentryHapiErrorPlugin',\n version: SDK_VERSION,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n register: async function (serverArg: Record<any, any>) {\n const server = serverArg as unknown as Server;\n\n server.events.on({ name: 'request', channels: ['error'] }, (request: Request, event: RequestEvent) => {\n if (getIsolationScope() !== getDefaultIsolationScope()) {\n const route = request.route;\n if (route && route.path) {\n getIsolationScope().setTransactionName(`${route.method?.toUpperCase() || 'GET'} ${route.path}`);\n }\n } else {\n DEBUG_BUILD &&\n logger.warn('Isolation scope is still the default isolation scope - skipping setting transactionName');\n }\n\n if (isErrorEvent(event)) {\n sendErrorToSentry(event.error);\n }\n });\n },\n};\n\n/**\n * Add a Hapi plugin to capture errors to Sentry.\n */\nexport async function setupHapiErrorHandler(server: Server): Promise<void> {\n await server.register(hapiErrorPlugin);\n\n // Sadly, middleware spans do not go through `requestHook`, so we handle those here\n // We register this hook in this method, because if we register it in the integration `setup`,\n // it would always run even for users that are not even using hapi\n const client = getClient();\n if (client) {\n client.on('spanStart', span => {\n addHapiSpanAttributes(span);\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n ensureIsWrapped(server.register, 'hapi');\n}\n\nfunction addHapiSpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data || {};\n\n // this is one of: router, plugin, server.ext\n const type = attributes['hapi.type'];\n\n // If this is already set, or we have no Hapi span, no need to process again...\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.hapi',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.hapi`,\n });\n}\n","import { KoaInstrumentation } from '@opentelemetry/instrumentation-koa';\nimport { SEMATTRS_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n captureException,\n defineIntegration,\n getDefaultIsolationScope,\n getIsolationScope,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn, Span } from '@sentry/types';\nimport { logger } from '@sentry/utils';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { generateInstrumentOnce } from '../../otel/instrument';\nimport { ensureIsWrapped } from '../../utils/ensureIsWrapped';\n\nconst INTEGRATION_NAME = 'Koa';\n\nexport const instrumentKoa = generateInstrumentOnce(\n INTEGRATION_NAME,\n () =>\n new KoaInstrumentation({\n requestHook(span, info) {\n addKoaSpanAttributes(span);\n\n if (getIsolationScope() === getDefaultIsolationScope()) {\n DEBUG_BUILD && logger.warn('Isolation scope is default isolation scope - skipping setting transactionName');\n return;\n }\n const attributes = spanToJSON(span).data;\n const route = attributes && attributes[SEMATTRS_HTTP_ROUTE];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const method: string = info?.context?.request?.method?.toUpperCase() || 'GET';\n if (route) {\n getIsolationScope().setTransactionName(`${method} ${route}`);\n }\n },\n }),\n);\n\nconst _koaIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentKoa();\n },\n };\n}) satisfies IntegrationFn;\n\nexport const koaIntegration = defineIntegration(_koaIntegration);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const setupKoaErrorHandler = (app: { use: (arg0: (ctx: any, next: any) => Promise<void>) => void }): void => {\n app.use(async (ctx, next) => {\n try {\n await next();\n } catch (error) {\n captureException(error);\n throw error;\n }\n });\n\n ensureIsWrapped(app.use, 'koa');\n};\n\nfunction addKoaSpanAttributes(span: Span): void {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.http.otel.koa');\n\n const attributes = spanToJSON(span).data || {};\n\n // this is one of: middleware, router\n const type = attributes['koa.type'];\n\n if (type) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, `${type}.koa`);\n }\n\n // Also update the name\n const name = attributes['koa.name'];\n if (typeof name === 'string') {\n // Somehow, name is sometimes `''` for middleware spans\n // See: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2220\n span.updateName(name || '< unknown >');\n }\n}\n","import { ConnectInstrumentation } from '@opentelemetry/instrumentation-connect';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n captureException,\n defineIntegration,\n getClient,\n spanToJSON,\n} from '@sentry/core';\nimport type { IntegrationFn, Span } from '@sentry/types';\nimport { generateInstrumentOnce } from '../../otel/instrument';\nimport { ensureIsWrapped } from '../../utils/ensureIsWrapped';\n\ntype ConnectApp = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n use: (middleware: any) => void;\n};\n\nconst INTEGRATION_NAME = 'Connect';\n\nexport const instrumentConnect = generateInstrumentOnce(INTEGRATION_NAME, () => new ConnectInstrumentation());\n\nconst _connectIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentConnect();\n },\n };\n}) satisfies IntegrationFn;\n\nexport const connectIntegration = defineIntegration(_connectIntegration);\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction connectErrorMiddleware(err: any, req: any, res: any, next: any): void {\n captureException(err);\n next(err);\n}\n\nexport const setupConnectErrorHandler = (app: ConnectApp): void => {\n app.use(connectErrorMiddleware);\n\n // Sadly, ConnectInstrumentation has no requestHook, so we need to add the attributes here\n // We register this hook in this method, because if we register it in the integration `setup`,\n // it would always run even for users that are not even using connect\n const client = getClient();\n if (client) {\n client.on('spanStart', span => {\n addConnectSpanAttributes(span);\n });\n }\n\n ensureIsWrapped(app.use, 'connect');\n};\n\nfunction addConnectSpanAttributes(span: Span): void {\n const attributes = spanToJSON(span).data || {};\n\n // this is one of: middleware, request_handler\n const type = attributes['connect.type'];\n\n // If this is already set, or we have no connect span, no need to process again...\n if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || !type) {\n return;\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.connect',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${type}.connect`,\n });\n\n // Also update the name, we don't need to \"middleware - \" prefix\n const name = attributes['connect.name'];\n if (typeof name === 'string') {\n span.updateName(name);\n }\n}\n","import type { Integration } from '@sentry/types';\nimport { instrumentHttp } from '../http';\n\nimport { connectIntegration, instrumentConnect } from './connect';\nimport { expressIntegration, instrumentExpress } from './express';\nimport { fastifyIntegration, instrumentFastify } from './fastify';\nimport { graphqlIntegration, instrumentGraphql } from './graphql';\nimport { hapiIntegration, instrumentHapi } from './hapi';\nimport { instrumentKoa, koaIntegration } from './koa';\nimport { instrumentMongo, mongoIntegration } from './mongo';\nimport { instrumentMongoose, mongooseIntegration } from './mongoose';\nimport { instrumentMysql, mysqlIntegration } from './mysql';\nimport { instrumentMysql2, mysql2Integration } from './mysql2';\nimport { instrumentNest, nestIntegration } from './nest';\nimport { instrumentPostgres, postgresIntegration } from './postgres';\nimport { instrumentRedis, redisIntegration } from './redis';\n\n/**\n * With OTEL, all performance integrations will be added, as OTEL only initializes them when the patched package is actually required.\n */\nexport function getAutoPerformanceIntegrations(): Integration[] {\n return [\n expressIntegration(),\n fastifyIntegration(),\n graphqlIntegration(),\n mongoIntegration(),\n mongooseIntegration(),\n mysqlIntegration(),\n mysql2Integration(),\n redisIntegration(),\n postgresIntegration(),\n // For now, we do not include prisma by default because it has ESM issues\n // See https://github.com/prisma/prisma/issues/23410\n // TODO v8: Figure out a better solution for this, maybe only disable in ESM mode?\n // prismaIntegration(),\n nestIntegration(),\n hapiIntegration(),\n koaIntegration(),\n connectIntegration(),\n ];\n}\n\n/**\n * Get a list of methods to instrument OTEL, when preload instrumentation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getOpenTelemetryInstrumentationToPreload(): (((options?: any) => void) & { id: string })[] {\n return [\n instrumentHttp,\n instrumentExpress,\n instrumentConnect,\n instrumentFastify,\n instrumentHapi,\n instrumentKoa,\n instrumentNest,\n instrumentMongo,\n instrumentMongoose,\n instrumentMysql,\n instrumentMysql2,\n instrumentPostgres,\n instrumentHapi,\n instrumentGraphql,\n instrumentRedis,\n ];\n}\n","/**\n * This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7\n * With the following LICENSE:\n *\n * (The MIT License)\n *\n * Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:*\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.*\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint-disable @typescript-eslint/explicit-member-accessibility */\n/* eslint-disable @typescript-eslint/member-ordering */\n/* eslint-disable jsdoc/require-jsdoc */\nimport * as http from 'node:http';\nimport type * as net from 'node:net';\nimport type { Duplex } from 'node:stream';\nimport type * as tls from 'node:tls';\n\nexport * from './helpers';\n\ninterface HttpConnectOpts extends net.TcpNetConnectOpts {\n secureEndpoint: false;\n protocol?: string;\n}\n\ninterface HttpsConnectOpts extends tls.ConnectionOptions {\n secureEndpoint: true;\n protocol?: string;\n port: number;\n}\n\nexport type AgentConnectOpts = HttpConnectOpts | HttpsConnectOpts;\n\nconst INTERNAL = Symbol('AgentBaseInternalState');\n\ninterface InternalState {\n defaultPort?: number;\n protocol?: string;\n currentSocket?: Duplex;\n}\n\nexport abstract class Agent extends http.Agent {\n private [INTERNAL]: InternalState;\n\n // Set by `http.Agent` - missing from `@types/node`\n options!: Partial<net.TcpNetConnectOpts & tls.ConnectionOptions>;\n keepAlive!: boolean;\n\n constructor(opts?: http.AgentOptions) {\n super(opts);\n this[INTERNAL] = {};\n }\n\n abstract connect(\n req: http.ClientRequest,\n options: AgentConnectOpts,\n ): Promise<Duplex | http.Agent> | Duplex | http.Agent;\n\n /**\n * Determine whether this is an `http` or `https` request.\n */\n isSecureEndpoint(options?: AgentConnectOpts): boolean {\n if (options) {\n // First check the `secureEndpoint` property explicitly, since this\n // means that a parent `Agent` is \"passing through\" to this instance.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n if (typeof (options as any).secureEndpoint === 'boolean') {\n return options.secureEndpoint;\n }\n\n // If no explicit `secure` endpoint, check if `protocol` property is\n // set. This will usually be the case since using a full string URL\n // or `URL` instance should be the most common usage.\n if (typeof options.protocol === 'string') {\n return options.protocol === 'https:';\n }\n }\n\n // Finally, if no `protocol` property was set, then fall back to\n // checking the stack trace of the current call stack, and try to\n // detect the \"https\" module.\n const { stack } = new Error();\n if (typeof stack !== 'string') return false;\n return stack.split('\\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);\n }\n\n createSocket(req: http.ClientRequest, options: AgentConnectOpts, cb: (err: Error | null, s?: Duplex) => void): void {\n const connectOpts = {\n ...options,\n secureEndpoint: this.isSecureEndpoint(options),\n };\n Promise.resolve()\n .then(() => this.connect(req, connectOpts))\n .then(socket => {\n if (socket instanceof http.Agent) {\n // @ts-expect-error `addRequest()` isn't defined in `@types/node`\n return socket.addRequest(req, connectOpts);\n }\n this[INTERNAL].currentSocket = socket;\n // @ts-expect-error `createSocket()` isn't defined in `@types/node`\n super.createSocket(req, options, cb);\n }, cb);\n }\n\n createConnection(): Duplex {\n const socket = this[INTERNAL].currentSocket;\n this[INTERNAL].currentSocket = undefined;\n if (!socket) {\n throw new Error('No socket was returned in the `connect()` function');\n }\n return socket;\n }\n\n get defaultPort(): number {\n return this[INTERNAL].defaultPort ?? (this.protocol === 'https:' ? 443 : 80);\n }\n\n set defaultPort(v: number) {\n if (this[INTERNAL]) {\n this[INTERNAL].defaultPort = v;\n }\n }\n\n get protocol(): string {\n return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? 'https:' : 'http:');\n }\n\n set protocol(v: string) {\n if (this[INTERNAL]) {\n this[INTERNAL].protocol = v;\n }\n }\n}\n","/**\n * This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7\n * With the following LICENSE:\n *\n * (The MIT License)\n *\n * Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:*\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.*\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable jsdoc/require-jsdoc */\nimport type { IncomingHttpHeaders } from 'node:http';\nimport type { Readable } from 'node:stream';\nimport { logger } from '@sentry/utils';\n\nfunction debug(...args: unknown[]): void {\n logger.log('[https-proxy-agent:parse-proxy-response]', ...args);\n}\n\nexport interface ConnectResponse {\n statusCode: number;\n statusText: string;\n headers: IncomingHttpHeaders;\n}\n\nexport function parseProxyResponse(socket: Readable): Promise<{ connect: ConnectResponse; buffered: Buffer }> {\n return new Promise((resolve, reject) => {\n // we need to buffer any HTTP traffic that happens with the proxy before we get\n // the CONNECT response, so that if the response is anything other than an \"200\"\n // response code, then we can re-play the \"data\" events on the socket once the\n // HTTP parser is hooked up...\n let buffersLength = 0;\n const buffers: Buffer[] = [];\n\n function read() {\n const b = socket.read();\n if (b) ondata(b);\n else socket.once('readable', read);\n }\n\n function cleanup() {\n socket.removeListener('end', onend);\n socket.removeListener('error', onerror);\n socket.removeListener('readable', read);\n }\n\n function onend() {\n cleanup();\n debug('onend');\n reject(new Error('Proxy connection ended before receiving CONNECT response'));\n }\n\n function onerror(err: Error) {\n cleanup();\n debug('onerror %o', err);\n reject(err);\n }\n\n function ondata(b: Buffer) {\n buffers.push(b);\n buffersLength += b.length;\n\n const buffered = Buffer.concat(buffers, buffersLength);\n const endOfHeaders = buffered.indexOf('\\r\\n\\r\\n');\n\n if (endOfHeaders === -1) {\n // keep buffering\n debug('have not received end of HTTP headers yet...');\n read();\n return;\n }\n\n const headerParts = buffered.slice(0, endOfHeaders).toString('ascii').split('\\r\\n');\n const firstLine = headerParts.shift();\n if (!firstLine) {\n socket.destroy();\n return reject(new Error('No header received from proxy CONNECT response'));\n }\n const firstLineParts = firstLine.split(' ');\n const statusCode = +(firstLineParts[1] || 0);\n const statusText = firstLineParts.slice(2).join(' ');\n const headers: IncomingHttpHeaders = {};\n for (const header of headerParts) {\n if (!header) continue;\n const firstColon = header.indexOf(':');\n if (firstColon === -1) {\n socket.destroy();\n return reject(new Error(`Invalid header from proxy CONNECT response: \"${header}\"`));\n }\n const key = header.slice(0, firstColon).toLowerCase();\n const value = header.slice(firstColon + 1).trimStart();\n const current = headers[key];\n if (typeof current === 'string') {\n headers[key] = [current, value];\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n headers[key] = value;\n }\n }\n debug('got proxy server response: %o %o', firstLine, headers);\n cleanup();\n resolve({\n connect: {\n statusCode,\n statusText,\n headers,\n },\n buffered,\n });\n }\n\n socket.on('error', onerror);\n socket.on('end', onend);\n\n read();\n });\n}\n","/**\n * This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7\n * With the following LICENSE:\n *\n * (The MIT License)\n *\n * Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:*\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.*\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/* eslint-disable @typescript-eslint/explicit-member-accessibility */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport type * as http from 'node:http';\nimport type { OutgoingHttpHeaders } from 'node:http';\nimport * as net from 'node:net';\nimport * as tls from 'node:tls';\nimport { logger } from '@sentry/utils';\nimport { Agent } from './base';\nimport type { AgentConnectOpts } from './base';\nimport { parseProxyResponse } from './parse-proxy-response';\n\nfunction debug(...args: unknown[]): void {\n logger.log('[https-proxy-agent]', ...args);\n}\n\ntype Protocol<T> = T extends `${infer Protocol}:${infer _}` ? Protocol : never;\n\ntype ConnectOptsMap = {\n http: Omit<net.TcpNetConnectOpts, 'host' | 'port'>;\n https: Omit<tls.ConnectionOptions, 'host' | 'port'>;\n};\n\ntype ConnectOpts<T> = {\n [P in keyof ConnectOptsMap]: Protocol<T> extends P ? ConnectOptsMap[P] : never;\n}[keyof ConnectOptsMap];\n\nexport type HttpsProxyAgentOptions<T> = ConnectOpts<T> &\n http.AgentOptions & {\n headers?: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);\n };\n\n/**\n * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to\n * the specified \"HTTP(s) proxy server\" in order to proxy HTTPS requests.\n *\n * Outgoing HTTP requests are first tunneled through the proxy server using the\n * `CONNECT` HTTP request method to establish a connection to the proxy server,\n * and then the proxy server connects to the destination target and issues the\n * HTTP request from the proxy server.\n *\n * `https:` requests have their socket connection upgraded to TLS once\n * the connection to the proxy server has been established.\n */\nexport class HttpsProxyAgent<Uri extends string> extends Agent {\n static protocols = ['http', 'https'] as const;\n\n readonly proxy: URL;\n proxyHeaders: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);\n connectOpts: net.TcpNetConnectOpts & tls.ConnectionOptions;\n\n constructor(proxy: Uri | URL, opts?: HttpsProxyAgentOptions<Uri>) {\n super(opts);\n this.options = {};\n this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy;\n this.proxyHeaders = opts?.headers ?? {};\n debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);\n\n // Trim off the brackets from IPv6 addresses\n const host = (this.proxy.hostname || this.proxy.host).replace(/^\\[|\\]$/g, '');\n const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80;\n this.connectOpts = {\n // Attempt to negotiate http/1.1 for proxy servers that support http/2\n ALPNProtocols: ['http/1.1'],\n ...(opts ? omit(opts, 'headers') : null),\n host,\n port,\n };\n }\n\n /**\n * Called when the node-core HTTP client library is creating a\n * new HTTP request.\n */\n async connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise<net.Socket> {\n const { proxy } = this;\n\n if (!opts.host) {\n throw new TypeError('No \"host\" provided');\n }\n\n // Create a socket connection to the proxy server.\n let socket: net.Socket;\n if (proxy.protocol === 'https:') {\n debug('Creating `tls.Socket`: %o', this.connectOpts);\n const servername = this.connectOpts.servername || this.connectOpts.host;\n socket = tls.connect({\n ...this.connectOpts,\n servername: servername && net.isIP(servername) ? undefined : servername,\n });\n } else {\n debug('Creating `net.Socket`: %o', this.connectOpts);\n socket = net.connect(this.connectOpts);\n }\n\n const headers: OutgoingHttpHeaders =\n typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders };\n const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;\n let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\\r\\n`;\n\n // Inject the `Proxy-Authorization` header if necessary.\n if (proxy.username || proxy.password) {\n const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;\n headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;\n }\n\n headers.Host = `${host}:${opts.port}`;\n\n if (!headers['Proxy-Connection']) {\n headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close';\n }\n for (const name of Object.keys(headers)) {\n payload += `${name}: ${headers[name]}\\r\\n`;\n }\n\n const proxyResponsePromise = parseProxyResponse(socket);\n\n socket.write(`${payload}\\r\\n`);\n\n const { connect, buffered } = await proxyResponsePromise;\n req.emit('proxyConnect', connect);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Not EventEmitter in Node types\n this.emit('proxyConnect', connect, req);\n\n if (connect.statusCode === 200) {\n req.once('socket', resume);\n\n if (opts.secureEndpoint) {\n // The proxy is connecting to a TLS server, so upgrade\n // this socket connection to a TLS connection.\n debug('Upgrading socket connection to TLS');\n const servername = opts.servername || opts.host;\n return tls.connect({\n ...omit(opts, 'host', 'path', 'port'),\n socket,\n servername: net.isIP(servername) ? undefined : servername,\n });\n }\n\n return socket;\n }\n\n // Some other status code that's not 200... need to re-play the HTTP\n // header \"data\" events onto the socket once the HTTP machinery is\n // attached so that the node core `http` can parse and handle the\n // error status code.\n\n // Close the original socket, and a new \"fake\" socket is returned\n // instead, so that the proxy doesn't get the HTTP request\n // written to it (which may contain `Authorization` headers or other\n // sensitive data).\n //\n // See: https://hackerone.com/reports/541502\n socket.destroy();\n\n const fakeSocket = new net.Socket({ writable: false });\n fakeSocket.readable = true;\n\n // Need to wait for the \"socket\" event to re-play the \"data\" events.\n req.once('socket', (s: net.Socket) => {\n debug('Replaying proxy buffer for failed request');\n // Replay the \"buffered\" Buffer onto the fake `socket`, since at\n // this point the HTTP module machinery has been hooked up for\n // the user.\n s.push(buffered);\n s.push(null);\n });\n\n return fakeSocket;\n }\n}\n\nfunction resume(socket: net.Socket | tls.TLSSocket): void {\n socket.resume();\n}\n\nfunction omit<T extends object, K extends [...(keyof T)[]]>(\n obj: T,\n ...keys: K\n): {\n [K2 in Exclude<keyof T, K[number]>]: T[K2];\n} {\n const ret = {} as {\n [K in keyof typeof obj]: (typeof obj)[K];\n };\n let key: keyof typeof obj;\n for (key in obj) {\n if (!keys.includes(key)) {\n ret[key] = obj[key];\n }\n }\n return ret;\n}\n","import * as http from 'node:http';\nimport * as https from 'node:https';\nimport { Readable } from 'node:stream';\nimport { createGzip } from 'node:zlib';\nimport { createTransport, suppressTracing } from '@sentry/core';\nimport type {\n BaseTransportOptions,\n Transport,\n TransportMakeRequestResponse,\n TransportRequest,\n TransportRequestExecutor,\n} from '@sentry/types';\nimport { consoleSandbox } from '@sentry/utils';\nimport { HttpsProxyAgent } from '../proxy';\nimport type { HTTPModule } from './http-module';\n\nexport interface NodeTransportOptions extends BaseTransportOptions {\n /** Define custom headers */\n headers?: Record<string, string>;\n /** Set a proxy that should be used for outbound requests. */\n proxy?: string;\n /** HTTPS proxy CA certificates */\n caCerts?: string | Buffer | Array<string | Buffer>;\n /** Custom HTTP module. Defaults to the native 'http' and 'https' modules. */\n httpModule?: HTTPModule;\n /** Allow overriding connection keepAlive, defaults to false */\n keepAlive?: boolean;\n}\n\n// Estimated maximum size for reasonable standalone event\nconst GZIP_THRESHOLD = 1024 * 32;\n\n/**\n * Gets a stream from a Uint8Array or string\n * Readable.from is ideal but was added in node.js v12.3.0 and v10.17.0\n */\nfunction streamFromBody(body: Uint8Array | string): Readable {\n return new Readable({\n read() {\n this.push(body);\n this.push(null);\n },\n });\n}\n\n/**\n * Creates a Transport that uses native the native 'http' and 'https' modules to send events to Sentry.\n */\nexport function makeNodeTransport(options: NodeTransportOptions): Transport {\n let urlSegments: URL;\n\n try {\n urlSegments = new URL(options.url);\n } catch (e) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.',\n );\n });\n return createTransport(options, () => Promise.resolve({}));\n }\n\n const isHttps = urlSegments.protocol === 'https:';\n\n // Proxy prioritization: http => `options.proxy` | `process.env.http_proxy`\n // Proxy prioritization: https => `options.proxy` | `process.env.https_proxy` | `process.env.http_proxy`\n const proxy = applyNoProxyOption(\n urlSegments,\n options.proxy || (isHttps ? process.env.https_proxy : undefined) || process.env.http_proxy,\n );\n\n const nativeHttpModule = isHttps ? https : http;\n const keepAlive = options.keepAlive === undefined ? false : options.keepAlive;\n\n // TODO(v9): Evaluate if we can set keepAlive to true. This would involve testing for memory leaks in older node\n // versions(>= 8) as they had memory leaks when using it: #2555\n const agent = proxy\n ? (new HttpsProxyAgent(proxy) as http.Agent)\n : new nativeHttpModule.Agent({ keepAlive, maxSockets: 30, timeout: 2000 });\n\n // This ensures we do not generate any spans in OpenTelemetry for the transport\n return suppressTracing(() => {\n const requestExecutor = createRequestExecutor(options, options.httpModule ?? nativeHttpModule, agent);\n return createTransport(options, requestExecutor);\n });\n}\n\n/**\n * Honors the `no_proxy` env variable with the highest priority to allow for hosts exclusion.\n *\n * @param transportUrl The URL the transport intends to send events to.\n * @param proxy The client configured proxy.\n * @returns A proxy the transport should use.\n */\nfunction applyNoProxyOption(transportUrlSegments: URL, proxy: string | undefined): string | undefined {\n const { no_proxy } = process.env;\n\n const urlIsExemptFromProxy =\n no_proxy &&\n no_proxy\n .split(',')\n .some(\n exemption => transportUrlSegments.host.endsWith(exemption) || transportUrlSegments.hostname.endsWith(exemption),\n );\n\n if (urlIsExemptFromProxy) {\n return undefined;\n } else {\n return proxy;\n }\n}\n\n/**\n * Creates a RequestExecutor to be used with `createTransport`.\n */\nfunction createRequestExecutor(\n options: NodeTransportOptions,\n httpModule: HTTPModule,\n agent: http.Agent,\n): TransportRequestExecutor {\n const { hostname, pathname, port, protocol, search } = new URL(options.url);\n return function makeRequest(request: TransportRequest): Promise<TransportMakeRequestResponse> {\n return new Promise((resolve, reject) => {\n let body = streamFromBody(request.body);\n\n const headers: Record<string, string> = { ...options.headers };\n\n if (request.body.length > GZIP_THRESHOLD) {\n headers['content-encoding'] = 'gzip';\n body = body.pipe(createGzip());\n }\n\n const req = httpModule.request(\n {\n method: 'POST',\n agent,\n headers,\n hostname,\n path: `${pathname}${search}`,\n port,\n protocol,\n ca: options.caCerts,\n },\n res => {\n res.on('data', () => {\n // Drain socket\n });\n\n res.on('end', () => {\n // Drain socket\n });\n\n res.setEncoding('utf8');\n\n // \"Key-value pairs of header names and values. Header names are lower-cased.\"\n // https://nodejs.org/api/http.html#http_message_headers\n const retryAfterHeader = res.headers['retry-after'] ?? null;\n const rateLimitsHeader = res.headers['x-sentry-rate-limits'] ?? null;\n\n resolve({\n statusCode: res.statusCode,\n headers: {\n 'retry-after': retryAfterHeader,\n 'x-sentry-rate-limits': Array.isArray(rateLimitsHeader) ? rateLimitsHeader[0] || null : rateLimitsHeader,\n },\n });\n },\n );\n\n req.on('error', reject);\n body.pipe(req);\n });\n };\n}\n","import { posix, sep } from 'node:path';\nimport { dirname } from '@sentry/utils';\n\n/** normalizes Windows paths */\nfunction normalizeWindowsPath(path: string): string {\n return path\n .replace(/^[A-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/'); // replace all `\\` instances with `/`\n}\n\n/** Creates a function that gets the module name from a filename */\nexport function createGetModuleFromFilename(\n basePath: string = process.argv[1] ? dirname(process.argv[1]) : process.cwd(),\n isWindows: boolean = sep === '\\\\',\n): (filename: string | undefined) => string | undefined {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n\n return (filename: string | undefined) => {\n if (!filename) {\n return;\n }\n\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n\n // eslint-disable-next-line prefer-const\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n\n if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {\n file = file.slice(0, ext.length * -1);\n }\n\n if (!dir) {\n // No dirname whatsoever\n dir = '.';\n }\n\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) {\n return `${dir.slice(n + 14).replace(/\\//g, '.')}:${file}`;\n }\n\n // Let's see if it's a part of the main module\n // To be a part of main module, it has to share the same base\n if (dir.startsWith(normalizedBase)) {\n let moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n\n if (moduleName) {\n moduleName += ':';\n }\n moduleName += file;\n\n return moduleName;\n }\n\n return file;\n };\n}\n","// PUBLIC APIS\n\nimport type { StackParser } from '@sentry/types';\nimport { GLOBAL_OBJ, createStackParser, nodeStackLineParser } from '@sentry/utils';\nimport { createGetModuleFromFilename } from '../utils/module';\n\n/**\n * Returns a release dynamically from environment variables.\n */\n// eslint-disable-next-line complexity\nexport function getSentryRelease(fallback?: string): string | undefined {\n // Always read first as Sentry takes this as precedence\n if (process.env.SENTRY_RELEASE) {\n return process.env.SENTRY_RELEASE;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (GLOBAL_OBJ.SENTRY_RELEASE && GLOBAL_OBJ.SENTRY_RELEASE.id) {\n return GLOBAL_OBJ.SENTRY_RELEASE.id;\n }\n\n // This list is in approximate alpha order, separated into 3 categories:\n // 1. Git providers\n // 2. CI providers with specific environment variables (has the provider name in the variable name)\n // 3. CI providers with generic environment variables (checked for last to prevent possible false positives)\n\n const possibleReleaseNameOfGitProvider =\n // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables\n process.env['GITHUB_SHA'] ||\n // GitLab CI - https://docs.gitlab.com/ee/ci/variables/predefined_variables.html\n process.env['CI_MERGE_REQUEST_SOURCE_BRANCH_SHA'] ||\n process.env['CI_BUILD_REF'] ||\n process.env['CI_COMMIT_SHA'] ||\n // Bitbucket - https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/\n process.env['BITBUCKET_COMMIT'];\n\n const possibleReleaseNameOfCiProvidersWithSpecificEnvVar =\n // AppVeyor - https://www.appveyor.com/docs/environment-variables/\n process.env['APPVEYOR_PULL_REQUEST_HEAD_COMMIT'] ||\n process.env['APPVEYOR_REPO_COMMIT'] ||\n // AWS CodeBuild - https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html\n process.env['CODEBUILD_RESOLVED_SOURCE_VERSION'] ||\n // AWS Amplify - https://docs.aws.amazon.com/amplify/latest/userguide/environment-variables.html\n process.env['AWS_COMMIT_ID'] ||\n // Azure Pipelines - https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml\n process.env['BUILD_SOURCEVERSION'] ||\n // Bitrise - https://devcenter.bitrise.io/builds/available-environment-variables/\n process.env['GIT_CLONE_COMMIT_HASH'] ||\n // Buddy CI - https://buddy.works/docs/pipelines/environment-variables#default-environment-variables\n process.env['BUDDY_EXECUTION_REVISION'] ||\n // Builtkite - https://buildkite.com/docs/pipelines/environment-variables\n process.env['BUILDKITE_COMMIT'] ||\n // CircleCI - https://circleci.com/docs/variables/\n process.env['CIRCLE_SHA1'] ||\n // Cirrus CI - https://cirrus-ci.org/guide/writing-tasks/#environment-variables\n process.env['CIRRUS_CHANGE_IN_REPO'] ||\n // Codefresh - https://codefresh.io/docs/docs/codefresh-yaml/variables/\n process.env['CF_REVISION'] ||\n // Codemagic - https://docs.codemagic.io/yaml-basic-configuration/environment-variables/\n process.env['CM_COMMIT'] ||\n // Cloudflare Pages - https://developers.cloudflare.com/pages/platform/build-configuration/#environment-variables\n process.env['CF_PAGES_COMMIT_SHA'] ||\n // Drone - https://docs.drone.io/pipeline/environment/reference/\n process.env['DRONE_COMMIT_SHA'] ||\n // Flightcontrol - https://www.flightcontrol.dev/docs/guides/flightcontrol/environment-variables#built-in-environment-variables\n process.env['FC_GIT_COMMIT_SHA'] ||\n // Heroku #1 https://devcenter.heroku.com/articles/heroku-ci\n process.env['HEROKU_TEST_RUN_COMMIT_VERSION'] ||\n // Heroku #2 https://docs.sentry.io/product/integrations/deployment/heroku/#configure-releases\n process.env['HEROKU_SLUG_COMMIT'] ||\n // Render - https://render.com/docs/environment-variables\n process.env['RENDER_GIT_COMMIT'] ||\n // Semaphore CI - https://docs.semaphoreci.com/ci-cd-environment/environment-variables\n process.env['SEMAPHORE_GIT_SHA'] ||\n // TravisCI - https://docs.travis-ci.com/user/environment-variables/#default-environment-variables\n process.env['TRAVIS_PULL_REQUEST_SHA'] ||\n // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables\n process.env['VERCEL_GIT_COMMIT_SHA'] ||\n process.env['VERCEL_GITHUB_COMMIT_SHA'] ||\n process.env['VERCEL_GITLAB_COMMIT_SHA'] ||\n process.env['VERCEL_BITBUCKET_COMMIT_SHA'] ||\n // Zeit (now known as Vercel)\n process.env['ZEIT_GITHUB_COMMIT_SHA'] ||\n process.env['ZEIT_GITLAB_COMMIT_SHA'] ||\n process.env['ZEIT_BITBUCKET_COMMIT_SHA'];\n\n const possibleReleaseNameOfCiProvidersWithGenericEnvVar =\n // CloudBees CodeShip - https://docs.cloudbees.com/docs/cloudbees-codeship/latest/pro-builds-and-configuration/environment-variables\n process.env['CI_COMMIT_ID'] ||\n // Coolify - https://coolify.io/docs/knowledge-base/environment-variables\n process.env['SOURCE_COMMIT'] ||\n // Heroku #3 https://devcenter.heroku.com/changelog-items/630\n process.env['SOURCE_VERSION'] ||\n // Jenkins - https://plugins.jenkins.io/git/#environment-variables\n process.env['GIT_COMMIT'] ||\n // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata\n process.env['COMMIT_REF'] ||\n // TeamCity - https://www.jetbrains.com/help/teamcity/predefined-build-parameters.html\n process.env['BUILD_VCS_NUMBER'] ||\n // Woodpecker CI - https://woodpecker-ci.org/docs/usage/environment\n process.env['CI_COMMIT_SHA'];\n\n return (\n possibleReleaseNameOfGitProvider ||\n possibleReleaseNameOfCiProvidersWithSpecificEnvVar ||\n possibleReleaseNameOfCiProvidersWithGenericEnvVar ||\n fallback\n );\n}\n\n/** Node.js stack parser */\nexport const defaultStackParser: StackParser = createStackParser(nodeStackLineParser(createGetModuleFromFilename()));\n","import * as os from 'node:os';\nimport type { Tracer } from '@opentelemetry/api';\nimport { trace } from '@opentelemetry/api';\nimport type { BasicTracerProvider } from '@opentelemetry/sdk-trace-base';\nimport type { ServerRuntimeClientOptions } from '@sentry/core';\nimport { SDK_VERSION, ServerRuntimeClient, applySdkMetadata } from '@sentry/core';\nimport { logger } from '@sentry/utils';\nimport { isMainThread, threadId } from 'worker_threads';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { NodeClientOptions } from '../types';\n\nconst DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS = 60_000; // 60s was chosen arbitrarily\n\n/** A client for using Sentry with Node & OpenTelemetry. */\nexport class NodeClient extends ServerRuntimeClient<NodeClientOptions> {\n public traceProvider: BasicTracerProvider | undefined;\n private _tracer: Tracer | undefined;\n private _clientReportInterval: NodeJS.Timeout | undefined;\n private _clientReportOnExitFlushListener: (() => void) | undefined;\n\n public constructor(options: NodeClientOptions) {\n const clientOptions: ServerRuntimeClientOptions = {\n ...options,\n platform: 'node',\n runtime: { name: 'node', version: global.process.version },\n serverName: options.serverName || global.process.env.SENTRY_NAME || os.hostname(),\n };\n\n applySdkMetadata(clientOptions, 'node');\n\n logger.log(\n `Initializing Sentry: process: ${process.pid}, thread: ${isMainThread ? 'main' : `worker-${threadId}`}.`,\n );\n\n super(clientOptions);\n }\n\n /** Get the OTEL tracer. */\n public get tracer(): Tracer {\n if (this._tracer) {\n return this._tracer;\n }\n\n const name = '@sentry/node';\n const version = SDK_VERSION;\n const tracer = trace.getTracer(name, version);\n this._tracer = tracer;\n\n return tracer;\n }\n\n // Eslint ignore explanation: This is already documented in super.\n // eslint-disable-next-line jsdoc/require-jsdoc\n public async flush(timeout?: number): Promise<boolean> {\n const provider = this.traceProvider;\n const spanProcessor = provider?.activeSpanProcessor;\n\n if (spanProcessor) {\n await spanProcessor.forceFlush();\n }\n\n if (this.getOptions().sendClientReports) {\n this._flushOutcomes();\n }\n\n return super.flush(timeout);\n }\n\n // Eslint ignore explanation: This is already documented in super.\n // eslint-disable-next-line jsdoc/require-jsdoc\n public close(timeout?: number | undefined): PromiseLike<boolean> {\n if (this._clientReportInterval) {\n clearInterval(this._clientReportInterval);\n }\n\n if (this._clientReportOnExitFlushListener) {\n process.off('beforeExit', this._clientReportOnExitFlushListener);\n }\n\n return super.close(timeout);\n }\n\n /**\n * Will start tracking client reports for this client.\n *\n * NOTICE: This method will create an interval that is periodically called and attach a `process.on('beforeExit')`\n * hook. To clean up these resources, call `.close()` when you no longer intend to use the client. Not doing so will\n * result in a memory leak.\n */\n // The reason client reports need to be manually activated with this method instead of just enabling them in a\n // constructor, is that if users periodically and unboundedly create new clients, we will create more and more\n // intervals and beforeExit listeners, thus leaking memory. In these situations, users are required to call\n // `client.close()` in order to dispose of the acquired resources.\n // We assume that calling this method in Sentry.init() is a sensible default, because calling Sentry.init() over and\n // over again would also result in memory leaks.\n // Note: We have experimented with using `FinalizationRegisty` to clear the interval when the client is garbage\n // collected, but it did not work, because the cleanup function never got called.\n public startClientReportTracking(): void {\n const clientOptions = this.getOptions();\n if (clientOptions.sendClientReports) {\n this._clientReportOnExitFlushListener = () => {\n this._flushOutcomes();\n };\n\n this._clientReportInterval = setInterval(\n () => {\n DEBUG_BUILD && logger.log('Flushing client reports based on interval.');\n this._flushOutcomes();\n },\n clientOptions.clientReportFlushInterval ?? DEFAULT_CLIENT_REPORT_FLUSH_INTERVAL_MS,\n )\n // Unref is critical for not preventing the process from exiting because the interval is active.\n .unref();\n\n process.on('beforeExit', this._clientReportOnExitFlushListener);\n }\n }\n}\n","import {\n endSession,\n functionToStringIntegration,\n getClient,\n getCurrentScope,\n getIntegrationsToSetup,\n getIsolationScope,\n hasTracingEnabled,\n inboundFiltersIntegration,\n linkedErrorsIntegration,\n requestDataIntegration,\n startSession,\n} from '@sentry/core';\nimport {\n enhanceDscWithOpenTelemetryRootSpanName,\n openTelemetrySetupCheck,\n setOpenTelemetryContextAsyncContextStrategy,\n setupEventContextTrace,\n} from '@sentry/opentelemetry';\nimport type { Client, Integration, Options } from '@sentry/types';\nimport {\n consoleSandbox,\n dropUndefinedKeys,\n logger,\n propagationContextFromHeaders,\n stackParserFromStackParserOptions,\n} from '@sentry/utils';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { consoleIntegration } from '../integrations/console';\nimport { nodeContextIntegration } from '../integrations/context';\nimport { contextLinesIntegration } from '../integrations/contextlines';\n\nimport { httpIntegration } from '../integrations/http';\nimport { localVariablesIntegration } from '../integrations/local-variables';\nimport { modulesIntegration } from '../integrations/modules';\nimport { nativeNodeFetchIntegration } from '../integrations/node-fetch';\nimport { onUncaughtExceptionIntegration } from '../integrations/onuncaughtexception';\nimport { onUnhandledRejectionIntegration } from '../integrations/onunhandledrejection';\nimport { spotlightIntegration } from '../integrations/spotlight';\nimport { getAutoPerformanceIntegrations } from '../integrations/tracing';\nimport { makeNodeTransport } from '../transports';\nimport type { NodeClientOptions, NodeOptions } from '../types';\nimport { isCjs } from '../utils/commonjs';\nimport { defaultStackParser, getSentryRelease } from './api';\nimport { NodeClient } from './client';\nimport { initOpenTelemetry, maybeInitializeEsmLoader } from './initOtel';\n\nfunction getCjsOnlyIntegrations(): Integration[] {\n return isCjs() ? [modulesIntegration()] : [];\n}\n\n/**\n * Get default integrations, excluding performance.\n */\nexport function getDefaultIntegrationsWithoutPerformance(): Integration[] {\n return [\n // Common\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n linkedErrorsIntegration(),\n requestDataIntegration(),\n // Native Wrappers\n consoleIntegration(),\n httpIntegration(),\n nativeNodeFetchIntegration(),\n // Global Handlers\n onUncaughtExceptionIntegration(),\n onUnhandledRejectionIntegration(),\n // Event Info\n contextLinesIntegration(),\n localVariablesIntegration(),\n nodeContextIntegration(),\n ...getCjsOnlyIntegrations(),\n ];\n}\n\n/** Get the default integrations for the Node SDK. */\nexport function getDefaultIntegrations(options: Options): Integration[] {\n return [\n ...getDefaultIntegrationsWithoutPerformance(),\n // We only add performance integrations if tracing is enabled\n // Note that this means that without tracing enabled, e.g. `expressIntegration()` will not be added\n // This means that generally request isolation will work (because that is done by httpIntegration)\n // But `transactionName` will not be set automatically\n ...(shouldAddPerformanceIntegrations(options) ? getAutoPerformanceIntegrations() : []),\n ];\n}\n\nfunction shouldAddPerformanceIntegrations(options: Options): boolean {\n if (!hasTracingEnabled(options)) {\n return false;\n }\n\n // We want to ensure `tracesSampleRate` is not just undefined/null here\n // eslint-disable-next-line deprecation/deprecation\n return options.enableTracing || options.tracesSampleRate != null || 'tracesSampler' in options;\n}\n\n/**\n * Initialize Sentry for Node.\n */\nexport function init(options: NodeOptions | undefined = {}): NodeClient | undefined {\n return _init(options, getDefaultIntegrations);\n}\n\n/**\n * Initialize Sentry for Node, without any integrations added by default.\n */\nexport function initWithoutDefaultIntegrations(options: NodeOptions | undefined = {}): NodeClient {\n return _init(options, () => []);\n}\n\n/**\n * Initialize Sentry for Node, without performance instrumentation.\n */\nfunction _init(\n _options: NodeOptions | undefined = {},\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClient {\n const options = getClientOptions(_options, getDefaultIntegrationsImpl);\n\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n\n if (!isCjs() && options.registerEsmLoaderHooks !== false) {\n maybeInitializeEsmLoader(options.registerEsmLoaderHooks === true ? undefined : options.registerEsmLoaderHooks);\n }\n\n setOpenTelemetryContextAsyncContextStrategy();\n\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new NodeClient(options);\n // The client is on the current scope, from where it generally is inherited\n getCurrentScope().setClient(client);\n\n if (isEnabled(client)) {\n client.init();\n }\n\n logger.log(`Running in ${isCjs() ? 'CommonJS' : 'ESM'} mode.`);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\n\n client.startClientReportTracking();\n\n updateScopeFromEnvVariables();\n\n if (options.spotlight) {\n // force integrations to be setup even if no DSN was set\n // If they have already been added before, they will be ignored anyhow\n const integrations = client.getOptions().integrations;\n for (const integration of integrations) {\n client.addIntegration(integration);\n }\n client.addIntegration(\n spotlightIntegration({\n sidecarUrl: typeof options.spotlight === 'string' ? options.spotlight : undefined,\n }),\n );\n }\n\n // If users opt-out of this, they _have_ to set up OpenTelemetry themselves\n // There is no way to use this SDK without OpenTelemetry!\n if (!options.skipOpenTelemetrySetup) {\n initOpenTelemetry(client);\n validateOpenTelemetrySetup();\n }\n\n enhanceDscWithOpenTelemetryRootSpanName(client);\n setupEventContextTrace(client);\n\n return client;\n}\n\n/**\n * Validate that your OpenTelemetry setup is correct.\n */\nexport function validateOpenTelemetrySetup(): void {\n if (!DEBUG_BUILD) {\n return;\n }\n\n const setup = openTelemetrySetupCheck();\n\n const required = ['SentrySpanProcessor', 'SentryContextManager', 'SentryPropagator'] as const;\n for (const k of required) {\n if (!setup.includes(k)) {\n logger.error(\n `You have to set up the ${k}. Without this, the OpenTelemetry & Sentry integration will not work properly.`,\n );\n }\n }\n\n if (!setup.includes('SentrySampler')) {\n logger.warn(\n 'You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected.',\n );\n }\n}\n\nfunction getClientOptions(\n options: NodeOptions,\n getDefaultIntegrationsImpl: (options: Options) => Integration[],\n): NodeClientOptions {\n const release = getRelease(options.release);\n\n const autoSessionTracking =\n typeof release !== 'string'\n ? false\n : options.autoSessionTracking === undefined\n ? true\n : options.autoSessionTracking;\n\n const tracesSampleRate = getTracesSampleRate(options.tracesSampleRate);\n\n const baseOptions = dropUndefinedKeys({\n transport: makeNodeTransport,\n dsn: process.env.SENTRY_DSN,\n environment: process.env.SENTRY_ENVIRONMENT,\n sendClientReports: true,\n });\n\n const overwriteOptions = dropUndefinedKeys({\n release,\n autoSessionTracking,\n tracesSampleRate,\n });\n\n const mergedOptions = {\n ...baseOptions,\n ...options,\n ...overwriteOptions,\n };\n\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = getDefaultIntegrationsImpl(mergedOptions);\n }\n\n const clientOptions: NodeClientOptions = {\n ...mergedOptions,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup({\n defaultIntegrations: options.defaultIntegrations,\n integrations: options.integrations,\n }),\n };\n\n return clientOptions;\n}\n\nfunction getRelease(release: NodeOptions['release']): string | undefined {\n if (release !== undefined) {\n return release;\n }\n\n const detectedRelease = getSentryRelease();\n if (detectedRelease !== undefined) {\n return detectedRelease;\n }\n\n return undefined;\n}\n\nfunction getTracesSampleRate(tracesSampleRate: NodeOptions['tracesSampleRate']): number | undefined {\n if (tracesSampleRate !== undefined) {\n return tracesSampleRate;\n }\n\n const sampleRateFromEnv = process.env.SENTRY_TRACES_SAMPLE_RATE;\n if (!sampleRateFromEnv) {\n return undefined;\n }\n\n const parsed = parseFloat(sampleRateFromEnv);\n return isFinite(parsed) ? parsed : undefined;\n}\n\n/**\n * Update scope and propagation context based on environmental variables.\n *\n * See https://github.com/getsentry/rfcs/blob/main/text/0071-continue-trace-over-process-boundaries.md\n * for more details.\n */\nfunction updateScopeFromEnvVariables(): void {\n const sentryUseEnvironment = (process.env.SENTRY_USE_ENVIRONMENT || '').toLowerCase();\n if (!['false', 'n', 'no', 'off', '0'].includes(sentryUseEnvironment)) {\n const sentryTraceEnv = process.env.SENTRY_TRACE;\n const baggageEnv = process.env.SENTRY_BAGGAGE;\n const propagationContext = propagationContextFromHeaders(sentryTraceEnv, baggageEnv);\n getCurrentScope().setPropagationContext(propagationContext);\n }\n}\n\n/**\n * Enable automatic Session Tracking for the node process.\n */\nfunction startSessionTracking(): void {\n const client = getClient<NodeClient>();\n if (client && client.getOptions().autoSessionTracking) {\n client.initSessionFlusher();\n }\n\n startSession();\n\n // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because\n // The 'beforeExit' event is not emitted for conditions causing explicit termination,\n // such as calling process.exit() or uncaught exceptions.\n // Ref: https://nodejs.org/api/process.html#process_event_beforeexit\n process.on('beforeExit', () => {\n const session = getIsolationScope().getSession();\n\n // Only call endSession, if the Session exists on Scope and SessionStatus is not a\n // Terminal Status i.e. Exited or Crashed because\n // \"When a session is moved away from ok it must not be updated anymore.\"\n // Ref: https://develop.sentry.dev/sdk/sessions/\n if (session && session.status !== 'ok') {\n endSession();\n }\n });\n}\n\nfunction isEnabled(client: Client): boolean {\n return client.getOptions().enabled !== false && client.getTransport() !== undefined;\n}\n","import { stdin } from 'node:process';\nimport React from 'react';\nimport { isType } from 'variant';\nimport { createFsCache, CacheState } from '@wix/cli-fs-cache';\nimport { render, renderSync } from '@wix/cli-ui-kit';\nimport { I18nProvider } from '@wix/cli-i18n';\nimport { UserFeedbackForm } from './components/UserFeedback/Form.js';\nimport { UserFeedbackFallback } from './components/UserFeedback/Fallback.js';\nimport { ReportErrorResult } from './error-reporter.js';\nimport type { ErrorReporter } from './error-reporter.js';\nimport messages from './messages.json' with { type: 'json' };\n\ninterface Options {\n cachePath: string | undefined;\n errorReporter: ErrorReporter;\n reportResult: ReportErrorResult;\n}\n\nexport async function collectUserFeedback({\n cachePath,\n reportResult,\n errorReporter,\n}: Options) {\n if (\n !stdin.isTTY ||\n !cachePath ||\n !isType(reportResult, ReportErrorResult.Reported)\n ) {\n return;\n }\n\n const fsCache = createFsCache({\n filePath: cachePath,\n ttlInHours: 1,\n });\n const cacheState = await fsCache.get();\n\n if (isType(cacheState, CacheState.Exists)) {\n return;\n }\n\n const user = errorReporter.getUser();\n\n if (user) {\n await render(\n <I18nProvider messages={messages}>\n <UserFeedbackForm\n onSubmit={({ feedback }) => {\n void errorReporter.reportUserFeedback({\n userId: user.id,\n eventId: reportResult.eventId,\n feedback,\n });\n }}\n />\n </I18nProvider>\n );\n } else {\n renderSync(\n <I18nProvider messages={messages}>\n <UserFeedbackFallback />\n </I18nProvider>\n );\n }\n\n await fsCache.set({ reported: true });\n}\n","import { writeJson, readJson, pathExists } from '@wix/cli-fs';\nimport { CliError, CliErrorCode } from '@wix/cli-error';\nimport { getTestOverrides } from '@wix/cli-test-overrides';\nimport { join } from 'node:path';\nimport type { VariantOf } from 'variant';\nimport { fields, variant } from 'variant';\nimport { z } from 'zod';\n\nexport const CacheState = variant({\n Exists: fields<{ data: unknown }>(),\n NotExists: {},\n});\n\nexport type CacheState = VariantOf<typeof CacheState>;\n\nconst CacheData = z.object({\n data: z.unknown(),\n createdAt: z.number(),\n});\n\ntype CacheData = z.infer<typeof CacheData>;\n\ninterface CliCacheOptions {\n filePath: string;\n ttlInHours?: number;\n}\n\nconst isFileExpired = (createdAt: number, ttlInHours: number) => {\n return Date.now() - createdAt.valueOf() > ttlInHours * 60 * 60 * 1000;\n};\n\nexport function getFsCacheFilePath(dirPath: string, fileName: string) {\n const testOverrides = getTestOverrides();\n\n if (testOverrides.fsCacheDir) {\n return join(testOverrides.fsCacheDir, fileName);\n }\n\n return join(dirPath, fileName);\n}\n\nexport function createFsCache({\n filePath,\n ttlInHours = 24 * 7,\n}: CliCacheOptions) {\n const get = async (): Promise<CacheState> => {\n try {\n const isCacheExists = await pathExists(filePath);\n\n if (isCacheExists) {\n const cacheData = CacheData.parse(await readJson(filePath));\n\n if (!isFileExpired(cacheData.createdAt, ttlInHours)) {\n return CacheState.Exists({ data: cacheData.data });\n }\n }\n\n return CacheState.NotExists();\n } catch (e) {\n throw new CliError({\n code: CliErrorCode.FailedToReadCache({ path: filePath }),\n cause: e,\n });\n }\n };\n\n const set = async (data: unknown): Promise<CacheState> => {\n try {\n await writeJson(filePath, {\n data,\n createdAt: Date.now(),\n });\n return CacheState.Exists({ data });\n } catch (e) {\n throw new CliError({\n code: CliErrorCode.FailedToWriteCache({ path: filePath }),\n cause: e,\n });\n }\n };\n\n return {\n get,\n set,\n };\n}\n","import React, { useState, useCallback } from 'react';\nimport type { FC } from 'react';\nimport { useTranslation } from '@wix/cli-i18n';\nimport { Text, ConfirmInput, TextInput, Box } from '@wix/cli-ui-kit';\nimport { ContactUs } from './ContactUs.js';\n\ninterface Props {\n onSubmit: ({ feedback }: { feedback: string }) => void;\n}\n\nexport const UserFeedbackForm: FC<Props> = ({ onSubmit }) => {\n const { t } = useTranslation();\n const [isSubmitted, setIsSubmitted] = useState(false);\n const [consent, setConsent] = useState<boolean>();\n\n const handleConsentSubmit = useCallback((value: boolean) => {\n setConsent(value);\n if (!value) {\n setIsSubmitted(true);\n }\n }, []);\n\n const handleSubmit = useCallback(\n (feedback: string) => {\n setIsSubmitted(true);\n onSubmit({ feedback });\n },\n [onSubmit]\n );\n\n return (\n <>\n <Box flexDirection=\"column\" marginTop={1} marginBottom={1}>\n <Text>{t('user_feedback.title')}</Text>\n <Text skin=\"secondary\">{t('user_feedback.subtitle')}</Text>\n </Box>\n <ConfirmInput\n initialValue={false}\n label={t('user_feedback.consent.label')}\n onSubmit={handleConsentSubmit}\n />\n {consent === true && (\n <TextInput\n label={t('user_feedback.comments.label')}\n onSubmit={handleSubmit}\n />\n )}\n {isSubmitted && (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text>\n {consent\n ? t('user_feedback.submitted')\n : t('user_feedback.declined')}\n </Text>\n <ContactUs />\n </Box>\n )}\n </>\n );\n};\n","import React from 'react';\nimport type { FC } from 'react';\nimport { Trans } from '@wix/cli-i18n';\nimport { Link } from '@wix/cli-ui-kit';\n\nexport const ContactUs: FC = () => (\n <Trans\n i18nKey=\"user_feedback.contact_us\"\n components={[<Link url=\"https://discord.gg/wixstudio\" />]}\n />\n);\n","import React from 'react';\nimport type { FC } from 'react';\nimport { Box } from '@wix/cli-ui-kit';\nimport { ContactUs } from './ContactUs.js';\n\nexport const UserFeedbackFallback: FC = () => {\n return (\n <Box flexDirection=\"column\" marginTop={1}>\n <ContactUs />\n </Box>\n );\n};\n","import type { FC } from 'react';\nimport React from 'react';\nimport VError from 'verror';\nimport { Text, Box } from '@wix/cli-ui-kit';\nimport type { IHttpError } from '@wix/http-client';\nimport { extractHttpError } from '@wix/cli-http-client';\n\ninterface RawErrorViewerProps {\n error: unknown;\n occurredAt: Date;\n}\n\nexport const RawErrorViewer: FC<RawErrorViewerProps> = (props) => {\n const { error, occurredAt } = props;\n\n return (\n <Box flexDirection=\"column\" paddingTop={1}>\n <Text>----- CLI crash report at {occurredAt.toISOString()}</Text>\n {error instanceof Error ? (\n <FullErrorDetails error={error} />\n ) : (\n <Text>{JSON.stringify(error)}</Text>\n )}\n </Box>\n );\n};\n\nconst FullErrorDetails: FC<{ error: Error }> = ({ error }) => {\n const httpError = extractHttpError(error);\n const httpErrorInfo = httpError ? getSafeHttpErrorInfo(httpError) : null;\n\n return (\n <>\n <Text>Error Trace</Text>\n <Text>{VError.fullStack(error)}</Text>\n <Text>Error Info</Text>\n <Text>{toPrettyJson(VError.info(error))}</Text>\n {httpErrorInfo ? (\n <Box flexDirection=\"column\">\n <Text>Request Info</Text>\n <Text>{toPrettyJson(httpErrorInfo)}</Text>\n </Box>\n ) : null}\n </>\n );\n};\n\nfunction getSafeHttpErrorInfo(httpError: IHttpError) {\n return {\n request: {\n baseURL: httpError.config.baseURL,\n url: httpError.config.url,\n method: httpError.config.method,\n data: httpError.config.data,\n },\n response: {\n code: httpError.code,\n message: httpError.message,\n status: httpError.response?.status,\n headers: getSafeHeaders(httpError.response?.headers),\n data: httpError.response?.data,\n },\n };\n}\n\nconst SAFE_HEADERS = new Set(['x-wix-request-id']);\n\nfunction getSafeHeaders(headers?: Record<string, unknown>) {\n if (headers) {\n return Object.keys(headers).reduce<Record<string, unknown>>((acc, curr) => {\n if (SAFE_HEADERS.has(curr.toLowerCase())) {\n acc[curr] = headers[curr];\n }\n return acc;\n }, {});\n }\n return headers;\n}\n\nfunction toPrettyJson(data: unknown) {\n return JSON.stringify(data, null, 2);\n}\n","import React, { createContext, useContext } from 'react';\nimport type { FC, ReactNode } from 'react';\nimport type { ErrorReporter } from './error-reporter.js';\n\nconst ErrorReporterContext = createContext<ErrorReporter | null>(null);\n\ninterface Props {\n value: ErrorReporter;\n children: ReactNode;\n}\n\nexport const ErrorReporterProvider: FC<Props> = (props) => (\n <ErrorReporterContext.Provider {...props} />\n);\n\nexport const useErrorReporter = (): ErrorReporter => {\n const context = useContext(ErrorReporterContext);\n if (context == null) {\n throw new Error(\n 'useErrorReporter() cannot be used without an <ErrorReporterProvider>'\n );\n }\n return context;\n};\n","import { useMemo } from 'react';\n\nexport function useColoredVerificationUri(verificationUri: string) {\n return useMemo(() => {\n const coloredUri = new URL(verificationUri);\n coloredUri.searchParams.set('color', 'developer');\n coloredUri.searchParams.set('studio', 'true');\n const signupUri = new URL('https://users.wix.com/login/signup/password');\n signupUri.searchParams.set('redirectTo', coloredUri.href);\n return {\n coloredVerificationUri: coloredUri.toString(),\n signupUri: signupUri.toString(),\n };\n }, [verificationUri]);\n}\n","import React from 'react';\nimport type { FC, ReactNode } from 'react';\nimport { useExit } from '@wix/cli-ui-kit';\nimport { AuthContext } from '../context.js';\nimport type { UserInfo } from '../schemas.js';\nimport { accountAuthStrategy } from '../auth-strategies/index.js';\nimport { EnsureLoggedIn } from '../components/EnsureLoggedIn.js';\n\ninterface Props {\n children: ReactNode;\n onError?: (error: unknown) => void;\n onLogin?: (userInfo: UserInfo) => void;\n}\n\nexport const AccountAuthProvider: FC<Props> = ({\n children,\n onError,\n onLogin,\n}) => {\n const exit = useExit();\n\n return (\n <EnsureLoggedIn\n authStrategy={accountAuthStrategy}\n onLogin={({ userInfo }) => onLogin?.(userInfo)}\n onError={onError ?? exit}\n >\n {({ getAccessToken, getRequestHeaders, userInfo }) => (\n <AuthContext.Provider\n value={{ getAccessToken, getRequestHeaders, userInfo }}\n >\n {children}\n </AuthContext.Provider>\n )}\n </EnsureLoggedIn>\n );\n};\n","import React from 'react';\nimport type { ReactNode, FC } from 'react';\nimport { match } from 'variant';\nimport { useAsync, Spinner } from '@wix/cli-ui-kit';\nimport { I18nProvider } from '@wix/cli-i18n';\nimport type {\n AuthStrategy,\n AuthStrategyState,\n} from '../auth-strategies/index.js';\nimport { Login } from './Login.js';\nimport { WarnLegacyAuthData } from './WarnLegacyAuthData.js';\nimport messages from '../messages.json' with { type: 'json' };\n\ninterface Props {\n authStrategy: AuthStrategy;\n onLogin: (data: AuthStrategyState) => void;\n onError: (error: unknown) => void;\n children: (data: AuthStrategyState) => ReactNode;\n}\n\nexport const EnsureLoggedIn: FC<Props> = ({\n authStrategy: { login, isLoggedIn },\n onLogin,\n onError,\n children,\n}) => {\n const { status, merge: updateAccountAuth } = useAsync(isLoggedIn, [], {\n onSuccess: (result) => {\n if (result) {\n onLogin(result);\n }\n },\n onError,\n });\n\n return match(status, {\n Loading: () => <Spinner />,\n Error: () => null,\n Success: ({ result: accountAuth }) => {\n if (accountAuth == null) {\n return (\n <I18nProvider messages={messages}>\n <WarnLegacyAuthData>\n <Login\n loginFn={login}\n onLogin={(data) => {\n updateAccountAuth({ result: data });\n onLogin(data);\n }}\n onError={onError}\n />\n </WarnLegacyAuthData>\n </I18nProvider>\n );\n }\n\n return children(accountAuth);\n },\n });\n};\n","import React from 'react';\nimport type { FC, ReactNode } from 'react';\nimport { match } from 'variant';\nimport { Box, useAsync } from '@wix/cli-ui-kit';\nimport { Trans } from '@wix/cli-i18n';\nimport { hasLegacyAuthData } from '../auth-data.js';\n\ninterface Props {\n children: ReactNode;\n}\n\nexport const WarnLegacyAuthData: FC<Props> = ({ children }) => {\n const { status } = useAsync(hasLegacyAuthData, [], { onError: () => {} });\n\n return match(status, {\n Error: () => null,\n Loading: () => null,\n Success: ({ result }) => (\n <>\n {result && (\n <Box marginBottom={1}>\n <Trans i18nKey=\"login.legacy_auth_notice\" />\n </Box>\n )}\n {children}\n </>\n ),\n });\n};\n","import React, { useMemo } from 'react';\nimport type { FC, ReactNode } from 'react';\nimport { useExit } from '@wix/cli-ui-kit';\nimport type { UserInfo } from '../schemas.js';\nimport { AuthContext } from '../context.js';\nimport { EnsureLoggedIn } from '../components/EnsureLoggedIn.js';\nimport { createSiteAuthStrategy } from '../auth-strategies/index.js';\n\ninterface Props {\n siteId: string;\n onError?: (error: unknown) => void;\n onLogin?: (userInfo: UserInfo) => void;\n children: ReactNode;\n}\n\nexport const SiteAuthProvider: FC<Props> = ({\n children,\n siteId,\n onError,\n onLogin,\n}) => {\n const exit = useExit();\n const authStrategy = useMemo(() => createSiteAuthStrategy(siteId), [siteId]);\n\n return (\n <EnsureLoggedIn\n authStrategy={authStrategy}\n onLogin={({ userInfo }) => onLogin?.(userInfo)}\n onError={onError ?? exit}\n >\n {({ getAccessToken, getRequestHeaders, userInfo }) => (\n <AuthContext.Provider\n value={{\n getAccessToken,\n getRequestHeaders,\n userInfo,\n }}\n >\n {children}\n </AuthContext.Provider>\n )}\n </EnsureLoggedIn>\n );\n};\n","import { useMemo } from 'react';\nimport { useAsync, useExit } from '@wix/cli-ui-kit';\nimport type { Headers } from '@wix/cli-http-client';\nimport { isType } from 'variant';\nimport type { UserInfo } from '../schemas.js';\nimport { createSiteAuthStrategy } from '../auth-strategies/index.js';\nimport type { AuthStrategyState } from '../auth-strategies/index.js';\n\ninterface UseSiteAuthOptions {\n siteId: string;\n onError?: (error: unknown) => void;\n onLogin?: (userInfo: UserInfo) => void;\n}\n\ntype UseSiteAuthResult =\n | {\n isLoading: boolean;\n isError: boolean;\n isAuthenticated: false;\n authState: null;\n error?: unknown;\n }\n | {\n isLoading: false;\n isError: false;\n isAuthenticated: true;\n authState: AuthStrategyState;\n getAccessToken: () => Promise<string>;\n getRequestHeaders?: () => Headers;\n userInfo: UserInfo;\n };\n\nexport const useSiteAuth = ({\n siteId,\n onError,\n onLogin,\n}: UseSiteAuthOptions): UseSiteAuthResult => {\n const exit = useExit();\n const authStrategy = useMemo(() => createSiteAuthStrategy(siteId), [siteId]);\n\n const { status } = useAsync(authStrategy.isLoggedIn, [], {\n onSuccess: (result) => {\n if (result) {\n onLogin?.(result.userInfo);\n }\n },\n onError: onError ?? exit,\n });\n\n if (isType(status, 'Loading')) {\n return {\n isLoading: true,\n isError: false,\n isAuthenticated: false,\n authState: null,\n };\n }\n\n if (isType(status, 'Error')) {\n return {\n isLoading: false,\n isError: true,\n isAuthenticated: false,\n authState: null,\n error: status.error,\n };\n }\n\n const authState = status.result;\n if (authState == null) {\n return {\n isLoading: false,\n isError: false,\n isAuthenticated: false,\n authState: null,\n };\n }\n\n return {\n isLoading: false,\n isError: false,\n isAuthenticated: true,\n authState,\n getAccessToken: authState.getAccessToken,\n getRequestHeaders: authState.getRequestHeaders,\n userInfo: authState.userInfo,\n };\n};\n","import React, { useEffect } from 'react';\nimport type { FC } from 'react';\nimport { render, useExit } from '@wix/cli-ui-kit';\nimport { BiProvider } from '@wix/cli-telemetry-react';\nimport type { BiLogger } from '@wix/cli-telemetry';\nimport { ErrorReporterProvider } from '@wix/cli-error-reporting';\nimport type { ErrorReporter } from '@wix/cli-error-reporting';\nimport type { AuthState } from './context.js';\nimport { SiteAuthProvider } from './providers/SiteAuthProvider.js';\nimport { useAuth } from './useAuth.js';\n\nconst Wrapper: FC<{ onReady: (data: AuthState) => void }> = ({ onReady }) => {\n const exit = useExit();\n const auth = useAuth();\n\n useEffect(() => {\n onReady(auth);\n exit();\n }, [exit, auth, onReady]);\n\n return null;\n};\n\n/**\n * @deprecated migrate to ink & use `SiteAuthProvider` directly\n */\nexport function authenticateWithSiteId(\n siteId: string,\n biLogger: BiLogger,\n errorReporter: ErrorReporter\n): Promise<AuthState> {\n return new Promise<AuthState>((resolve, reject) => {\n render(\n <ErrorReporterProvider value={errorReporter}>\n <BiProvider value={biLogger}>\n <SiteAuthProvider siteId={siteId}>\n <Wrapper onReady={resolve} />\n </SiteAuthProvider>\n </BiProvider>\n </ErrorReporterProvider>\n ).catch((error: unknown) => reject(error));\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,kFAAAA,SAAA;AAAA;AAAA;AAAA,aAAS,eAAe,UAAU,SAAS;AAEzC,UAAI,OAAO,YAAY,WAAW;AAChC,kBAAU,EAAE,SAAS,QAAQ;AAAA,MAC/B;AAEA,WAAK,oBAAoB,KAAK,MAAM,KAAK,UAAU,QAAQ,CAAC;AAC5D,WAAK,YAAY;AACjB,WAAK,WAAW,WAAW,CAAC;AAC5B,WAAK,gBAAgB,WAAW,QAAQ,gBAAgB;AACxD,WAAK,MAAM;AACX,WAAK,UAAU,CAAC;AAChB,WAAK,YAAY;AACjB,WAAK,oBAAoB;AACzB,WAAK,sBAAsB;AAC3B,WAAK,WAAW;AAChB,WAAK,kBAAkB;AACvB,W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C,iBAAiC;AAWjC,IAAM,UAAsD,CAAC,EAAE,QAAQ,MAAM;AAC3E,QAAM,OAAO,QAAQ;AACrB,QAAM,OAAO,QAAQ;AAErB,gCAAU,MAAM;AACd,YAAQ,IAAI;AACZ,SAAK;AAAA,EACP,GAAG,CAAC,MAAM,MAAM,OAAO,CAAC;AAExB,SAAO;AACT;AAKO,SAAS,uBACd,QACA,UACA,eACoB;AACpB,SAAO,IAAI,QAAmB,CAACC,UAAS,WAAW;AACjD;AAAA,MACE,+BAAAC,QAAA,cAAC,yBAAsB,OAAO,iBAC5B,+BAAAA,QAAA,cAAC,cAAW,OAAO,YACjB,+BAAAA,QAAA,cAAC,oBAAiB,UAChB,+BAAAA,QAAA,cAAC,WAAQ,SAASD,UAAS,CAC7B,CACF,CACF;AAAA,IACF,EAAE,MAAM,CAAC,UAAmB,OAAO,KAAK,CAAC;AAAA,EAC3C,CAAC;AACH;;;A3JxCO,IAAM,EAAE,YAAY,oBAAoB,IAAI;","names":["module","original","require_retry","module","suppressTracing","context","_a","W3CBaggagePropagator","context","AnchoredClock","__read","_a","TracesSamplerValues","init_environment","bytes","RandomIdGenerator","init_esm","init_environment","seconds","ExportResultCode","CompositePropagator","_a","context","__values","TraceState","match","VERSION","W3CTraceContextPropagator","context","context","RPCType","AlwaysOffSampler","AlwaysOnSampler","ParentBasedSampler","_a","context","TraceIdRatioBasedSampler","context","objectToString","TimeoutError","__values","Deferred","resolve","BindOnceFuture","_a","__read","resolve","suppressTracing","esm_exports","TimeoutError","suppressTracing","init_esm","module","module","debug","module","debug","token","module","module","module","debug","release","match","module","module","module","module","release","module","module","module","module","module","module","module","module","module","module","module","module","module","module","module","module","module","module","module","match","module","module","debug","module","debug","module","satisfies","module","module","module","module","require_valid","module","module","satisfies","module","module","module","module","satisfies","module","satisfies","require_semver","module","satisfies","AttributeNames","getAbsoluteUrl","path","constant","hostname","_a","SeverityNumber","NoopLogger","NoopLoggerProvider","_globalThis","init_globalThis","init_node","init_globalThis","init_platform","init_node","init_platform","_globalThis","LogsAPI","_a","init_esm","_a","init_esm","module","isFunction","logger","shimmer","wrap","massWrap","unwrap","massUnwrap","init_esm","InstrumentationAbstract","_a","module","os","module","stack","module","posix","module","path","getNodeModulesDirs","module","path","paths","opts","module","concatty","slicy","Empty","module","module","module","module","module","fs","path","maybeRealpath","defaultReadPackage","readFile","getPackageCandidates","resolve","err","init","basedir","pkg","x","callback","cb","exts","isdir","onfile","require_core","module","require_core","module","module","module","fs","path","maybeRealpathSync","defaultReadPackageSync","readFileSync","getPackageCandidates","x","m","n","module","module","path","module","module","path","resolve","debug","Hook","normalize","exports","ModuleNameTrieNode","ModuleNameTrie","__values","_a","__spreadArray","__read","path","RequireInTheMiddleSingleton","__values","_a","module","path","fileURLToPath","Hook","_a","isWrapped","init_utils","path","import_require_in_the_middle","init_instrumentation","init_utils","__extends","InstrumentationBase","isWrapped","module","_a","__values","module_2","HookRequire","HookImport","normalize","init_node","init_instrumentation","init_platform","init_node","InstrumentationNodeModuleDefinition","init_platform","InstrumentationNodeModuleFile","normalize","init_types","esm_exports","isWrapped","init_esm","init_platform","init_types","init_utils","HttpInstrumentation","_a","hostname","duration","ExpressLayerType","AttributeNames","constant","_a","ExpressInstrumentation","path","isError","_a","AttributeNames","FastifyTypes","FastifyNames","startSpan","_a","FastifyInstrumentation","_a","AllowedOperationTypes","TokenKind","SpanNames","AttributeNames","isObjectLike","path","fieldNode","_a","fields","GraphQLInstrumentation","module","_a","MongodbCommandType","MongoDBInstrumentation","_a","MongodbCommandType","MongooseInstrumentation","module","_a","require_types","AttributeNames","MySQLInstrumentation","fields","format","_a","MySQL2Instrumentation","format","err","fields","_a","IORedisInstrumentation","module","result","_a","client","diag","_a","RedisInstrumentation","_a","AttributeNames","NestType","NestInstrumentation","module","_a","AttributeNames","SpanNames","_a","PgInstrumentation","module","connect","result","resolve","AttributeNames","_a","HapiInstrumentation","module","_a","KoaLayerType","AttributeNames","context","_a","KoaInstrumentation","module","_a","path","context","AttributeNames","ConnectTypes","ConnectNames","ConnectInstrumentation","import_variant","resolve","retry","path","path","path","isObject","resolvePath","flatten","ConverterType","payload","seconds","payload","_a","payload","_a","payload","_a","import_http_client","client","createHttpClientOriginal","import_http_client","VError","token","payload","token","import_variant","token","payload","resolve","import_variant","AbortError","resolve","resolve","deviceCode","import_variant","payload","deviceCode","import_variant","import_react","context","import_react","import_react","React","context","import_variant","token","React","import_react","import_variant","import_react","process","Buffer","fs","process","fs","fs","fs","process","fs","promisify","process","execFile","process","match","process","promisify","execFile","execFileAsync","promisify","execFile","execFileAsync","match","execFileAsync","promisify","execFile","defaultBrowser","process","process","fs","defaultBrowser","Buffer","resolve","import_http_client","open","open","import_react","process","import_react","import_verror","dirname","VError","dirname","React","context","ci","import_react","import_react","import_variant","match","import_react","React","import_react","messages_default","React","messages_default","import_react","React","React","path","import_variant","context","_optionalChain","hostname","path","client","_addRequestBreadcrumb","getBreadcrumbData","path","INTEGRATION_NAME","client","promisify","INTEGRATION_NAME","uptime","match","resolve","execFile","join","INTEGRATION_NAME","path","resolve","range","client","INTEGRATION_NAME","client","seconds","INTEGRATION_NAME","path","dirname","join","readFileSync","client","error","INTEGRATION_NAME","client","INTEGRATION_NAME","client","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","arg","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","INTEGRATION_NAME","Agent","resolve","debug","Agent","payload","connect","http","hostname","resolve","path","sep","import_verror","VError","release","client","context","import_react","import_variant","import_variant","join","join","import_react","import_react","React","React","import_react","React","React","messages_default","import_react","import_verror","React","VError","React","process","import_react","React","context","import_react","reportError","React","React","import_react","import_react","import_variant","import_react","import_variant","React","React","React","import_react","React","import_react","import_variant","import_react","resolve","React"]}
|