functiontostring.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { getOriginalFunction } from '@sentry/utils';
  2. import { getClient } from '../exports.js';
  3. import { convertIntegrationFnToClass, defineIntegration } from '../integration.js';
  4. let originalFunctionToString;
  5. const INTEGRATION_NAME = 'FunctionToString';
  6. const SETUP_CLIENTS = new WeakMap();
  7. const _functionToStringIntegration = (() => {
  8. return {
  9. name: INTEGRATION_NAME,
  10. setupOnce() {
  11. // eslint-disable-next-line @typescript-eslint/unbound-method
  12. originalFunctionToString = Function.prototype.toString;
  13. // intrinsics (like Function.prototype) might be immutable in some environments
  14. // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)
  15. try {
  16. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  17. Function.prototype.toString = function ( ...args) {
  18. const originalFunction = getOriginalFunction(this);
  19. const context =
  20. SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;
  21. return originalFunctionToString.apply(context, args);
  22. };
  23. } catch (e) {
  24. // ignore errors here, just don't patch this
  25. }
  26. },
  27. setup(client) {
  28. SETUP_CLIENTS.set(client, true);
  29. },
  30. };
  31. }) ;
  32. /**
  33. * Patch toString calls to return proper name for wrapped functions.
  34. *
  35. * ```js
  36. * Sentry.init({
  37. * integrations: [
  38. * functionToStringIntegration(),
  39. * ],
  40. * });
  41. * ```
  42. */
  43. const functionToStringIntegration = defineIntegration(_functionToStringIntegration);
  44. /**
  45. * Patch toString calls to return proper name for wrapped functions.
  46. *
  47. * @deprecated Use `functionToStringIntegration()` instead.
  48. */
  49. // eslint-disable-next-line deprecation/deprecation
  50. const FunctionToString = convertIntegrationFnToClass(
  51. INTEGRATION_NAME,
  52. functionToStringIntegration,
  53. ) ;
  54. // eslint-disable-next-line deprecation/deprecation
  55. export { FunctionToString, functionToStringIntegration };
  56. //# sourceMappingURL=functiontostring.js.map