global-utils.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const major = VERSION.split('.')[0];
  20. const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
  21. const _global = _globalThis;
  22. export function registerGlobal(type, instance, diag, allowOverride = false) {
  23. var _a;
  24. const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
  25. version: VERSION,
  26. });
  27. if (!allowOverride && api[type]) {
  28. // already registered an API of this type
  29. const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
  30. diag.error(err.stack || err.message);
  31. return false;
  32. }
  33. if (api.version !== VERSION) {
  34. // All registered APIs must be of the same version exactly
  35. const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`);
  36. diag.error(err.stack || err.message);
  37. return false;
  38. }
  39. api[type] = instance;
  40. diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`);
  41. return true;
  42. }
  43. export function getGlobal(type) {
  44. var _a, _b;
  45. const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
  46. if (!globalVersion || !isCompatible(globalVersion)) {
  47. return;
  48. }
  49. return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
  50. }
  51. export function unregisterGlobal(type, diag) {
  52. diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`);
  53. const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
  54. if (api) {
  55. delete api[type];
  56. }
  57. }
  58. //# sourceMappingURL=global-utils.js.map