object.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import { htmlTreeAsString } from './browser.js';
  2. import { DEBUG_BUILD } from './debug-build.js';
  3. import { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';
  4. import { logger } from './logger.js';
  5. import { truncate } from './string.js';
  6. /**
  7. * Replace a method in an object with a wrapped version of itself.
  8. *
  9. * @param source An object that contains a method to be wrapped.
  10. * @param name The name of the method to be wrapped.
  11. * @param replacementFactory A higher-order function that takes the original version of the given method and returns a
  12. * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to
  13. * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other
  14. * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.
  15. * @returns void
  16. */
  17. function fill(source, name, replacementFactory) {
  18. if (!(name in source)) {
  19. return;
  20. }
  21. const original = source[name] ;
  22. const wrapped = replacementFactory(original) ;
  23. // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work
  24. // otherwise it'll throw "TypeError: Object.defineProperties called on non-object"
  25. if (typeof wrapped === 'function') {
  26. markFunctionWrapped(wrapped, original);
  27. }
  28. source[name] = wrapped;
  29. }
  30. /**
  31. * Defines a non-enumerable property on the given object.
  32. *
  33. * @param obj The object on which to set the property
  34. * @param name The name of the property to be set
  35. * @param value The value to which to set the property
  36. */
  37. function addNonEnumerableProperty(obj, name, value) {
  38. try {
  39. Object.defineProperty(obj, name, {
  40. // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
  41. value: value,
  42. writable: true,
  43. configurable: true,
  44. });
  45. } catch (o_O) {
  46. DEBUG_BUILD && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
  47. }
  48. }
  49. /**
  50. * Remembers the original function on the wrapped function and
  51. * patches up the prototype.
  52. *
  53. * @param wrapped the wrapper function
  54. * @param original the original function that gets wrapped
  55. */
  56. function markFunctionWrapped(wrapped, original) {
  57. try {
  58. const proto = original.prototype || {};
  59. wrapped.prototype = original.prototype = proto;
  60. addNonEnumerableProperty(wrapped, '__sentry_original__', original);
  61. } catch (o_O) {} // eslint-disable-line no-empty
  62. }
  63. /**
  64. * This extracts the original function if available. See
  65. * `markFunctionWrapped` for more information.
  66. *
  67. * @param func the function to unwrap
  68. * @returns the unwrapped version of the function if available.
  69. */
  70. function getOriginalFunction(func) {
  71. return func.__sentry_original__;
  72. }
  73. /**
  74. * Encodes given object into url-friendly format
  75. *
  76. * @param object An object that contains serializable values
  77. * @returns string Encoded
  78. */
  79. function urlEncode(object) {
  80. return Object.keys(object)
  81. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)
  82. .join('&');
  83. }
  84. /**
  85. * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
  86. * non-enumerable properties attached.
  87. *
  88. * @param value Initial source that we have to transform in order for it to be usable by the serializer
  89. * @returns An Event or Error turned into an object - or the value argurment itself, when value is neither an Event nor
  90. * an Error.
  91. */
  92. function convertToPlainObject(
  93. value,
  94. )
  95. {
  96. if (isError(value)) {
  97. return {
  98. message: value.message,
  99. name: value.name,
  100. stack: value.stack,
  101. ...getOwnProperties(value),
  102. };
  103. } else if (isEvent(value)) {
  104. const newObj
  105. = {
  106. type: value.type,
  107. target: serializeEventTarget(value.target),
  108. currentTarget: serializeEventTarget(value.currentTarget),
  109. ...getOwnProperties(value),
  110. };
  111. if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
  112. newObj.detail = value.detail;
  113. }
  114. return newObj;
  115. } else {
  116. return value;
  117. }
  118. }
  119. /** Creates a string representation of the target of an `Event` object */
  120. function serializeEventTarget(target) {
  121. try {
  122. return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
  123. } catch (_oO) {
  124. return '<unknown>';
  125. }
  126. }
  127. /** Filters out all but an object's own properties */
  128. function getOwnProperties(obj) {
  129. if (typeof obj === 'object' && obj !== null) {
  130. const extractedProps = {};
  131. for (const property in obj) {
  132. if (Object.prototype.hasOwnProperty.call(obj, property)) {
  133. extractedProps[property] = (obj )[property];
  134. }
  135. }
  136. return extractedProps;
  137. } else {
  138. return {};
  139. }
  140. }
  141. /**
  142. * Given any captured exception, extract its keys and create a sorted
  143. * and truncated list that will be used inside the event message.
  144. * eg. `Non-error exception captured with keys: foo, bar, baz`
  145. */
  146. function extractExceptionKeysForMessage(exception, maxLength = 40) {
  147. const keys = Object.keys(convertToPlainObject(exception));
  148. keys.sort();
  149. if (!keys.length) {
  150. return '[object has no keys]';
  151. }
  152. if (keys[0].length >= maxLength) {
  153. return truncate(keys[0], maxLength);
  154. }
  155. for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
  156. const serialized = keys.slice(0, includedKeys).join(', ');
  157. if (serialized.length > maxLength) {
  158. continue;
  159. }
  160. if (includedKeys === keys.length) {
  161. return serialized;
  162. }
  163. return truncate(serialized, maxLength);
  164. }
  165. return '';
  166. }
  167. /**
  168. * Given any object, return a new object having removed all fields whose value was `undefined`.
  169. * Works recursively on objects and arrays.
  170. *
  171. * Attention: This function keeps circular references in the returned object.
  172. */
  173. function dropUndefinedKeys(inputValue) {
  174. // This map keeps track of what already visited nodes map to.
  175. // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular
  176. // references as the input object.
  177. const memoizationMap = new Map();
  178. // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API
  179. return _dropUndefinedKeys(inputValue, memoizationMap);
  180. }
  181. function _dropUndefinedKeys(inputValue, memoizationMap) {
  182. if (isPojo(inputValue)) {
  183. // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object
  184. const memoVal = memoizationMap.get(inputValue);
  185. if (memoVal !== undefined) {
  186. return memoVal ;
  187. }
  188. const returnValue = {};
  189. // Store the mapping of this value in case we visit it again, in case of circular data
  190. memoizationMap.set(inputValue, returnValue);
  191. for (const key of Object.keys(inputValue)) {
  192. if (typeof inputValue[key] !== 'undefined') {
  193. returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
  194. }
  195. }
  196. return returnValue ;
  197. }
  198. if (Array.isArray(inputValue)) {
  199. // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object
  200. const memoVal = memoizationMap.get(inputValue);
  201. if (memoVal !== undefined) {
  202. return memoVal ;
  203. }
  204. const returnValue = [];
  205. // Store the mapping of this value in case we visit it again, in case of circular data
  206. memoizationMap.set(inputValue, returnValue);
  207. inputValue.forEach((item) => {
  208. returnValue.push(_dropUndefinedKeys(item, memoizationMap));
  209. });
  210. return returnValue ;
  211. }
  212. return inputValue;
  213. }
  214. function isPojo(input) {
  215. if (!isPlainObject(input)) {
  216. return false;
  217. }
  218. try {
  219. const name = (Object.getPrototypeOf(input) ).constructor.name;
  220. return !name || name === 'Object';
  221. } catch (e) {
  222. return true;
  223. }
  224. }
  225. /**
  226. * Ensure that something is an object.
  227. *
  228. * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper
  229. * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.
  230. *
  231. * @param wat The subject of the objectification
  232. * @returns A version of `wat` which can safely be used with `Object` class methods
  233. */
  234. function objectify(wat) {
  235. let objectified;
  236. switch (true) {
  237. case wat === undefined || wat === null:
  238. objectified = new String(wat);
  239. break;
  240. // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason
  241. // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as
  242. // an object in order to wrap it.
  243. case typeof wat === 'symbol' || typeof wat === 'bigint':
  244. objectified = Object(wat);
  245. break;
  246. // this will catch the remaining primitives: `String`, `Number`, and `Boolean`
  247. case isPrimitive(wat):
  248. // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  249. objectified = new (wat ).constructor(wat);
  250. break;
  251. // by process of elimination, at this point we know that `wat` must already be an object
  252. default:
  253. objectified = wat;
  254. break;
  255. }
  256. return objectified;
  257. }
  258. export { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify, urlEncode };
  259. //# sourceMappingURL=object.js.map