@opentelemetry/instrumentation-express 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # OpenTelemetry Express Instrumentation for Node.js
2
+
3
+ [![NPM Published Version][npm-img]][npm-url]
4
+ [![dependencies][dependencies-image]][dependencies-url]
5
+ [![devDependencies][devDependencies-image]][devDependencies-url]
6
+ [![Apache License][license-image]][license-image]
7
+
8
+ This module provides automatic instrumentation for [`express`](https://github.com/expressjs/express).
9
+
10
+ For automatic instrumentation see the
11
+ [@opentelemetry/sdk-trace-node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package.
12
+
13
+ ## Installation
14
+
15
+ This instrumentation relies on HTTP calls to also be instrumented. Make sure you install and enable both, otherwise you will not see any spans being exported from the instrumentation.
16
+
17
+ ```bash
18
+ npm install --save @opentelemetry/instrumentation-http @opentelemetry/instrumentation-express
19
+ ```
20
+
21
+ ### Supported Versions
22
+
23
+ - `^4.0.0`
24
+
25
+ ## Usage
26
+
27
+ OpenTelemetry Express Instrumentation allows the user to automatically collect trace data and export them to their backend of choice, to give observability to distributed systems.
28
+
29
+ To load the instrumentation, specify it in the Node Tracer's configuration:
30
+
31
+ ```js
32
+ const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
33
+ const { registerInstrumentations } = require('@opentelemetry/instrumentation');
34
+ const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
35
+ const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
36
+
37
+ const provider = new NodeTracerProvider();
38
+ provider.register();
39
+
40
+ registerInstrumentations({
41
+ instrumentations: [
42
+ // Express instrumentation expects HTTP layer to be instrumented
43
+ new HttpInstrumentation(),
44
+ new ExpressInstrumentation(),
45
+ ],
46
+ });
47
+ ```
48
+
49
+ See [examples/express](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/express) for a short example.
50
+
51
+ ### Caveats
52
+
53
+ Because of the way express works, it's hard to correctly compute the time taken by asynchronous middlewares and request handlers. For this reason, the time you'll see reported for asynchronous middlewares and request handlers still only represent the synchronous execution time, and **not** any asynchronous work.
54
+
55
+ ### Express Instrumentation Options
56
+
57
+ Express instrumentation has few options available to choose from. You can set the following:
58
+
59
+ | Options | Type | Example | Description |
60
+ | ------- | ---- | ------- | ----------- |
61
+ | `ignoreLayers` | `IgnoreMatcher[]` | `[/^\/_internal\//]` | Ignore layers that by match. |
62
+ | `ignoreLayersType`| `ExpressLayerType[]` | `['request_handler']` | Ignore layers of specified type. |
63
+
64
+ `ignoreLayers` accepts an array of elements of types:
65
+
66
+ - `string` for full match of the path,
67
+ - `RegExp` for partial match of the path,
68
+ - `function` in the form of `(path) => boolean` for custom logic.
69
+
70
+ `ignoreLayersType` accepts an array of following strings:
71
+
72
+ - `router` is the name of `express.Router()`,
73
+ - `middleware`,
74
+ - `request_handler` is the name for anything that's not a router or a middleware.
75
+
76
+ ## Useful links
77
+
78
+ - For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
79
+ - For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
80
+ - For help or feedback on this project, join us in [GitHub Discussions][discussions-url]
81
+
82
+ ## License
83
+
84
+ Apache 2.0 - See [LICENSE][license-url] for more information.
85
+
86
+ [discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions
87
+ [license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE
88
+ [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
89
+ [dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-express
90
+ [dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-express
91
+ [devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-express&type=dev
92
+ [devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-express&type=dev
93
+ [npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-dns
94
+ [npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-dns.svg
@@ -0,0 +1,5 @@
1
+ export declare enum AttributeNames {
2
+ EXPRESS_TYPE = "express.type",
3
+ EXPRESS_NAME = "express.name"
4
+ }
5
+ //# sourceMappingURL=AttributeNames.d.ts.map
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AttributeNames = void 0;
4
+ /*
5
+ * Copyright The OpenTelemetry Authors
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * https://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ var AttributeNames;
20
+ (function (AttributeNames) {
21
+ AttributeNames["EXPRESS_TYPE"] = "express.type";
22
+ AttributeNames["EXPRESS_NAME"] = "express.name";
23
+ })(AttributeNames = exports.AttributeNames || (exports.AttributeNames = {}));
24
+ //# sourceMappingURL=AttributeNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AttributeNames.js","sourceRoot":"","sources":["../../../src/enums/AttributeNames.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,+CAA6B,CAAA;IAC7B,+CAA6B,CAAA;AAC/B,CAAC,EAHW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAGzB"}
@@ -0,0 +1,6 @@
1
+ export declare enum ExpressLayerType {
2
+ ROUTER = "router",
3
+ MIDDLEWARE = "middleware",
4
+ REQUEST_HANDLER = "request_handler"
5
+ }
6
+ //# sourceMappingURL=ExpressLayerType.d.ts.map
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ExpressLayerType = void 0;
4
+ /*
5
+ * Copyright The OpenTelemetry Authors
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * https://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ var ExpressLayerType;
20
+ (function (ExpressLayerType) {
21
+ ExpressLayerType["ROUTER"] = "router";
22
+ ExpressLayerType["MIDDLEWARE"] = "middleware";
23
+ ExpressLayerType["REQUEST_HANDLER"] = "request_handler";
24
+ })(ExpressLayerType = exports.ExpressLayerType || (exports.ExpressLayerType = {}));
25
+ //# sourceMappingURL=ExpressLayerType.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ExpressLayerType.js","sourceRoot":"","sources":["../../../src/enums/ExpressLayerType.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;GAcG;AACH,IAAY,gBAIX;AAJD,WAAY,gBAAgB;IAC1B,qCAAiB,CAAA;IACjB,6CAAyB,CAAA;IACzB,uDAAmC,CAAA;AACrC,CAAC,EAJW,gBAAgB,GAAhB,wBAAgB,KAAhB,wBAAgB,QAI3B"}
@@ -0,0 +1,4 @@
1
+ export * from './instrumentation';
2
+ export { ExpressLayerType } from './enums/ExpressLayerType';
3
+ export { ExpressInstrumentationConfig } from './types';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
25
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
26
+ };
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.ExpressLayerType = void 0;
29
+ __exportStar(require("./instrumentation"), exports);
30
+ var ExpressLayerType_1 = require("./enums/ExpressLayerType");
31
+ Object.defineProperty(exports, "ExpressLayerType", { enumerable: true, get: function () { return ExpressLayerType_1.ExpressLayerType; } });
32
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;AAEH,oDAAkC;AAClC,6DAA4D;AAAnD,oHAAA,gBAAgB,OAAA"}
@@ -0,0 +1,28 @@
1
+ import * as express from 'express';
2
+ import { ExpressInstrumentationConfig } from './types';
3
+ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';
4
+ /**
5
+ * This symbol is used to mark express layer as being already instrumented
6
+ * since its possible to use a given layer multiple times (ex: middlewares)
7
+ */
8
+ export declare const kLayerPatched: unique symbol;
9
+ /** Express instrumentation for OpenTelemetry */
10
+ export declare class ExpressInstrumentation extends InstrumentationBase<typeof express> {
11
+ constructor(config?: ExpressInstrumentationConfig);
12
+ init(): InstrumentationNodeModuleDefinition<typeof express>[];
13
+ /**
14
+ * Get the patch for Router.route function
15
+ */
16
+ private _getRoutePatch;
17
+ /**
18
+ * Get the patch for Router.use function
19
+ */
20
+ private _getRouterUsePatch;
21
+ /**
22
+ * Get the patch for Application.use function
23
+ */
24
+ private _getAppUsePatch;
25
+ /** Patch each express layer to create span and propagate context */
26
+ private _applyPatch;
27
+ }
28
+ //# sourceMappingURL=instrumentation.d.ts.map
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.ExpressInstrumentation = exports.kLayerPatched = void 0;
19
+ const core_1 = require("@opentelemetry/core");
20
+ const api_1 = require("@opentelemetry/api");
21
+ const types_1 = require("./types");
22
+ const ExpressLayerType_1 = require("./enums/ExpressLayerType");
23
+ const AttributeNames_1 = require("./enums/AttributeNames");
24
+ const utils_1 = require("./utils");
25
+ const version_1 = require("./version");
26
+ const instrumentation_1 = require("@opentelemetry/instrumentation");
27
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
28
+ /**
29
+ * This symbol is used to mark express layer as being already instrumented
30
+ * since its possible to use a given layer multiple times (ex: middlewares)
31
+ */
32
+ exports.kLayerPatched = Symbol('express-layer-patched');
33
+ /** Express instrumentation for OpenTelemetry */
34
+ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
35
+ constructor(config = {}) {
36
+ super('@opentelemetry/instrumentation-express', version_1.VERSION, Object.assign({}, config));
37
+ }
38
+ init() {
39
+ return [
40
+ new instrumentation_1.InstrumentationNodeModuleDefinition('express', ['^4.0.0'], (moduleExports, moduleVersion) => {
41
+ api_1.diag.debug(`Applying patch for express@${moduleVersion}`);
42
+ const routerProto = moduleExports.Router;
43
+ // patch express.Router.route
44
+ if (instrumentation_1.isWrapped(routerProto.route)) {
45
+ this._unwrap(routerProto, 'route');
46
+ }
47
+ this._wrap(routerProto, 'route', this._getRoutePatch());
48
+ // patch express.Router.use
49
+ if (instrumentation_1.isWrapped(routerProto.use)) {
50
+ this._unwrap(routerProto, 'use');
51
+ }
52
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
+ this._wrap(routerProto, 'use', this._getRouterUsePatch());
54
+ // patch express.Application.use
55
+ if (instrumentation_1.isWrapped(moduleExports.application.use)) {
56
+ this._unwrap(moduleExports.application, 'use');
57
+ }
58
+ this._wrap(moduleExports.application, 'use',
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ this._getAppUsePatch());
61
+ return moduleExports;
62
+ }, (moduleExports, moduleVersion) => {
63
+ if (moduleExports === undefined)
64
+ return;
65
+ api_1.diag.debug(`Removing patch for express@${moduleVersion}`);
66
+ this._unwrap(moduleExports.Router.prototype, 'route');
67
+ this._unwrap(moduleExports.Router.prototype, 'use');
68
+ this._unwrap(moduleExports.application.prototype, 'use');
69
+ }),
70
+ ];
71
+ }
72
+ /**
73
+ * Get the patch for Router.route function
74
+ */
75
+ _getRoutePatch() {
76
+ const instrumentation = this;
77
+ return function (original) {
78
+ return function route_trace(...args) {
79
+ const route = original.apply(this, args);
80
+ const layer = this.stack[this.stack.length - 1];
81
+ instrumentation._applyPatch(layer, typeof args[0] === 'string' ? args[0] : undefined);
82
+ return route;
83
+ };
84
+ };
85
+ }
86
+ /**
87
+ * Get the patch for Router.use function
88
+ */
89
+ _getRouterUsePatch() {
90
+ const instrumentation = this;
91
+ return function (original) {
92
+ return function use(...args) {
93
+ const route = original.apply(this, args);
94
+ const layer = this.stack[this.stack.length - 1];
95
+ instrumentation._applyPatch(layer, typeof args[0] === 'string' ? args[0] : undefined);
96
+ return route;
97
+ };
98
+ };
99
+ }
100
+ /**
101
+ * Get the patch for Application.use function
102
+ */
103
+ _getAppUsePatch() {
104
+ const instrumentation = this;
105
+ return function (original) {
106
+ return function use(...args) {
107
+ const route = original.apply(this, args);
108
+ const layer = this._router.stack[this._router.stack.length - 1];
109
+ instrumentation._applyPatch.call(instrumentation, layer, typeof args[0] === 'string' ? args[0] : undefined);
110
+ return route;
111
+ };
112
+ };
113
+ }
114
+ /** Patch each express layer to create span and propagate context */
115
+ _applyPatch(layer, layerPath) {
116
+ const instrumentation = this;
117
+ // avoid patching multiple times the same layer
118
+ if (layer[exports.kLayerPatched] === true)
119
+ return;
120
+ layer[exports.kLayerPatched] = true;
121
+ this._wrap(layer, 'handle', (original) => {
122
+ if (original.length === 4)
123
+ return original;
124
+ return function (req, res) {
125
+ utils_1.storeLayerPath(req, layerPath);
126
+ const route = req[types_1._LAYERS_STORE_PROPERTY]
127
+ .filter(path => path !== '/' && path !== '/*')
128
+ .join('');
129
+ const attributes = {
130
+ [semantic_conventions_1.SemanticAttributes.HTTP_ROUTE]: route.length > 0 ? route : '/',
131
+ };
132
+ const metadata = utils_1.getLayerMetadata(layer, layerPath);
133
+ const type = metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE];
134
+ // Rename the root http span in case we haven't done it already
135
+ // once we reach the request handler
136
+ const rpcMetadata = core_1.getRPCMetadata(api_1.context.active());
137
+ if (metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE] ===
138
+ ExpressLayerType_1.ExpressLayerType.REQUEST_HANDLER &&
139
+ (rpcMetadata === null || rpcMetadata === void 0 ? void 0 : rpcMetadata.type) === core_1.RPCType.HTTP) {
140
+ rpcMetadata.span.updateName(`${req.method} ${route.length > 0 ? route : '/'}`);
141
+ }
142
+ // verify against the config if the layer should be ignored
143
+ if (utils_1.isLayerIgnored(metadata.name, type, instrumentation._config)) {
144
+ if (type === ExpressLayerType_1.ExpressLayerType.MIDDLEWARE) {
145
+ req[types_1._LAYERS_STORE_PROPERTY].pop();
146
+ }
147
+ return original.apply(this, arguments);
148
+ }
149
+ if (api_1.trace.getSpan(api_1.context.active()) === undefined) {
150
+ return original.apply(this, arguments);
151
+ }
152
+ const span = instrumentation.tracer.startSpan(metadata.name, {
153
+ attributes: Object.assign(attributes, metadata.attributes),
154
+ });
155
+ const startTime = core_1.hrTime();
156
+ let spanHasEnded = false;
157
+ // If we found anything that isnt a middleware, there no point of measuring
158
+ // their time since they dont have callback.
159
+ if (metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE] !==
160
+ ExpressLayerType_1.ExpressLayerType.MIDDLEWARE) {
161
+ span.end(startTime);
162
+ spanHasEnded = true;
163
+ }
164
+ // listener for response.on('finish')
165
+ const onResponseFinish = () => {
166
+ if (spanHasEnded === false) {
167
+ spanHasEnded = true;
168
+ span.end(startTime);
169
+ }
170
+ };
171
+ // verify we have a callback
172
+ const args = Array.from(arguments);
173
+ const callbackIdx = args.findIndex(arg => typeof arg === 'function');
174
+ const newContext = (rpcMetadata === null || rpcMetadata === void 0 ? void 0 : rpcMetadata.type) === core_1.RPCType.HTTP
175
+ ? core_1.setRPCMetadata(api_1.context.active(), Object.assign(rpcMetadata, { route: route }))
176
+ : api_1.context.active();
177
+ if (callbackIdx >= 0) {
178
+ arguments[callbackIdx] = function () {
179
+ var _a;
180
+ if (spanHasEnded === false) {
181
+ spanHasEnded = true;
182
+ (_a = req.res) === null || _a === void 0 ? void 0 : _a.removeListener('finish', onResponseFinish);
183
+ span.end();
184
+ }
185
+ if (!(req.route && arguments[0] instanceof Error)) {
186
+ req[types_1._LAYERS_STORE_PROPERTY].pop();
187
+ }
188
+ const callback = args[callbackIdx];
189
+ return api_1.context.bind(newContext, callback).apply(this, arguments);
190
+ };
191
+ }
192
+ const result = original.apply(this, arguments);
193
+ /**
194
+ * At this point if the callback wasn't called, that means either the
195
+ * layer is asynchronous (so it will call the callback later on) or that
196
+ * the layer directly end the http response, so we'll hook into the "finish"
197
+ * event to handle the later case.
198
+ */
199
+ if (!spanHasEnded) {
200
+ res.once('finish', onResponseFinish);
201
+ }
202
+ return result;
203
+ };
204
+ });
205
+ }
206
+ }
207
+ exports.ExpressInstrumentation = ExpressInstrumentation;
208
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAK6B;AAC7B,4CAA0E;AAE1E,mCAMiB;AACjB,+DAA4D;AAC5D,2DAAwD;AACxD,mCAA2E;AAC3E,uCAAoC;AACpC,oEAIwC;AACxC,8EAAyE;AAEzE;;;GAGG;AACU,QAAA,aAAa,GAAkB,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAE5E,gDAAgD;AAChD,MAAa,sBAAuB,SAAQ,qCAE3C;IACC,YAAY,SAAuC,EAAE;QACnD,KAAK,CACH,wCAAwC,EACxC,iBAAO,EACP,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAC1B,CAAC;IACJ,CAAC;IAED,IAAI;QACF,OAAO;YACL,IAAI,qDAAmC,CACrC,SAAS,EACT,CAAC,QAAQ,CAAC,EACV,CAAC,aAAa,EAAE,aAAa,EAAE,EAAE;g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ACpB,SAAS,CAAC,WAAW,CAAC,GAAG;;wBACvB,IAAI,YAAY,KAAK,KAAK,EAAE;4BAC1B,YAAY,GAAG,IAAI,CAAC;4BACpB,MAAA,GAAG,CAAC,GAAG,0CAAE,cAAc,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC;4BACpD,IAAI,CAAC,GAAG,EAAE,CAAC;yBACZ;wBACD,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC,YAAY,KAAK,CAAC,EAAE;4BAChD,GAAG,CAAC,8BAAsB,CAAc,CAAC,GAAG,EAAE,CAAC;yBACjD;wBACD,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAa,CAAC;wBAC/C,OAAO,aAAO,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;oBACnE,CAAC,CAAC;iBACH;gBACD,MAAM,MAAM,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;gBAC/C;;;;;mBAKG;gBACH,IAAI,CAAC,YAAY,EAAE;oBACjB,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,gBAAgB,CAAC,CAAC;iBACtC;gBACD,OAAO,MAAM,CAAC;YAChB,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAtOD,wDAsOC"}
@@ -0,0 +1,61 @@
1
+ import { kLayerPatched } from './';
2
+ import { Request } from 'express';
3
+ import { SpanAttributes } from '@opentelemetry/api';
4
+ import { InstrumentationConfig } from '@opentelemetry/instrumentation';
5
+ import { ExpressLayerType } from './enums/ExpressLayerType';
6
+ /**
7
+ * This const define where on the `request` object the Instrumentation will mount the
8
+ * current stack of express layer.
9
+ *
10
+ * It is necessary because express doesnt store the different layers
11
+ * (ie: middleware, router etc) that it called to get to the current layer.
12
+ * Given that, the only way to know the route of a given layer is to
13
+ * store the path of where each previous layer has been mounted.
14
+ *
15
+ * ex: bodyParser > auth middleware > /users router > get /:id
16
+ * in this case the stack would be: ["/users", "/:id"]
17
+ *
18
+ * ex2: bodyParser > /api router > /v1 router > /users router > get /:id
19
+ * stack: ["/api", "/v1", "/users", ":id"]
20
+ *
21
+ */
22
+ export declare const _LAYERS_STORE_PROPERTY = "__ot_middlewares";
23
+ export declare type PatchedRequest = {
24
+ [_LAYERS_STORE_PROPERTY]?: string[];
25
+ } & Request;
26
+ export declare type PathParams = string | RegExp | Array<string | RegExp>;
27
+ export declare type ExpressRouter = {
28
+ params: {
29
+ [key: string]: string;
30
+ };
31
+ _params: string[];
32
+ caseSensitive: boolean;
33
+ mergeParams: boolean;
34
+ strict: boolean;
35
+ stack: ExpressLayer[];
36
+ };
37
+ export declare type ExpressLayer = {
38
+ handle: Function;
39
+ [kLayerPatched]?: boolean;
40
+ name: string;
41
+ params: {
42
+ [key: string]: string;
43
+ };
44
+ path: string;
45
+ regexp: RegExp;
46
+ };
47
+ export declare type LayerMetadata = {
48
+ attributes: SpanAttributes;
49
+ name: string;
50
+ };
51
+ export declare type IgnoreMatcher = string | RegExp | ((name: string) => boolean);
52
+ /**
53
+ * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-Instrumentation-express#express-Instrumentation-options))
54
+ */
55
+ export interface ExpressInstrumentationConfig extends InstrumentationConfig {
56
+ /** Ignore specific based on their name */
57
+ ignoreLayers?: IgnoreMatcher[];
58
+ /** Ignore specific layers based on their type */
59
+ ignoreLayersType?: ExpressLayerType[];
60
+ }
61
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports._LAYERS_STORE_PROPERTY = void 0;
19
+ const _1 = require("./");
20
+ /**
21
+ * This const define where on the `request` object the Instrumentation will mount the
22
+ * current stack of express layer.
23
+ *
24
+ * It is necessary because express doesnt store the different layers
25
+ * (ie: middleware, router etc) that it called to get to the current layer.
26
+ * Given that, the only way to know the route of a given layer is to
27
+ * store the path of where each previous layer has been mounted.
28
+ *
29
+ * ex: bodyParser > auth middleware > /users router > get /:id
30
+ * in this case the stack would be: ["/users", "/:id"]
31
+ *
32
+ * ex2: bodyParser > /api router > /v1 router > /users router > get /:id
33
+ * stack: ["/api", "/v1", "/users", ":id"]
34
+ *
35
+ */
36
+ exports._LAYERS_STORE_PROPERTY = '__ot_middlewares';
37
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,yBAAmC;AAMnC;;;;;;;;;;;;;;;GAeG;AACU,QAAA,sBAAsB,GAAG,kBAAkB,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { SpanAttributes } from '@opentelemetry/api';
2
+ import { ExpressLayer, PatchedRequest, ExpressInstrumentationConfig } from './types';
3
+ import { ExpressLayerType } from './enums/ExpressLayerType';
4
+ /**
5
+ * Store layers path in the request to be able to construct route later
6
+ * @param request The request where
7
+ * @param [value] the value to push into the array
8
+ */
9
+ export declare const storeLayerPath: (request: PatchedRequest, value?: string | undefined) => void;
10
+ /**
11
+ * Parse express layer context to retrieve a name and attributes.
12
+ * @param layer Express layer
13
+ * @param [layerPath] if present, the path on which the layer has been mounted
14
+ */
15
+ export declare const getLayerMetadata: (layer: ExpressLayer, layerPath?: string | undefined) => {
16
+ attributes: SpanAttributes;
17
+ name: string;
18
+ };
19
+ /**
20
+ * Check whether the given request is ignored by configuration
21
+ * It will not re-throw exceptions from `list` provided by the client
22
+ * @param constant e.g URL of request
23
+ * @param [list] List of ignore patterns
24
+ * @param [onException] callback for doing something when an exception has
25
+ * occurred
26
+ */
27
+ export declare const isLayerIgnored: (name: string, type: ExpressLayerType, config?: ExpressInstrumentationConfig | undefined) => boolean;
28
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.isLayerIgnored = exports.getLayerMetadata = exports.storeLayerPath = void 0;
19
+ const types_1 = require("./types");
20
+ const ExpressLayerType_1 = require("./enums/ExpressLayerType");
21
+ const AttributeNames_1 = require("./enums/AttributeNames");
22
+ /**
23
+ * Store layers path in the request to be able to construct route later
24
+ * @param request The request where
25
+ * @param [value] the value to push into the array
26
+ */
27
+ const storeLayerPath = (request, value) => {
28
+ if (Array.isArray(request[types_1._LAYERS_STORE_PROPERTY]) === false) {
29
+ Object.defineProperty(request, types_1._LAYERS_STORE_PROPERTY, {
30
+ enumerable: false,
31
+ value: [],
32
+ });
33
+ }
34
+ if (value === undefined)
35
+ return;
36
+ request[types_1._LAYERS_STORE_PROPERTY].push(value);
37
+ };
38
+ exports.storeLayerPath = storeLayerPath;
39
+ /**
40
+ * Parse express layer context to retrieve a name and attributes.
41
+ * @param layer Express layer
42
+ * @param [layerPath] if present, the path on which the layer has been mounted
43
+ */
44
+ const getLayerMetadata = (layer, layerPath) => {
45
+ if (layer.name === 'router') {
46
+ return {
47
+ attributes: {
48
+ [AttributeNames_1.AttributeNames.EXPRESS_NAME]: layerPath,
49
+ [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.ROUTER,
50
+ },
51
+ name: `router - ${layerPath}`,
52
+ };
53
+ }
54
+ else if (layer.name === 'bound dispatch') {
55
+ return {
56
+ attributes: {
57
+ [AttributeNames_1.AttributeNames.EXPRESS_NAME]: layerPath !== null && layerPath !== void 0 ? layerPath : 'request handler',
58
+ [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.REQUEST_HANDLER,
59
+ },
60
+ name: `request handler${layer.path ? ` - ${layerPath}` : ''}`,
61
+ };
62
+ }
63
+ else {
64
+ return {
65
+ attributes: {
66
+ [AttributeNames_1.AttributeNames.EXPRESS_NAME]: layer.name,
67
+ [AttributeNames_1.AttributeNames.EXPRESS_TYPE]: ExpressLayerType_1.ExpressLayerType.MIDDLEWARE,
68
+ },
69
+ name: `middleware - ${layer.name}`,
70
+ };
71
+ }
72
+ };
73
+ exports.getLayerMetadata = getLayerMetadata;
74
+ /**
75
+ * Check whether the given obj match pattern
76
+ * @param constant e.g URL of request
77
+ * @param obj obj to inspect
78
+ * @param pattern Match pattern
79
+ */
80
+ const satisfiesPattern = (constant, pattern) => {
81
+ if (typeof pattern === 'string') {
82
+ return pattern === constant;
83
+ }
84
+ else if (pattern instanceof RegExp) {
85
+ return pattern.test(constant);
86
+ }
87
+ else if (typeof pattern === 'function') {
88
+ return pattern(constant);
89
+ }
90
+ else {
91
+ throw new TypeError('Pattern is in unsupported datatype');
92
+ }
93
+ };
94
+ /**
95
+ * Check whether the given request is ignored by configuration
96
+ * It will not re-throw exceptions from `list` provided by the client
97
+ * @param constant e.g URL of request
98
+ * @param [list] List of ignore patterns
99
+ * @param [onException] callback for doing something when an exception has
100
+ * occurred
101
+ */
102
+ const isLayerIgnored = (name, type, config) => {
103
+ var _a;
104
+ if (Array.isArray(config === null || config === void 0 ? void 0 : config.ignoreLayersType) &&
105
+ ((_a = config === null || config === void 0 ? void 0 : config.ignoreLayersType) === null || _a === void 0 ? void 0 : _a.includes(type))) {
106
+ return true;
107
+ }
108
+ if (Array.isArray(config === null || config === void 0 ? void 0 : config.ignoreLayers) === false)
109
+ return false;
110
+ try {
111
+ for (const pattern of config.ignoreLayers) {
112
+ if (satisfiesPattern(name, pattern)) {
113
+ return true;
114
+ }
115
+ }
116
+ }
117
+ catch (e) {
118
+ /* catch block*/
119
+ }
120
+ return false;
121
+ };
122
+ exports.isLayerIgnored = isLayerIgnored;
123
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,mCAMiB;AACjB,+DAA4D;AAC5D,2DAAwD;AAExD;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAAC,OAAuB,EAAE,KAAc,EAAE,EAAE;IACxE,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,8BAAsB,CAAC,CAAC,KAAK,KAAK,EAAE;QAC5D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,8BAAsB,EAAE;YACrD,UAAU,EAAE,KAAK;YACjB,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;KACJ;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO;IAC/B,OAAO,CAAC,8BAAsB,CAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC,CAAC;AATW,QAAA,cAAc,kBASzB;AAEF;;;;GAIG;AACI,MAAM,gBAAgB,GAAG,CAC9B,KAAmB,EACnB,SAAkB,EAIlB,EAAE;IACF,IAAI,KAAK,CAAC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AC1B;SAAM;QACL,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;KAC3D;AACH,CAAC,CAAC;AAEF;;;;;;;GAOG;AACI,MAAM,cAAc,GAAG,CAC5B,IAAY,EACZ,IAAsB,EACtB,MAAqC,EAC5B,EAAE;;IACX,IACE,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,CAAC;SACvC,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,gBAAgB,0CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,EACxC;QACA,OAAO,IAAI,CAAC;KACb;IACD,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,YAAY,CAAC,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAChE,IAAI;QACF,KAAK,MAAM,OAAO,IAAI,MAAO,CAAC,YAAa,EAAE;YAC3C,IAAI,gBAAgB,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE;gBACnC,OAAO,IAAI,CAAC;aACb;SACF;KACF;IAAC,OAAO,CAAC,EAAE;QACV,gBAAgB;KACjB;IAED,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAvBW,QAAA,cAAc,kBAuBzB"}
@@ -0,0 +1,2 @@
1
+ export declare const VERSION = "0.25.0";
2
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.VERSION = void 0;
19
+ // this is autogenerated file, see scripts/version-update.js
20
+ exports.VERSION = '0.25.0';
21
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@opentelemetry/instrumentation-express",
3
+ "version": "0.25.0",
4
+ "description": "OpenTelemetry express automatic instrumentation package.",
5
+ "main": "build/src/index.js",
6
+ "types": "build/src/index.d.ts",
7
+ "repository": "open-telemetry/opentelemetry-js-contrib",
8
+ "scripts": {
9
+ "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts'",
10
+ "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../",
11
+ "tdd": "yarn test -- --watch-extensions ts --watch",
12
+ "clean": "rimraf build/*",
13
+ "lint": "eslint . --ext .ts",
14
+ "lint:fix": "eslint . --ext .ts --fix",
15
+ "precompile": "tsc --version",
16
+ "version:update": "node ../../../scripts/version-update.js",
17
+ "compile": "npm run version:update && tsc -p .",
18
+ "prepare": "npm run compile",
19
+ "watch": "tsc -w"
20
+ },
21
+ "keywords": [
22
+ "opentelemetry",
23
+ "express",
24
+ "nodejs",
25
+ "tracing",
26
+ "profiling",
27
+ "instrumentation"
28
+ ],
29
+ "author": "OpenTelemetry Authors",
30
+ "license": "Apache-2.0",
31
+ "engines": {
32
+ "node": ">=8.5.0"
33
+ },
34
+ "files": [
35
+ "build/src/**/*.js",
36
+ "build/src/**/*.js.map",
37
+ "build/src/**/*.d.ts",
38
+ "doc",
39
+ "LICENSE",
40
+ "README.md"
41
+ ],
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "peerDependencies": {
46
+ "@opentelemetry/api": "^1.0.2"
47
+ },
48
+ "devDependencies": {
49
+ "@opentelemetry/api": "1.0.2",
50
+ "@opentelemetry/context-async-hooks": "0.25.0",
51
+ "@opentelemetry/sdk-trace-base": "0.25.0",
52
+ "@opentelemetry/sdk-trace-node": "0.25.0",
53
+ "@types/mocha": "7.0.2",
54
+ "@types/node": "14.17.9",
55
+ "codecov": "3.8.3",
56
+ "express": "4.17.1",
57
+ "gts": "3.1.0",
58
+ "mocha": "7.2.0",
59
+ "nyc": "15.1.0",
60
+ "rimraf": "3.0.2",
61
+ "ts-mocha": "8.0.0",
62
+ "typescript": "4.3.5"
63
+ },
64
+ "dependencies": {
65
+ "@opentelemetry/core": "^0.25.0",
66
+ "@opentelemetry/instrumentation": "^0.25.0",
67
+ "@opentelemetry/semantic-conventions": "^0.25.0",
68
+ "@types/express": "4.17.13"
69
+ },
70
+ "gitHead": "fcfaeb965804d2a081f1dc8d2b82803cd51681af"
71
+ }