Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

201
node_modules/@opentelemetry/instrumentation/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

257
node_modules/@opentelemetry/instrumentation/README.md generated vendored Normal file
View File

@@ -0,0 +1,257 @@
# OpenTelemetry Instrumentation for web and node
[![NPM Published Version][npm-img]][npm-url]
[![Apache License][license-image]][license-image]
**Note: This is an experimental package under active development. New releases may include breaking changes.**
## Installation
**Note: Much of OpenTelemetry JS documentation is written assuming the compiled application is run as CommonJS.**
For more details on ECMAScript Modules vs CommonJS, refer to [esm-support](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md).
```bash
npm install --save @opentelemetry/instrumentation
```
## Usage in Node
```typescript
import {
InstrumentationBase,
InstrumentationConfig,
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
} from '@opentelemetry/instrumentation';
import type * as module_name_to_be_patched from 'module_name_to_be_patched';
export class MyInstrumentation extends InstrumentationBase {
constructor(config: InstrumentationConfig = {}) {
super('MyInstrumentation', VERSION, config);
}
/**
* Init method will be called when the plugin is constructed.
* It returns an `InstrumentationNodeModuleDefinition` which describes
* the node module to be instrumented and patched.
* It may also return a list of `InstrumentationNodeModuleDefinition`s if
* the plugin should patch multiple modules or versions.
*/
protected init() {
const module = new InstrumentationNodeModuleDefinition(
'module_name_to_be_patched',
['1.*'],
this._onPatchMain,
this._onUnPatchMain,
);
// in case you need to patch additional files - this is optional
module.files.push(this._addPatchingMethod());
return module;
// you can also define more modules then just return an array of modules
// return [module1, module2, ....]
}
private _onPatchMain(moduleExports: typeof module_name_to_be_patched) {
this._wrap(
moduleExports,
'mainMethodName',
this._patchMainMethodName()
);
return moduleExports;
}
private _onUnPatchMain(moduleExports: typeof module_name_to_be_patched) {
this._unwrap(moduleExports, 'mainMethodName');
}
private _addPatchingMethod(): InstrumentationNodeModuleFile {
const file = new InstrumentationNodeModuleFile(
'module_name_to_be_patched/src/some_file.js',
this._onPatchMethodName,
this._onUnPatchMethodName,
);
return file;
}
private _onPatchMethodName(moduleExports: typeof module_name_to_be_patched) {
this._wrap(
moduleExports,
'methodName',
this._patchMethodName()
);
return moduleExports;
}
private _onUnPatchMethodName(moduleExports: typeof module_name_to_be_patched) {
this._unwrap(moduleExports, 'methodName');
}
private _patchMethodName(): (original) => any {
const plugin = this;
return function methodName(original) {
return function patchMethodName(this: any): PromiseOrValue<module_name_to_be_patched.methodName> {
console.log('methodName', arguments);
return original.apply(this, arguments);
};
};
}
private _patchMainMethodName(): (original) => any {
const plugin = this;
return function mainMethodName(original) {
return function patchMainMethodName(this: any): PromiseOrValue<module_name_to_be_patched.mainMethodName> {
console.log('mainMethodName', arguments);
return original.apply(this, arguments);
};
};
}
}
// Later, but before the module to instrument is required
const myInstrumentation = new MyInstrumentation();
myInstrumentation.setTracerProvider(provider); // this is optional, only if global TracerProvider shouldn't be used
myInstrumentation.setMeterProvider(meterProvider); // this is optional
myInstrumentation.enable();
// or use Auto Loader
```
## Usage in Web
```typescript
import {
InstrumentationBase,
InstrumentationConfig,
} from '@opentelemetry/instrumentation';
import { Instrumentation } from '@opentelemetry/instrumentation';
export class MyInstrumentation extends InstrumentationBase {
constructor(config: InstrumentationConfig = {}) {
super('MyInstrumentation', VERSION, config);
}
private _patchOpen() {
return (original: OpenFunction): OpenFunction => {
const plugin = this;
return function patchOpen(this: XMLHttpRequest, ...args): void {
console.log('open', arguments);
return original.apply(this, args);
};
};
}
public enable() {
this._wrap(XMLHttpRequest.prototype, 'open', this._patchOpen());
}
public disable() {
this._unwrap(XMLHttpRequest.prototype, 'open');
}
}
// Later
const myInstrumentation = new MyInstrumentation();
myInstrumentation.setTracerProvider(provider); // this is optional, only if global TracerProvider shouldn't be used
myInstrumentation.setMeterProvider(meterProvider); // this is optional, only if global MeterProvider shouldn't be used
myInstrumentation.enable();
// or use Auto Loader
```
## AutoLoader
### NODE - Auto Loader
```javascript
const { B3Propagator } = require('@opentelemetry/propagator-b3');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
const tracerProvider = new NodeTracerProvider();
tracerProvider.register({
propagator: new B3Propagator(),
});
registerInstrumentations({
instrumentations: [
new HttpInstrumentation(),
],
//tracerProvider: tracerProvider, // optional, only if global TracerProvider shouldn't be used
//meterProvider: meterProvider, // optional, only if global MeterProvider shouldn't be used
});
```
### WEB - Auto Loader
```javascript
const { B3Propagator } = require('@opentelemetry/propagator-b3');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const { XMLHttpRequestInstrumentation } = require('@opentelemetry/instrumentation-xml-http-request');
const { WebTracerProvider } = require('@opentelemetry/sdk-trace-web');
const tracerProvider = new WebTracerProvider();
tracerProvider.register({
propagator: new B3Propagator(),
});
registerInstrumentations({
instrumentations: [
new XMLHttpRequestInstrumentation({
ignoreUrls: [/localhost/],
propagateTraceHeaderCorsUrls: [
'http://localhost:8090',
],
}),
],
//tracerProvider: tracerProvider, // optional, only if global TracerProvider shouldn't be used
//meterProvider: meterProvider, // optional, only if global MeterProvider shouldn't be used
});
```
## Selection of the used TracerProvider/MeterProvider
The `registerInstrumentations()` API allows to specify which `TracerProvider` and/or `MeterProvider` to use by the given options object.
If nothing is specified the global registered provider is used. Usually this is what most users want therefore it's recommended to keep this default.
There might be use case where someone has the need for more providers within an application. Please note that special care must be takes in such setups
to avoid leaking information from one provider to the other because there are a lot places where e.g. the global `ContextManager` or `Propagator` is used.
## Instrumentation for ECMAScript Modules (ESM) in Node.js (experimental)
Node.js uses a different module loader for ECMAScript Modules (ESM) vs. CommonJS (CJS).
A `require()` call will cause Node.js to use the CommonJS module loader.
An `import ...` statement or `import()` call will cause Node.js to use the ECMAScript module loader.
If your application is written in JavaScript as ESM, or it must compile to ESM from TypeScript, then a loader hook is required to properly patch instrumentation.
The custom hook for ESM instrumentation is `--experimental-loader=@opentelemetry/instrumentation/hook.mjs`.
This flag must be passed to the `node` binary, which is often done as a startup command and/or in the `NODE_OPTIONS` environment variable.
For more details on ECMAScript Modules vs CommonJS, refer to [esm-support](https://github.com/open-telemetry/opentelemetry-js/blob/main/doc/esm-support.md).
## Limitations
Instrumentations for external modules (e.g. express, mongodb,...) hooks the `require` call or `import` statement. Therefore following conditions need to be met that this mechanism can work:
- Instrumentations are registered **before** the module to instrument is `require`ed (CJS only)
- modules are not included in a bundle. Tools like `esbuild`, `webpack`, ... usually have some mechanism to exclude specific modules from bundling
## License
Apache 2.0 - See [LICENSE][license-url] for more information.
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For help or feedback on this project, join us in [GitHub Discussions][discussions-url]
[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE
[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation.svg

View File

@@ -0,0 +1,9 @@
import { AutoLoaderOptions } from './types_internal';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export declare function registerInstrumentations(options: AutoLoaderOptions): () => void;
//# sourceMappingURL=autoLoader.d.ts.map

View File

@@ -0,0 +1,35 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { trace, metrics } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import { disableInstrumentations, enableInstrumentations, } from './autoLoaderUtils';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export function registerInstrumentations(options) {
const tracerProvider = options.tracerProvider || trace.getTracerProvider();
const meterProvider = options.meterProvider || metrics.getMeterProvider();
const loggerProvider = options.loggerProvider || logs.getLoggerProvider();
const instrumentations = options.instrumentations?.flat() ?? [];
enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider);
return () => {
disableInstrumentations(instrumentations);
};
}
//# sourceMappingURL=autoLoader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoader.js","sourceRoot":"","sources":["../../src/autoLoader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAG3B;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAA0B;IAE1B,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC3E,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAC1E,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;IAC1E,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAEhE,sBAAsB,CACpB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,cAAc,CACf,CAAC;IAEF,OAAO,GAAG,EAAE;QACV,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,16 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export declare function enableInstrumentations(instrumentations: Instrumentation[], tracerProvider?: TracerProvider, meterProvider?: MeterProvider, loggerProvider?: LoggerProvider): void;
/**
* Disable instrumentations
* @param instrumentations
*/
export declare function disableInstrumentations(instrumentations: Instrumentation[]): void;
//# sourceMappingURL=autoLoaderUtils.d.ts.map

View File

@@ -0,0 +1,50 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
for (let i = 0, j = instrumentations.length; i < j; i++) {
const instrumentation = instrumentations[i];
if (tracerProvider) {
instrumentation.setTracerProvider(tracerProvider);
}
if (meterProvider) {
instrumentation.setMeterProvider(meterProvider);
}
if (loggerProvider && instrumentation.setLoggerProvider) {
instrumentation.setLoggerProvider(loggerProvider);
}
// instrumentations have been already enabled during creation
// so enable only if user prevented that by setting enabled to false
// this is to prevent double enabling but when calling register all
// instrumentations should be now enabled
if (!instrumentation.getConfig().enabled) {
instrumentation.enable();
}
}
}
/**
* Disable instrumentations
* @param instrumentations
*/
export function disableInstrumentations(instrumentations) {
instrumentations.forEach(instrumentation => instrumentation.disable());
}
//# sourceMappingURL=autoLoaderUtils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoaderUtils.js","sourceRoot":"","sources":["../../src/autoLoaderUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,gBAAmC,EACnC,cAA+B,EAC/B,aAA6B,EAC7B,cAA+B;IAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvD,MAAM,eAAe,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;QAC5C,IAAI,cAAc,EAAE;YAClB,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,IAAI,aAAa,EAAE;YACjB,eAAe,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SACjD;QACD,IAAI,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;YACvD,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,6DAA6D;QAC7D,oEAAoE;QACpE,mEAAmE;QACnE,yCAAyC;QACzC,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE;YACxC,eAAe,CAAC,MAAM,EAAE,CAAC;SAC1B;KACF;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,gBAAmC;IAEnC,gBAAgB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,8 @@
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { Instrumentation, InstrumentationConfig, InstrumentationModuleDefinition, InstrumentationModuleFile, ShimWrapped, SpanCustomizationHook, } from './types';
export { AutoLoaderOptions, AutoLoaderResult } from './types_internal';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAUhF,OAAO,EACL,SAAS,EACT,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { registerInstrumentations } from './autoLoader';\nexport { InstrumentationBase } from './platform/index';\nexport { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';\nexport { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';\nexport {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n ShimWrapped,\n SpanCustomizationHook,\n} from './types';\nexport { AutoLoaderOptions, AutoLoaderResult } from './types_internal';\nexport {\n isWrapped,\n safeExecuteInTheMiddle,\n safeExecuteInTheMiddleAsync,\n} from './utils';\n"]}

View File

@@ -0,0 +1,74 @@
import { DiagLogger, Meter, MeterProvider, Tracer, TracerProvider, Span } from '@opentelemetry/api';
import { Logger, LoggerProvider } from '@opentelemetry/api-logs';
import { InstrumentationModuleDefinition, Instrumentation, InstrumentationConfig, SpanCustomizationHook } from './types';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export declare abstract class InstrumentationAbstract<ConfigType extends InstrumentationConfig = InstrumentationConfig> implements Instrumentation<ConfigType> {
readonly instrumentationName: string;
readonly instrumentationVersion: string;
protected _config: ConfigType;
private _tracer;
private _meter;
private _logger;
protected _diag: DiagLogger;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: <Nodule extends object, FieldName extends keyof Nodule>(nodule: Nodule, name: FieldName, wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _unwrap: <Nodule extends object>(nodule: Nodule, name: keyof Nodule) => void;
protected _massWrap: <Nodule extends object, FieldName extends keyof Nodule>(nodules: Nodule[], names: FieldName[], wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _massUnwrap: <Nodule extends object>(nodules: Nodule[], names: (keyof Nodule)[]) => void;
protected get meter(): Meter;
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider: MeterProvider): void;
protected get logger(): Logger;
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider: LoggerProvider): void;
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions(): InstrumentationModuleDefinition[];
/**
* Sets the new metric instruments with the current Meter.
*/
protected _updateMetricInstruments(): void;
getConfig(): ConfigType;
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config: ConfigType): void;
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider: TracerProvider): void;
protected get tracer(): Tracer;
abstract enable(): void;
abstract disable(): void;
/**
* Init method in which plugin should define _modules and patches for
* methods.
*/
protected abstract init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] | void;
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
protected _runSpanCustomizationHook<SpanCustomizationInfoType>(hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined, triggerName: string, span: Span, info: SpanCustomizationInfoType): void;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,141 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag, metrics, trace, } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import * as shimmer from 'shimmer';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export class InstrumentationAbstract {
instrumentationName;
instrumentationVersion;
_config = {};
_tracer;
_meter;
_logger;
_diag;
constructor(instrumentationName, instrumentationVersion, config) {
this.instrumentationName = instrumentationName;
this.instrumentationVersion = instrumentationVersion;
this.setConfig(config);
this._diag = diag.createComponentLogger({
namespace: instrumentationName,
});
this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);
this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);
this._logger = logs.getLogger(instrumentationName, instrumentationVersion);
this._updateMetricInstruments();
}
/* Api to wrap instrumented method */
_wrap = shimmer.wrap;
/* Api to unwrap instrumented methods */
_unwrap = shimmer.unwrap;
/* Api to mass wrap instrumented method */
_massWrap = shimmer.massWrap;
/* Api to mass unwrap instrumented methods */
_massUnwrap = shimmer.massUnwrap;
/* Returns meter */
get meter() {
return this._meter;
}
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider) {
this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
this._updateMetricInstruments();
}
/* Returns logger */
get logger() {
return this._logger;
}
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider) {
this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
}
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions() {
const initResult = this.init() ?? [];
if (!Array.isArray(initResult)) {
return [initResult];
}
return initResult;
}
/**
* Sets the new metric instruments with the current Meter.
*/
_updateMetricInstruments() {
return;
}
/* Returns InstrumentationConfig */
getConfig() {
return this._config;
}
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config) {
// copy config first level properties to ensure they are immutable.
// nested properties are not copied, thus are mutable from the outside.
this._config = {
enabled: true,
...config,
};
}
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider) {
this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
}
/* Returns tracer */
get tracer() {
return this._tracer;
}
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
_runSpanCustomizationHook(hookHandler, triggerName, span, info) {
if (!hookHandler) {
return;
}
try {
hookHandler(span, info);
}
catch (e) {
this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e);
}
}
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import { InstrumentationModuleDefinition, InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleDefinition implements InstrumentationModuleDefinition {
name: string;
supportedVersions: string[];
patch?: ((exports: any, moduleVersion?: string) => any) | undefined;
unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined;
files: InstrumentationModuleFile[];
constructor(name: string, supportedVersions: string[], patch?: ((exports: any, moduleVersion?: string) => any) | undefined, unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined, files?: InstrumentationModuleFile[]);
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.d.ts.map

View File

@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class InstrumentationNodeModuleDefinition {
name;
supportedVersions;
patch;
unpatch;
files;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch, files) {
this.name = name;
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.files = files || [];
}
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleDefinition.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleDefinition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,MAAM,OAAO,mCAAmC;IAKrC;IACA;IAEA;IAEA;IAPT,KAAK,CAA8B;IACnC,YACS,IAAY,EACZ,iBAA2B;IAClC,8DAA8D;IACvD,KAAqD;IAC5D,8DAA8D;IACvD,OAAwD,EAC/D,KAAmC;QAN5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAgD;QAErD,YAAO,GAAP,OAAO,CAAiD;QAG/D,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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"]}

View File

@@ -0,0 +1,9 @@
import { InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleFile implements InstrumentationModuleFile {
supportedVersions: string[];
patch: (moduleExports: any, moduleVersion?: string) => any;
unpatch: (moduleExports?: any, moduleVersion?: string) => void;
name: string;
constructor(name: string, supportedVersions: string[], patch: (moduleExports: any, moduleVersion?: string) => any, unpatch: (moduleExports?: any, moduleVersion?: string) => void);
}
//# sourceMappingURL=instrumentationNodeModuleFile.d.ts.map

View File

@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { normalize } from './platform/index';
export class InstrumentationNodeModuleFile {
supportedVersions;
patch;
unpatch;
name;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch) {
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.name = normalize(name);
}
}
//# sourceMappingURL=instrumentationNodeModuleFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleFile.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleFile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,OAAO,6BAA6B;IAM/B;IAEA;IAEA;IAPF,IAAI,CAAS;IACpB,YACE,IAAY,EACL,iBAA2B;IAClC,8DAA8D;IACvD,KAA0D;IACjE,8DAA8D;IACvD,OAA8D;QAJ9D,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAqD;QAE1D,YAAO,GAAP,OAAO,CAAuD;QAErE,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './noop-normalize';\n"]}

View File

@@ -0,0 +1,10 @@
import { InstrumentationAbstract } from '../../instrumentation';
import * as types from '../../types';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting web plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstrumentationAbstract } from '../../instrumentation';
/**
* Base abstract class for instrumenting web plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
if (this._config.enabled) {
this.enable();
}
}
}
//# sourceMappingURL=instrumentation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/platform/browser/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;GAEG;AACH,MAAM,OAAgB,mBAGpB,SAAQ,uBAAmC;IAG3C,YACE,mBAA2B,EAC3B,sBAA8B,EAC9B,MAAkB;QAElB,KAAK,CAAC,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,CAAC,CAAC;QAE3D,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACxB,IAAI,CAAC,MAAM,EAAE,CAAC;SACf;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport * as types from '../../types';\nimport { InstrumentationConfig } from '../../types';\n\n/**\n * Base abstract class for instrumenting web plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n}\n"]}

View File

@@ -0,0 +1,13 @@
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export declare function normalize(path: string): string;
//# sourceMappingURL=noop-normalize.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export function normalize(path) {
diag.warn('Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)');
return path;
}
//# sourceMappingURL=noop-normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"noop-normalize.js","sourceRoot":"","sources":["../../../../src/platform/browser/noop-normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC,IAAI,CACP,yOAAyO,CAC1O,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Placeholder normalize function to replace the node variant in browser runtimes,\n * this should never be called and will perform a no-op and warn if it is called regardless.\n *\n * This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation\n * package can be made node-only.\n *\n * @param path input path\n * @return unmodified path\n * @internal\n */\nexport function normalize(path: string): string {\n diag.warn(\n 'Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)'\n );\n return path;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase, normalize } from './node';\n"]}

View File

@@ -0,0 +1,36 @@
import type { Hooked } from './RequireInTheMiddleSingleton';
export declare const ModuleNameSeparator = "/";
type ModuleNameTrieSearchOptions = {
/**
* Whether to return the results in insertion order
*/
maintainInsertionOrder?: boolean;
/**
* Whether to return only full matches
*/
fullOnly?: boolean;
};
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export declare class ModuleNameTrie {
private _trie;
private _counter;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook: Hooked): void;
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName: string, { maintainInsertionOrder, fullOnly }?: ModuleNameTrieSearchOptions): Hooked[];
}
export {};
//# sourceMappingURL=ModuleNameTrie.d.ts.map

View File

@@ -0,0 +1,85 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const ModuleNameSeparator = '/';
/**
* Node in a `ModuleNameTrie`
*/
class ModuleNameTrieNode {
hooks = [];
children = new Map();
}
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export class ModuleNameTrie {
_trie = new ModuleNameTrieNode();
_counter = 0;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook) {
let trieNode = this._trie;
for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) {
let nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
nextNode = new ModuleNameTrieNode();
trieNode.children.set(moduleNamePart, nextNode);
}
trieNode = nextNode;
}
trieNode.hooks.push({ hook, insertedId: this._counter++ });
}
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName, { maintainInsertionOrder, fullOnly } = {}) {
let trieNode = this._trie;
const results = [];
let foundFull = true;
for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) {
const nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
foundFull = false;
break;
}
if (!fullOnly) {
results.push(...nextNode.hooks);
}
trieNode = nextNode;
}
if (fullOnly && foundFull) {
results.push(...trieNode.hooks);
}
if (results.length === 0) {
return [];
}
if (results.length === 1) {
return [results[0].hook];
}
if (maintainInsertionOrder) {
results.sort((a, b) => a.insertedId - b.insertedId);
}
return results.map(({ hook }) => hook);
}
}
//# sourceMappingURL=ModuleNameTrie.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { OnRequireFn } from 'require-in-the-middle';
export type Hooked = {
moduleName: string;
onRequire: OnRequireFn;
};
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export declare class RequireInTheMiddleSingleton {
private _moduleNameTrie;
private static _instance?;
private constructor();
private _initialize;
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName: string, onRequire: OnRequireFn): Hooked;
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance(): RequireInTheMiddleSingleton;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.d.ts.map

View File

@@ -0,0 +1,107 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Hook } from 'require-in-the-middle';
import * as path from 'path';
import { ModuleNameTrie, ModuleNameSeparator } from './ModuleNameTrie';
/**
* Whether Mocha is running in this process
* Inspired by https://github.com/AndreasPizsa/detect-mocha
*
* @type {boolean}
*/
const isMocha = [
'afterEach',
'after',
'beforeEach',
'before',
'describe',
'it',
].every(fn => {
// @ts-expect-error TS7053: Element implicitly has an 'any' type
return typeof global[fn] === 'function';
});
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export class RequireInTheMiddleSingleton {
_moduleNameTrie = new ModuleNameTrie();
static _instance;
constructor() {
this._initialize();
}
_initialize() {
new Hook(
// Intercept all `require` calls; we will filter the matching ones below
null, { internals: true }, (exports, name, basedir) => {
// For internal files on Windows, `name` will use backslash as the path separator
const normalizedModuleName = normalizePathSeparators(name);
const matches = this._moduleNameTrie.search(normalizedModuleName, {
maintainInsertionOrder: true,
// For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
// This matches the behavior of `require-in-the-middle`.
// `basedir` is always `undefined` for core modules.
fullOnly: basedir === undefined,
});
for (const { onRequire } of matches) {
exports = onRequire(exports, name, basedir);
}
return exports;
});
}
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName, onRequire) {
const hooked = { moduleName, onRequire };
this._moduleNameTrie.insert(hooked);
return hooked;
}
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance() {
// Mocha runs all test suites in the same process
// This prevents test suites from sharing a singleton
if (isMocha)
return new RequireInTheMiddleSingleton();
return (this._instance =
this._instance ?? new RequireInTheMiddleSingleton());
}
}
/**
* Normalize the path separators to forward slash in a module name or path
*
* @param {string} moduleNameOrPath Module name or path
* @returns {string} Normalized module name or path
*/
function normalizePathSeparators(moduleNameOrPath) {
return path.sep !== ModuleNameSeparator
? moduleNameOrPath.split(path.sep).join(ModuleNameSeparator)
: moduleNameOrPath;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './normalize';\n"]}

View File

@@ -0,0 +1,25 @@
import * as types from '../../types';
import { wrap, unwrap, massWrap, massUnwrap } from 'shimmer';
import { InstrumentationAbstract } from '../../instrumentation';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting node plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
private _modules;
private _hooks;
private _requireInTheMiddleSingleton;
private _enabled;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: typeof wrap;
protected _unwrap: typeof unwrap;
protected _massWrap: typeof massWrap;
protected _massUnwrap: typeof massUnwrap;
private _warnOnPreloadedModules;
private _extractPackageVersion;
private _onRequire;
enable(): void;
disable(): void;
isEnabled(): boolean;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,278 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import { types as utilTypes } from 'util';
import { satisfies } from '../../semver';
import { wrap, unwrap } from 'shimmer';
import { InstrumentationAbstract } from '../../instrumentation';
import { RequireInTheMiddleSingleton, } from './RequireInTheMiddleSingleton';
import { Hook as HookImport } from 'import-in-the-middle';
import { diag } from '@opentelemetry/api';
import { Hook as HookRequire } from 'require-in-the-middle';
import { readFileSync } from 'fs';
import { isWrapped } from '../../utils';
/**
* Base abstract class for instrumenting node plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
_modules;
_hooks = [];
_requireInTheMiddleSingleton = RequireInTheMiddleSingleton.getInstance();
_enabled = false;
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
let modules = this.init();
if (modules && !Array.isArray(modules)) {
modules = [modules];
}
this._modules = modules || [];
if (this._config.enabled) {
this.enable();
}
}
_wrap = (moduleExports, name, wrapper) => {
if (isWrapped(moduleExports[name])) {
this._unwrap(moduleExports, name);
}
if (!utilTypes.isProxy(moduleExports)) {
return wrap(moduleExports, name, wrapper);
}
else {
const wrapped = wrap(Object.assign({}, moduleExports), name, wrapper);
Object.defineProperty(moduleExports, name, {
value: wrapped,
});
return wrapped;
}
};
_unwrap = (moduleExports, name) => {
if (!utilTypes.isProxy(moduleExports)) {
return unwrap(moduleExports, name);
}
else {
return Object.defineProperty(moduleExports, name, {
value: moduleExports[name],
});
}
};
_massWrap = (moduleExportsArray, names, wrapper) => {
if (!moduleExportsArray) {
diag.error('must provide one or more modules to patch');
return;
}
else if (!Array.isArray(moduleExportsArray)) {
moduleExportsArray = [moduleExportsArray];
}
if (!(names && Array.isArray(names))) {
diag.error('must provide one or more functions to wrap on modules');
return;
}
moduleExportsArray.forEach(moduleExports => {
names.forEach(name => {
this._wrap(moduleExports, name, wrapper);
});
});
};
_massUnwrap = (moduleExportsArray, names) => {
if (!moduleExportsArray) {
diag.error('must provide one or more modules to patch');
return;
}
else if (!Array.isArray(moduleExportsArray)) {
moduleExportsArray = [moduleExportsArray];
}
if (!(names && Array.isArray(names))) {
diag.error('must provide one or more functions to wrap on modules');
return;
}
moduleExportsArray.forEach(moduleExports => {
names.forEach(name => {
this._unwrap(moduleExports, name);
});
});
};
_warnOnPreloadedModules() {
this._modules.forEach((module) => {
const { name } = module;
try {
const resolvedModule = require.resolve(name);
if (require.cache[resolvedModule]) {
// Module is already cached, which means the instrumentation hook might not work
this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`);
}
}
catch {
// Module isn't available, we can simply skip
}
});
}
_extractPackageVersion(baseDir) {
try {
const json = readFileSync(path.join(baseDir, 'package.json'), {
encoding: 'utf8',
});
const version = JSON.parse(json).version;
return typeof version === 'string' ? version : undefined;
}
catch (error) {
diag.warn('Failed extracting version', baseDir);
}
return undefined;
}
_onRequire(module, exports, name, baseDir) {
if (!baseDir) {
if (typeof module.patch === 'function') {
module.moduleExports = exports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for nodejs core module on require hook', {
module: module.name,
});
return module.patch(exports);
}
}
return exports;
}
const version = this._extractPackageVersion(baseDir);
module.moduleVersion = version;
if (module.name === name) {
// main module
if (isSupported(module.supportedVersions, version, module.includePrerelease)) {
if (typeof module.patch === 'function') {
module.moduleExports = exports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for module on require hook', {
module: module.name,
version: module.moduleVersion,
baseDir,
});
return module.patch(exports, module.moduleVersion);
}
}
}
return exports;
}
// internal file
const files = module.files ?? [];
const normalizedName = path.normalize(name);
const supportedFileInstrumentations = files
.filter(f => f.name === normalizedName)
.filter(f => isSupported(f.supportedVersions, version, module.includePrerelease));
return supportedFileInstrumentations.reduce((patchedExports, file) => {
file.moduleExports = patchedExports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for nodejs module file on require hook', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
baseDir,
});
// patch signature is not typed, so we cast it assuming it's correct
return file.patch(patchedExports, module.moduleVersion);
}
return patchedExports;
}, exports);
}
enable() {
if (this._enabled) {
return;
}
this._enabled = true;
// already hooked, just call patch again
if (this._hooks.length > 0) {
for (const module of this._modules) {
if (typeof module.patch === 'function' && module.moduleExports) {
this._diag.debug('Applying instrumentation patch for nodejs module on instrumentation enabled', {
module: module.name,
version: module.moduleVersion,
});
module.patch(module.moduleExports, module.moduleVersion);
}
for (const file of module.files) {
if (file.moduleExports) {
this._diag.debug('Applying instrumentation patch for nodejs module file on instrumentation enabled', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
});
file.patch(file.moduleExports, module.moduleVersion);
}
}
}
return;
}
this._warnOnPreloadedModules();
for (const module of this._modules) {
const hookFn = (exports, name, baseDir) => {
if (!baseDir && path.isAbsolute(name)) {
const parsedPath = path.parse(name);
name = parsedPath.name;
baseDir = parsedPath.dir;
}
return this._onRequire(module, exports, name, baseDir);
};
const onRequire = (exports, name, baseDir) => {
return this._onRequire(module, exports, name, baseDir);
};
// `RequireInTheMiddleSingleton` does not support absolute paths.
// For an absolute paths, we must create a separate instance of the
// require-in-the-middle `Hook`.
const hook = path.isAbsolute(module.name)
? new HookRequire([module.name], { internals: true }, onRequire)
: this._requireInTheMiddleSingleton.register(module.name, onRequire);
this._hooks.push(hook);
const esmHook = new HookImport([module.name], { internals: false }, hookFn);
this._hooks.push(esmHook);
}
}
disable() {
if (!this._enabled) {
return;
}
this._enabled = false;
for (const module of this._modules) {
if (typeof module.unpatch === 'function' && module.moduleExports) {
this._diag.debug('Removing instrumentation patch for nodejs module on instrumentation disabled', {
module: module.name,
version: module.moduleVersion,
});
module.unpatch(module.moduleExports, module.moduleVersion);
}
for (const file of module.files) {
if (file.moduleExports) {
this._diag.debug('Removing instrumentation patch for nodejs module file on instrumentation disabled', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
});
file.unpatch(file.moduleExports, module.moduleVersion);
}
}
}
}
isEnabled() {
return this._enabled;
}
}
function isSupported(supportedVersions, version, includePrerelease) {
if (typeof version === 'undefined') {
// If we don't have the version, accept the wildcard case only
return supportedVersions.includes('*');
}
return supportedVersions.some(supportedVersion => {
return satisfies(version, supportedVersion, { includePrerelease });
});
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { normalize } from 'path';
//# sourceMappingURL=normalize.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { normalize } from 'path';
//# sourceMappingURL=normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../../../src/platform/node/normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { normalize } from 'path';\n"]}

View File

@@ -0,0 +1,16 @@
/** Interface for the options to configure semantic versioning satisfy check. */
export interface SatisfiesOptions {
/**
* If set to true, the pre-release checks will be included
* as described [here](https://github.com/npm/node-semver#prerelease-tags).
*/
includePrerelease?: boolean;
}
/**
* Checks given version whether it satisfies given range expression.
* @param version the [version](https://github.com/npm/node-semver#versions) to be checked
* @param range the [range](https://github.com/npm/node-semver#ranges) expression for version check
* @param options options to configure semver satisfy check
*/
export declare function satisfies(version: string, range: string, options?: SatisfiesOptions): boolean;
//# sourceMappingURL=semver.d.ts.map

View File

@@ -0,0 +1,514 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a custom semantic versioning implementation compatible with the
// `satisfies(version, range, options?)` function from the `semver` npm package;
// with the exception that the `loose` option is not supported.
//
// The motivation for the custom semver implementation is that
// `semver` package has some initialization delay (lots of RegExp init and compile)
// and this leads to coldstart overhead for the OTEL Lambda Node.js layer.
// Hence, we have implemented lightweight version of it internally with required functionalities.
import { diag } from '@opentelemetry/api';
const VERSION_REGEXP = /^(?:v)?(?<version>(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*))(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const RANGE_REGEXP = /^(?<op><|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?<version>(?<major>x|X|\*|0|[1-9]\d*)(?:\.(?<minor>x|X|\*|0|[1-9]\d*))?(?:\.(?<patch>x|X|\*|0|[1-9]\d*))?)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const operatorResMap = {
'>': [1],
'>=': [0, 1],
'=': [0],
'<=': [-1, 0],
'<': [-1],
'!=': [-1, 1],
};
/**
* Checks given version whether it satisfies given range expression.
* @param version the [version](https://github.com/npm/node-semver#versions) to be checked
* @param range the [range](https://github.com/npm/node-semver#ranges) expression for version check
* @param options options to configure semver satisfy check
*/
export function satisfies(version, range, options) {
// Strict semver format check
if (!_validateVersion(version)) {
diag.error(`Invalid version: ${version}`);
return false;
}
// If range is empty, satisfy check succeeds regardless what version is
if (!range) {
return true;
}
// Cleanup range
range = range.replace(/([<>=~^]+)\s+/g, '$1');
// Parse version
const parsedVersion = _parseVersion(version);
if (!parsedVersion) {
return false;
}
const allParsedRanges = [];
// Check given version whether it satisfies given range expression
const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options);
// If check result is OK,
// do another final check for pre-release, if pre-release check is included by option
if (checkResult && !options?.includePrerelease) {
return _doPreleaseCheck(parsedVersion, allParsedRanges);
}
return checkResult;
}
function _validateVersion(version) {
return typeof version === 'string' && VERSION_REGEXP.test(version);
}
function _doSatisfies(parsedVersion, range, allParsedRanges, options) {
if (range.includes('||')) {
// A version matches a range if and only if
// every comparator in at least one of the ||-separated comparator sets is satisfied by the version
const ranges = range.trim().split('||');
for (const r of ranges) {
if (_checkRange(parsedVersion, r, allParsedRanges, options)) {
return true;
}
}
return false;
}
else if (range.includes(' - ')) {
// Hyphen ranges: https://github.com/npm/node-semver#hyphen-ranges-xyz---abc
range = replaceHyphen(range, options);
}
else if (range.includes(' ')) {
// Multiple separated ranges and all needs to be satisfied for success
const ranges = range
.trim()
.replace(/\s{2,}/g, ' ')
.split(' ');
for (const r of ranges) {
if (!_checkRange(parsedVersion, r, allParsedRanges, options)) {
return false;
}
}
return true;
}
// Check given parsed version with given range
return _checkRange(parsedVersion, range, allParsedRanges, options);
}
function _checkRange(parsedVersion, range, allParsedRanges, options) {
range = _normalizeRange(range, options);
if (range.includes(' ')) {
// If there are multiple ranges separated, satisfy each of them
return _doSatisfies(parsedVersion, range, allParsedRanges, options);
}
else {
// Validate and parse range
const parsedRange = _parseRange(range);
allParsedRanges.push(parsedRange);
// Check parsed version by parsed range
return _satisfies(parsedVersion, parsedRange);
}
}
function _satisfies(parsedVersion, parsedRange) {
// If range is invalid, satisfy check fails (no error throw)
if (parsedRange.invalid) {
return false;
}
// If range is empty or wildcard, satisfy check succeeds regardless what version is
if (!parsedRange.version || _isWildcard(parsedRange.version)) {
return true;
}
// Compare version segment first
let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []);
// If versions segments are equal, compare by pre-release segments
if (comparisonResult === 0) {
const versionPrereleaseSegments = parsedVersion.prereleaseSegments || [];
const rangePrereleaseSegments = parsedRange.prereleaseSegments || [];
if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
comparisonResult = 0;
}
else if (!versionPrereleaseSegments.length &&
rangePrereleaseSegments.length) {
comparisonResult = 1;
}
else if (versionPrereleaseSegments.length &&
!rangePrereleaseSegments.length) {
comparisonResult = -1;
}
else {
comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments);
}
}
// Resolve check result according to comparison operator
return operatorResMap[parsedRange.op]?.includes(comparisonResult);
}
function _doPreleaseCheck(parsedVersion, allParsedRanges) {
if (parsedVersion.prerelease) {
return allParsedRanges.some(r => r.prerelease && r.version === parsedVersion.version);
}
return true;
}
function _normalizeRange(range, options) {
range = range.trim();
range = replaceCaret(range, options);
range = replaceTilde(range);
range = replaceXRange(range, options);
range = range.trim();
return range;
}
function isX(id) {
return !id || id.toLowerCase() === 'x' || id === '*';
}
function _parseVersion(versionString) {
const match = versionString.match(VERSION_REGEXP);
if (!match) {
diag.error(`Invalid version: ${versionString}`);
return undefined;
}
const version = match.groups.version;
const prerelease = match.groups.prerelease;
const build = match.groups.build;
const versionSegments = version.split('.');
const prereleaseSegments = prerelease?.split('.');
return {
op: undefined,
version,
versionSegments,
versionSegmentCount: versionSegments.length,
prerelease,
prereleaseSegments,
prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
build,
};
}
function _parseRange(rangeString) {
if (!rangeString) {
return {};
}
const match = rangeString.match(RANGE_REGEXP);
if (!match) {
diag.error(`Invalid range: ${rangeString}`);
return {
invalid: true,
};
}
let op = match.groups.op;
const version = match.groups.version;
const prerelease = match.groups.prerelease;
const build = match.groups.build;
const versionSegments = version.split('.');
const prereleaseSegments = prerelease?.split('.');
if (op === '==') {
op = '=';
}
return {
op: op || '=',
version,
versionSegments,
versionSegmentCount: versionSegments.length,
prerelease,
prereleaseSegments,
prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
build,
};
}
function _isWildcard(s) {
return s === '*' || s === 'x' || s === 'X';
}
function _parseVersionString(v) {
const n = parseInt(v, 10);
return isNaN(n) ? v : n;
}
function _normalizeVersionType(a, b) {
if (typeof a === typeof b) {
if (typeof a === 'number') {
return [a, b];
}
else if (typeof a === 'string') {
return [a, b];
}
else {
throw new Error('Version segments can only be strings or numbers');
}
}
else {
return [String(a), String(b)];
}
}
function _compareVersionStrings(v1, v2) {
if (_isWildcard(v1) || _isWildcard(v2)) {
return 0;
}
const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2));
if (parsedV1 > parsedV2) {
return 1;
}
else if (parsedV1 < parsedV2) {
return -1;
}
return 0;
}
function _compareVersionSegments(v1, v2) {
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
const res = _compareVersionStrings(v1[i] || '0', v2[i] || '0');
if (res !== 0) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// The rest of this file is adapted from portions of https://github.com/npm/node-semver/tree/868d4bb
// License:
/*
* The ISC License
*
* Copyright (c) Isaac Z. Schlueter and Contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
const NUMERICIDENTIFIER = '0|[1-9]\\d*';
const NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`;
const GTLT = '((?:<|>)?=?)';
const PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`;
const PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`;
const BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`;
const BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`;
const XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`;
const XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})` +
`(?:\\.(${XRANGEIDENTIFIER})` +
`(?:\\.(${XRANGEIDENTIFIER})` +
`(?:${PRERELEASE})?${BUILD}?` +
`)?)?`;
const XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`;
const XRANGE_REGEXP = new RegExp(XRANGE);
const HYPHENRANGE = `^\\s*(${XRANGEPLAIN})` + `\\s+-\\s+` + `(${XRANGEPLAIN})` + `\\s*$`;
const HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE);
const LONETILDE = '(?:~>?)';
const TILDE = `^${LONETILDE}${XRANGEPLAIN}$`;
const TILDE_REGEXP = new RegExp(TILDE);
const LONECARET = '(?:\\^)';
const CARET = `^${LONECARET}${XRANGEPLAIN}$`;
const CARET_REGEXP = new RegExp(CARET);
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L285
//
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
function replaceTilde(comp) {
const r = TILDE_REGEXP;
return comp.replace(r, (_, M, m, p, pr) => {
let ret;
if (isX(M)) {
ret = '';
}
else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
}
else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
}
else if (pr) {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L329
//
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
function replaceCaret(comp, options) {
const r = CARET_REGEXP;
const z = options?.includePrerelease ? '-0' : '';
return comp.replace(r, (_, M, m, p, pr) => {
let ret;
if (isX(M)) {
ret = '';
}
else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
}
else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
}
else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
}
}
else if (pr) {
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
}
else {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
}
else {
ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
}
}
else {
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
}
else {
ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
}
}
else {
ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
}
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L390
function replaceXRange(comp, options) {
const r = XRANGE_REGEXP;
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p);
const anyX = xp;
if (gtlt === '=' && anyX) {
gtlt = '';
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options?.includePrerelease ? '-0' : '';
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0';
}
else {
// nothing is forbidden
ret = '*';
}
}
else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0;
}
p = 0;
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>=';
if (xm) {
M = +M + 1;
m = 0;
p = 0;
}
else {
m = +m + 1;
p = 0;
}
}
else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<';
if (xm) {
M = +M + 1;
}
else {
m = +m + 1;
}
}
if (gtlt === '<') {
pr = '-0';
}
ret = `${gtlt + M}.${m}.${p}${pr}`;
}
else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
}
else if (xp) {
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L488
//
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
function replaceHyphen(comp, options) {
const r = HYPHENRANGE_REGEXP;
return comp.replace(r, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = '';
}
else if (isX(fm)) {
from = `>=${fM}.0.0${options?.includePrerelease ? '-0' : ''}`;
}
else if (isX(fp)) {
from = `>=${fM}.${fm}.0${options?.includePrerelease ? '-0' : ''}`;
}
else if (fpr) {
from = `>=${from}`;
}
else {
from = `>=${from}${options?.includePrerelease ? '-0' : ''}`;
}
if (isX(tM)) {
to = '';
}
else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
}
else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
}
else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
}
else if (options?.includePrerelease) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
}
else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
});
}
//# sourceMappingURL=semver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,116 @@
import { TracerProvider, MeterProvider, Span } from '@opentelemetry/api';
import { LoggerProvider } from '@opentelemetry/api-logs';
/** Interface Instrumentation to apply patch. */
export interface Instrumentation<ConfigType extends InstrumentationConfig = InstrumentationConfig> {
/** Instrumentation Name */
instrumentationName: string;
/** Instrumentation Version */
instrumentationVersion: string;
/** Method to disable the instrumentation */
disable(): void;
/** Method to enable the instrumentation */
enable(): void;
/** Method to set tracer provider */
setTracerProvider(tracerProvider: TracerProvider): void;
/** Method to set meter provider */
setMeterProvider(meterProvider: MeterProvider): void;
/** Method to set logger provider */
setLoggerProvider?(loggerProvider: LoggerProvider): void;
/** Method to set instrumentation config */
setConfig(config: ConfigType): void;
/** Method to get instrumentation config */
getConfig(): ConfigType;
}
/**
* Base interface for configuration options common to all instrumentations.
* This interface can be extended by individual instrumentations to include
* additional configuration options specific to that instrumentation.
* All configuration options must be optional.
*/
export interface InstrumentationConfig {
/**
* Whether to enable the plugin.
* @default true
*/
enabled?: boolean;
}
/**
* This interface defines the params that are be added to the wrapped function
* using the "shimmer.wrap"
*/
export interface ShimWrapped extends Function {
__wrapped: boolean;
__unwrap: Function;
__original: Function;
}
export interface InstrumentationModuleFile {
/** Name of file to be patched with relative path */
name: string;
moduleExports?: unknown;
/** Supported versions for the file.
*
* A module version is supported if one of the supportedVersions in the array satisfies the module version.
* The syntax of the version is checked with a function compatible
* with [node-semver's `satisfies()` function](https://github.com/npm/node-semver#ranges-1).
* If the version is not supported, we won't apply instrumentation patch.
* If omitted, all versions of the module will be patched.
*
* It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.
* New major versions should be reviewed and tested before being added to the supportedVersions array.
*
* Example: ['>=1.2.3 <3']
*/
supportedVersions: string[];
/** Method to patch the instrumentation */
patch(moduleExports: unknown, moduleVersion?: string): unknown;
/** Method to unpatch the instrumentation */
unpatch(moduleExports?: unknown, moduleVersion?: string): void;
}
export interface InstrumentationModuleDefinition {
/** Module name or path */
name: string;
moduleExports?: any;
/** Instrumented module version */
moduleVersion?: string;
/** Supported version of module.
*
* A module version is supported if one of the supportedVersions in the array satisfies the module version.
* The syntax of the version is checked with the `satisfies` function of
* "The [semantic versioner](https://semver.org) for npm".
* If the version is not supported, we won't apply instrumentation patch (see `enable` method).
* If omitted, all versions of the module will be patched.
*
* It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.
* New major versions should be reviewed and tested before being added to the supportedVersions array.
*
* Example: ['>=1.2.3 <3']
*/
supportedVersions: string[];
/** Module internal files to be patched */
files: InstrumentationModuleFile[];
/** If set to true, the includePrerelease check will be included when calling semver.satisfies */
includePrerelease?: boolean;
/** Method to patch the instrumentation */
patch?: // eslint-disable-next-line @typescript-eslint/no-explicit-any
((moduleExports: any, moduleVersion?: string | undefined) => any) | undefined;
/** Method to unpatch the instrumentation */
unpatch?: ((moduleExports: any, moduleVersion?: string | undefined) => void) | undefined;
}
/**
* SpanCustomizationHook is a common way for instrumentations to expose extension points
* where users can add custom behavior to a span based on info object passed to the hook at different times of the span lifecycle.
* This is an advanced feature, commonly used to add additional or non-spec-compliant attributes to the span,
* capture payloads, modify the span in some way, or carry some other side effect.
*
* The hook is registered with the instrumentation specific config by implementing an handler function with this signature,
* and if the hook is present, it will be called with the span and the event information
* when the event is emitted.
*
* When and under what conditions the hook is called and what data is passed
* in the info argument, is specific to each instrumentation and life-cycle event
* and should be documented where it is used.
*
* Instrumentation may define multiple hooks, for different spans, or different span life-cycle events.
*/
export type SpanCustomizationHook<SpanCustomizationInfoType> = (span: Span, info: SpanCustomizationInfoType) => void;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
export interface AutoLoaderResult {
instrumentations: Instrumentation[];
}
export interface AutoLoaderOptions {
instrumentations?: (Instrumentation | Instrumentation[])[];
tracerProvider?: TracerProvider;
meterProvider?: MeterProvider;
loggerProvider?: LoggerProvider;
}
//# sourceMappingURL=types_internal.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=types_internal.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types_internal.js","sourceRoot":"","sources":["../../src/types_internal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,19 @@
import { ShimWrapped } from './types';
/**
* function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export declare function safeExecuteInTheMiddle<T>(execute: () => T, onFinish: (e: Error | undefined, result: T | undefined) => void, preventThrowingError?: boolean): T;
/**
* Async function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export declare function safeExecuteInTheMiddleAsync<T>(execute: () => T, onFinish: (e: Error | undefined, result: T | undefined) => void, preventThrowingError?: boolean): Promise<T>;
/**
* Checks if certain function has been already wrapped
* @param func
*/
export declare function isWrapped(func: unknown): func is ShimWrapped;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,74 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = execute();
}
catch (e) {
error = e;
}
finally {
onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
/**
* Async function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = await execute();
}
catch (e) {
error = e;
}
finally {
onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
/**
* Checks if certain function has been already wrapped
* @param func
*/
export function isWrapped(func) {
return (typeof func === 'function' &&
typeof func.__original === 'function' &&
typeof func.__unwrap === 'function' &&
func.__wrapped === true);
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAgB,EAChB,QAA+D,EAC/D,oBAA8B;IAE9B,IAAI,KAAwB,CAAC;IAC7B,IAAI,MAAqB,CAAC;IAC1B,IAAI;QACF,MAAM,GAAG,OAAO,EAAE,CAAC;KACpB;IAAC,OAAO,CAAC,EAAE;QACV,KAAK,GAAG,CAAC,CAAC;KACX;YAAS;QACR,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,KAAK,IAAI,CAAC,oBAAoB,EAAE;YAClC,6CAA6C;YAC7C,MAAM,KAAK,CAAC;SACb;QACD,6CAA6C;QAC7C,OAAO,MAAW,CAAC;KACpB;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,QAA+D,EAC/D,oBAA8B;IAE9B,IAAI,KAAwB,CAAC;IAC7B,IAAI,MAAqB,CAAC;IAC1B,IAAI;QACF,MAAM,GAAG,MAAM,OAAO,EAAE,CAAC;KAC1B;IAAC,OAAO,CAAC,EAAE;QACV,KAAK,GAAG,CAAC,CAAC;KACX;YAAS;QACR,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,KAAK,IAAI,CAAC,oBAAoB,EAAE;YAClC,6CAA6C;YAC7C,MAAM,KAAK,CAAC;SACb;QACD,6CAA6C;QAC7C,OAAO,MAAW,CAAC;KACpB;AACH,CAAC;AACD;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAAa;IACrC,OAAO,CACL,OAAO,IAAI,KAAK,UAAU;QAC1B,OAAQ,IAAoB,CAAC,UAAU,KAAK,UAAU;QACtD,OAAQ,IAAoB,CAAC,QAAQ,KAAK,UAAU;QACnD,IAAoB,CAAC,SAAS,KAAK,IAAI,CACzC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "0.200.0";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// this is autogenerated file, see scripts/version-update.js
export const VERSION = '0.200.0';
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.200.0';\n"]}

View File

@@ -0,0 +1,9 @@
import { AutoLoaderOptions } from './types_internal';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export declare function registerInstrumentations(options: AutoLoaderOptions): () => void;
//# sourceMappingURL=autoLoader.d.ts.map

View File

@@ -0,0 +1,35 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { trace, metrics } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import { disableInstrumentations, enableInstrumentations, } from './autoLoaderUtils';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export function registerInstrumentations(options) {
const tracerProvider = options.tracerProvider || trace.getTracerProvider();
const meterProvider = options.meterProvider || metrics.getMeterProvider();
const loggerProvider = options.loggerProvider || logs.getLoggerProvider();
const instrumentations = options.instrumentations?.flat() ?? [];
enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider);
return () => {
disableInstrumentations(instrumentations);
};
}
//# sourceMappingURL=autoLoader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoader.js","sourceRoot":"","sources":["../../src/autoLoader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAG3B;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAA0B;IAE1B,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC3E,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAC1E,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;IAC1E,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAEhE,sBAAsB,CACpB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,cAAc,CACf,CAAC;IAEF,OAAO,GAAG,EAAE;QACV,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,16 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export declare function enableInstrumentations(instrumentations: Instrumentation[], tracerProvider?: TracerProvider, meterProvider?: MeterProvider, loggerProvider?: LoggerProvider): void;
/**
* Disable instrumentations
* @param instrumentations
*/
export declare function disableInstrumentations(instrumentations: Instrumentation[]): void;
//# sourceMappingURL=autoLoaderUtils.d.ts.map

View File

@@ -0,0 +1,50 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
for (let i = 0, j = instrumentations.length; i < j; i++) {
const instrumentation = instrumentations[i];
if (tracerProvider) {
instrumentation.setTracerProvider(tracerProvider);
}
if (meterProvider) {
instrumentation.setMeterProvider(meterProvider);
}
if (loggerProvider && instrumentation.setLoggerProvider) {
instrumentation.setLoggerProvider(loggerProvider);
}
// instrumentations have been already enabled during creation
// so enable only if user prevented that by setting enabled to false
// this is to prevent double enabling but when calling register all
// instrumentations should be now enabled
if (!instrumentation.getConfig().enabled) {
instrumentation.enable();
}
}
}
/**
* Disable instrumentations
* @param instrumentations
*/
export function disableInstrumentations(instrumentations) {
instrumentations.forEach(instrumentation => instrumentation.disable());
}
//# sourceMappingURL=autoLoaderUtils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoaderUtils.js","sourceRoot":"","sources":["../../src/autoLoaderUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,gBAAmC,EACnC,cAA+B,EAC/B,aAA6B,EAC7B,cAA+B;IAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvD,MAAM,eAAe,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;QAC5C,IAAI,cAAc,EAAE;YAClB,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,IAAI,aAAa,EAAE;YACjB,eAAe,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SACjD;QACD,IAAI,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;YACvD,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,6DAA6D;QAC7D,oEAAoE;QACpE,mEAAmE;QACnE,yCAAyC;QACzC,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE;YACxC,eAAe,CAAC,MAAM,EAAE,CAAC;SAC1B;KACF;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,gBAAmC;IAEnC,gBAAgB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,8 @@
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { Instrumentation, InstrumentationConfig, InstrumentationModuleDefinition, InstrumentationModuleFile, ShimWrapped, SpanCustomizationHook, } from './types';
export { AutoLoaderOptions, AutoLoaderResult } from './types_internal';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAUhF,OAAO,EACL,SAAS,EACT,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { registerInstrumentations } from './autoLoader';\nexport { InstrumentationBase } from './platform/index';\nexport { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';\nexport { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';\nexport {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n ShimWrapped,\n SpanCustomizationHook,\n} from './types';\nexport { AutoLoaderOptions, AutoLoaderResult } from './types_internal';\nexport {\n isWrapped,\n safeExecuteInTheMiddle,\n safeExecuteInTheMiddleAsync,\n} from './utils';\n"]}

View File

@@ -0,0 +1,74 @@
import { DiagLogger, Meter, MeterProvider, Tracer, TracerProvider, Span } from '@opentelemetry/api';
import { Logger, LoggerProvider } from '@opentelemetry/api-logs';
import { InstrumentationModuleDefinition, Instrumentation, InstrumentationConfig, SpanCustomizationHook } from './types';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export declare abstract class InstrumentationAbstract<ConfigType extends InstrumentationConfig = InstrumentationConfig> implements Instrumentation<ConfigType> {
readonly instrumentationName: string;
readonly instrumentationVersion: string;
protected _config: ConfigType;
private _tracer;
private _meter;
private _logger;
protected _diag: DiagLogger;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: <Nodule extends object, FieldName extends keyof Nodule>(nodule: Nodule, name: FieldName, wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _unwrap: <Nodule extends object>(nodule: Nodule, name: keyof Nodule) => void;
protected _massWrap: <Nodule extends object, FieldName extends keyof Nodule>(nodules: Nodule[], names: FieldName[], wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _massUnwrap: <Nodule extends object>(nodules: Nodule[], names: (keyof Nodule)[]) => void;
protected get meter(): Meter;
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider: MeterProvider): void;
protected get logger(): Logger;
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider: LoggerProvider): void;
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions(): InstrumentationModuleDefinition[];
/**
* Sets the new metric instruments with the current Meter.
*/
protected _updateMetricInstruments(): void;
getConfig(): ConfigType;
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config: ConfigType): void;
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider: TracerProvider): void;
protected get tracer(): Tracer;
abstract enable(): void;
abstract disable(): void;
/**
* Init method in which plugin should define _modules and patches for
* methods.
*/
protected abstract init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] | void;
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
protected _runSpanCustomizationHook<SpanCustomizationInfoType>(hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined, triggerName: string, span: Span, info: SpanCustomizationInfoType): void;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,141 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag, metrics, trace, } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import * as shimmer from 'shimmer';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export class InstrumentationAbstract {
instrumentationName;
instrumentationVersion;
_config = {};
_tracer;
_meter;
_logger;
_diag;
constructor(instrumentationName, instrumentationVersion, config) {
this.instrumentationName = instrumentationName;
this.instrumentationVersion = instrumentationVersion;
this.setConfig(config);
this._diag = diag.createComponentLogger({
namespace: instrumentationName,
});
this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);
this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);
this._logger = logs.getLogger(instrumentationName, instrumentationVersion);
this._updateMetricInstruments();
}
/* Api to wrap instrumented method */
_wrap = shimmer.wrap;
/* Api to unwrap instrumented methods */
_unwrap = shimmer.unwrap;
/* Api to mass wrap instrumented method */
_massWrap = shimmer.massWrap;
/* Api to mass unwrap instrumented methods */
_massUnwrap = shimmer.massUnwrap;
/* Returns meter */
get meter() {
return this._meter;
}
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider) {
this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
this._updateMetricInstruments();
}
/* Returns logger */
get logger() {
return this._logger;
}
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider) {
this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
}
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions() {
const initResult = this.init() ?? [];
if (!Array.isArray(initResult)) {
return [initResult];
}
return initResult;
}
/**
* Sets the new metric instruments with the current Meter.
*/
_updateMetricInstruments() {
return;
}
/* Returns InstrumentationConfig */
getConfig() {
return this._config;
}
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config) {
// copy config first level properties to ensure they are immutable.
// nested properties are not copied, thus are mutable from the outside.
this._config = {
enabled: true,
...config,
};
}
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider) {
this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
}
/* Returns tracer */
get tracer() {
return this._tracer;
}
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
_runSpanCustomizationHook(hookHandler, triggerName, span, info) {
if (!hookHandler) {
return;
}
try {
hookHandler(span, info);
}
catch (e) {
this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e);
}
}
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import { InstrumentationModuleDefinition, InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleDefinition implements InstrumentationModuleDefinition {
name: string;
supportedVersions: string[];
patch?: ((exports: any, moduleVersion?: string) => any) | undefined;
unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined;
files: InstrumentationModuleFile[];
constructor(name: string, supportedVersions: string[], patch?: ((exports: any, moduleVersion?: string) => any) | undefined, unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined, files?: InstrumentationModuleFile[]);
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.d.ts.map

View File

@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class InstrumentationNodeModuleDefinition {
name;
supportedVersions;
patch;
unpatch;
files;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch, files) {
this.name = name;
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.files = files || [];
}
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleDefinition.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleDefinition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,MAAM,OAAO,mCAAmC;IAKrC;IACA;IAEA;IAEA;IAPT,KAAK,CAA8B;IACnC,YACS,IAAY,EACZ,iBAA2B;IAClC,8DAA8D;IACvD,KAAqD;IAC5D,8DAA8D;IACvD,OAAwD,EAC/D,KAAmC;QAN5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAgD;QAErD,YAAO,GAAP,OAAO,CAAiD;QAG/D,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\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"]}

View File

@@ -0,0 +1,9 @@
import { InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleFile implements InstrumentationModuleFile {
supportedVersions: string[];
patch: (moduleExports: any, moduleVersion?: string) => any;
unpatch: (moduleExports?: any, moduleVersion?: string) => void;
name: string;
constructor(name: string, supportedVersions: string[], patch: (moduleExports: any, moduleVersion?: string) => any, unpatch: (moduleExports?: any, moduleVersion?: string) => void);
}
//# sourceMappingURL=instrumentationNodeModuleFile.d.ts.map

View File

@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { normalize } from './platform/index';
export class InstrumentationNodeModuleFile {
supportedVersions;
patch;
unpatch;
name;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch) {
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.name = normalize(name);
}
}
//# sourceMappingURL=instrumentationNodeModuleFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleFile.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleFile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,OAAO,6BAA6B;IAM/B;IAEA;IAEA;IAPF,IAAI,CAAS;IACpB,YACE,IAAY,EACL,iBAA2B;IAClC,8DAA8D;IACvD,KAA0D;IACjE,8DAA8D;IACvD,OAA8D;QAJ9D,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAqD;QAE1D,YAAO,GAAP,OAAO,CAAuD;QAErE,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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"]}

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './noop-normalize';\n"]}

View File

@@ -0,0 +1,10 @@
import { InstrumentationAbstract } from '../../instrumentation';
import * as types from '../../types';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting web plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstrumentationAbstract } from '../../instrumentation';
/**
* Base abstract class for instrumenting web plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
if (this._config.enabled) {
this.enable();
}
}
}
//# sourceMappingURL=instrumentation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/platform/browser/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;GAEG;AACH,MAAM,OAAgB,mBAGpB,SAAQ,uBAAmC;IAG3C,YACE,mBAA2B,EAC3B,sBAA8B,EAC9B,MAAkB;QAElB,KAAK,CAAC,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,CAAC,CAAC;QAE3D,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACxB,IAAI,CAAC,MAAM,EAAE,CAAC;SACf;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport * as types from '../../types';\nimport { InstrumentationConfig } from '../../types';\n\n/**\n * Base abstract class for instrumenting web plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n}\n"]}

View File

@@ -0,0 +1,13 @@
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export declare function normalize(path: string): string;
//# sourceMappingURL=noop-normalize.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export function normalize(path) {
diag.warn('Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)');
return path;
}
//# sourceMappingURL=noop-normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"noop-normalize.js","sourceRoot":"","sources":["../../../../src/platform/browser/noop-normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC,IAAI,CACP,yOAAyO,CAC1O,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Placeholder normalize function to replace the node variant in browser runtimes,\n * this should never be called and will perform a no-op and warn if it is called regardless.\n *\n * This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation\n * package can be made node-only.\n *\n * @param path input path\n * @return unmodified path\n * @internal\n */\nexport function normalize(path: string): string {\n diag.warn(\n 'Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)'\n );\n return path;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase, normalize } from './node';\n"]}

View File

@@ -0,0 +1,36 @@
import type { Hooked } from './RequireInTheMiddleSingleton';
export declare const ModuleNameSeparator = "/";
type ModuleNameTrieSearchOptions = {
/**
* Whether to return the results in insertion order
*/
maintainInsertionOrder?: boolean;
/**
* Whether to return only full matches
*/
fullOnly?: boolean;
};
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export declare class ModuleNameTrie {
private _trie;
private _counter;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook: Hooked): void;
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName: string, { maintainInsertionOrder, fullOnly }?: ModuleNameTrieSearchOptions): Hooked[];
}
export {};
//# sourceMappingURL=ModuleNameTrie.d.ts.map

View File

@@ -0,0 +1,85 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const ModuleNameSeparator = '/';
/**
* Node in a `ModuleNameTrie`
*/
class ModuleNameTrieNode {
hooks = [];
children = new Map();
}
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export class ModuleNameTrie {
_trie = new ModuleNameTrieNode();
_counter = 0;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook) {
let trieNode = this._trie;
for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) {
let nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
nextNode = new ModuleNameTrieNode();
trieNode.children.set(moduleNamePart, nextNode);
}
trieNode = nextNode;
}
trieNode.hooks.push({ hook, insertedId: this._counter++ });
}
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName, { maintainInsertionOrder, fullOnly } = {}) {
let trieNode = this._trie;
const results = [];
let foundFull = true;
for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) {
const nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
foundFull = false;
break;
}
if (!fullOnly) {
results.push(...nextNode.hooks);
}
trieNode = nextNode;
}
if (fullOnly && foundFull) {
results.push(...trieNode.hooks);
}
if (results.length === 0) {
return [];
}
if (results.length === 1) {
return [results[0].hook];
}
if (maintainInsertionOrder) {
results.sort((a, b) => a.insertedId - b.insertedId);
}
return results.map(({ hook }) => hook);
}
}
//# sourceMappingURL=ModuleNameTrie.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { OnRequireFn } from 'require-in-the-middle';
export type Hooked = {
moduleName: string;
onRequire: OnRequireFn;
};
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export declare class RequireInTheMiddleSingleton {
private _moduleNameTrie;
private static _instance?;
private constructor();
private _initialize;
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName: string, onRequire: OnRequireFn): Hooked;
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance(): RequireInTheMiddleSingleton;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.d.ts.map

View File

@@ -0,0 +1,107 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Hook } from 'require-in-the-middle';
import * as path from 'path';
import { ModuleNameTrie, ModuleNameSeparator } from './ModuleNameTrie';
/**
* Whether Mocha is running in this process
* Inspired by https://github.com/AndreasPizsa/detect-mocha
*
* @type {boolean}
*/
const isMocha = [
'afterEach',
'after',
'beforeEach',
'before',
'describe',
'it',
].every(fn => {
// @ts-expect-error TS7053: Element implicitly has an 'any' type
return typeof global[fn] === 'function';
});
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export class RequireInTheMiddleSingleton {
_moduleNameTrie = new ModuleNameTrie();
static _instance;
constructor() {
this._initialize();
}
_initialize() {
new Hook(
// Intercept all `require` calls; we will filter the matching ones below
null, { internals: true }, (exports, name, basedir) => {
// For internal files on Windows, `name` will use backslash as the path separator
const normalizedModuleName = normalizePathSeparators(name);
const matches = this._moduleNameTrie.search(normalizedModuleName, {
maintainInsertionOrder: true,
// For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
// This matches the behavior of `require-in-the-middle`.
// `basedir` is always `undefined` for core modules.
fullOnly: basedir === undefined,
});
for (const { onRequire } of matches) {
exports = onRequire(exports, name, basedir);
}
return exports;
});
}
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName, onRequire) {
const hooked = { moduleName, onRequire };
this._moduleNameTrie.insert(hooked);
return hooked;
}
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance() {
// Mocha runs all test suites in the same process
// This prevents test suites from sharing a singleton
if (isMocha)
return new RequireInTheMiddleSingleton();
return (this._instance =
this._instance ?? new RequireInTheMiddleSingleton());
}
}
/**
* Normalize the path separators to forward slash in a module name or path
*
* @param {string} moduleNameOrPath Module name or path
* @returns {string} Normalized module name or path
*/
function normalizePathSeparators(moduleNameOrPath) {
return path.sep !== ModuleNameSeparator
? moduleNameOrPath.split(path.sep).join(ModuleNameSeparator)
: moduleNameOrPath;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.js.map

Some files were not shown because too many files have changed in this diff Show More