global-utils.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import { _globalThis } from '../platform';
  17. import { VERSION } from '../version';
  18. import { isCompatible } from './semver';
  19. var major = VERSION.split('.')[0];
  20. var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
  21. var _global = _globalThis;
  22. export function registerGlobal(type, instance, diag, allowOverride) {
  23. var _a;
  24. if (allowOverride === void 0) { allowOverride = false; }
  25. var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
  26. version: VERSION,
  27. });
  28. if (!allowOverride && api[type]) {
  29. // already registered an API of this type
  30. var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
  31. diag.error(err.stack || err.message);
  32. return false;
  33. }
  34. if (api.version !== VERSION) {
  35. // All registered APIs must be of the same version exactly
  36. var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
  37. diag.error(err.stack || err.message);
  38. return false;
  39. }
  40. api[type] = instance;
  41. diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
  42. return true;
  43. }
  44. export function getGlobal(type) {
  45. var _a, _b;
  46. var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
  47. if (!globalVersion || !isCompatible(globalVersion)) {
  48. return;
  49. }
  50. return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
  51. }
  52. export function unregisterGlobal(type, diag) {
  53. diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
  54. var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
  55. if (api) {
  56. delete api[type];
  57. }
  58. }
  59. //# sourceMappingURL=global-utils.js.map