index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = exports.DEFAULT_OPTIONS = void 0;
  6. exports.format = format;
  7. exports.plugins = void 0;
  8. var _ansiStyles = _interopRequireDefault(require('ansi-styles'));
  9. var _collections = require('./collections');
  10. var _AsymmetricMatcher = _interopRequireDefault(
  11. require('./plugins/AsymmetricMatcher')
  12. );
  13. var _ConvertAnsi = _interopRequireDefault(require('./plugins/ConvertAnsi'));
  14. var _DOMCollection = _interopRequireDefault(require('./plugins/DOMCollection'));
  15. var _DOMElement = _interopRequireDefault(require('./plugins/DOMElement'));
  16. var _Immutable = _interopRequireDefault(require('./plugins/Immutable'));
  17. var _ReactElement = _interopRequireDefault(require('./plugins/ReactElement'));
  18. var _ReactTestComponent = _interopRequireDefault(
  19. require('./plugins/ReactTestComponent')
  20. );
  21. function _interopRequireDefault(obj) {
  22. return obj && obj.__esModule ? obj : {default: obj};
  23. }
  24. /**
  25. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  26. *
  27. * This source code is licensed under the MIT license found in the
  28. * LICENSE file in the root directory of this source tree.
  29. */
  30. /* eslint-disable local/ban-types-eventually */
  31. const toString = Object.prototype.toString;
  32. const toISOString = Date.prototype.toISOString;
  33. const errorToString = Error.prototype.toString;
  34. const regExpToString = RegExp.prototype.toString;
  35. /**
  36. * Explicitly comparing typeof constructor to function avoids undefined as name
  37. * when mock identity-obj-proxy returns the key as the value for any key.
  38. */
  39. const getConstructorName = val =>
  40. (typeof val.constructor === 'function' && val.constructor.name) || 'Object';
  41. /* global window */
  42. /** Is val is equal to global window object? Works even if it does not exist :) */
  43. const isWindow = val => typeof window !== 'undefined' && val === window;
  44. const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
  45. const NEWLINE_REGEXP = /\n/gi;
  46. class PrettyFormatPluginError extends Error {
  47. constructor(message, stack) {
  48. super(message);
  49. this.stack = stack;
  50. this.name = this.constructor.name;
  51. }
  52. }
  53. function isToStringedArrayType(toStringed) {
  54. return (
  55. toStringed === '[object Array]' ||
  56. toStringed === '[object ArrayBuffer]' ||
  57. toStringed === '[object DataView]' ||
  58. toStringed === '[object Float32Array]' ||
  59. toStringed === '[object Float64Array]' ||
  60. toStringed === '[object Int8Array]' ||
  61. toStringed === '[object Int16Array]' ||
  62. toStringed === '[object Int32Array]' ||
  63. toStringed === '[object Uint8Array]' ||
  64. toStringed === '[object Uint8ClampedArray]' ||
  65. toStringed === '[object Uint16Array]' ||
  66. toStringed === '[object Uint32Array]'
  67. );
  68. }
  69. function printNumber(val) {
  70. return Object.is(val, -0) ? '-0' : String(val);
  71. }
  72. function printBigInt(val) {
  73. return String(`${val}n`);
  74. }
  75. function printFunction(val, printFunctionName) {
  76. if (!printFunctionName) {
  77. return '[Function]';
  78. }
  79. return '[Function ' + (val.name || 'anonymous') + ']';
  80. }
  81. function printSymbol(val) {
  82. return String(val).replace(SYMBOL_REGEXP, 'Symbol($1)');
  83. }
  84. function printError(val) {
  85. return '[' + errorToString.call(val) + ']';
  86. }
  87. /**
  88. * The first port of call for printing an object, handles most of the
  89. * data-types in JS.
  90. */
  91. function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {
  92. if (val === true || val === false) {
  93. return '' + val;
  94. }
  95. if (val === undefined) {
  96. return 'undefined';
  97. }
  98. if (val === null) {
  99. return 'null';
  100. }
  101. const typeOf = typeof val;
  102. if (typeOf === 'number') {
  103. return printNumber(val);
  104. }
  105. if (typeOf === 'bigint') {
  106. return printBigInt(val);
  107. }
  108. if (typeOf === 'string') {
  109. if (escapeString) {
  110. return '"' + val.replace(/"|\\/g, '\\$&') + '"';
  111. }
  112. return '"' + val + '"';
  113. }
  114. if (typeOf === 'function') {
  115. return printFunction(val, printFunctionName);
  116. }
  117. if (typeOf === 'symbol') {
  118. return printSymbol(val);
  119. }
  120. const toStringed = toString.call(val);
  121. if (toStringed === '[object WeakMap]') {
  122. return 'WeakMap {}';
  123. }
  124. if (toStringed === '[object WeakSet]') {
  125. return 'WeakSet {}';
  126. }
  127. if (
  128. toStringed === '[object Function]' ||
  129. toStringed === '[object GeneratorFunction]'
  130. ) {
  131. return printFunction(val, printFunctionName);
  132. }
  133. if (toStringed === '[object Symbol]') {
  134. return printSymbol(val);
  135. }
  136. if (toStringed === '[object Date]') {
  137. return isNaN(+val) ? 'Date { NaN }' : toISOString.call(val);
  138. }
  139. if (toStringed === '[object Error]') {
  140. return printError(val);
  141. }
  142. if (toStringed === '[object RegExp]') {
  143. if (escapeRegex) {
  144. // https://github.com/benjamingr/RegExp.escape/blob/main/polyfill.js
  145. return regExpToString.call(val).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
  146. }
  147. return regExpToString.call(val);
  148. }
  149. if (val instanceof Error) {
  150. return printError(val);
  151. }
  152. return null;
  153. }
  154. /**
  155. * Handles more complex objects ( such as objects with circular references.
  156. * maps and sets etc )
  157. */
  158. function printComplexValue(
  159. val,
  160. config,
  161. indentation,
  162. depth,
  163. refs,
  164. hasCalledToJSON
  165. ) {
  166. if (refs.indexOf(val) !== -1) {
  167. return '[Circular]';
  168. }
  169. refs = refs.slice();
  170. refs.push(val);
  171. const hitMaxDepth = ++depth > config.maxDepth;
  172. const min = config.min;
  173. if (
  174. config.callToJSON &&
  175. !hitMaxDepth &&
  176. val.toJSON &&
  177. typeof val.toJSON === 'function' &&
  178. !hasCalledToJSON
  179. ) {
  180. return printer(val.toJSON(), config, indentation, depth, refs, true);
  181. }
  182. const toStringed = toString.call(val);
  183. if (toStringed === '[object Arguments]') {
  184. return hitMaxDepth
  185. ? '[Arguments]'
  186. : (min ? '' : 'Arguments ') +
  187. '[' +
  188. (0, _collections.printListItems)(
  189. val,
  190. config,
  191. indentation,
  192. depth,
  193. refs,
  194. printer
  195. ) +
  196. ']';
  197. }
  198. if (isToStringedArrayType(toStringed)) {
  199. return hitMaxDepth
  200. ? '[' + val.constructor.name + ']'
  201. : (min
  202. ? ''
  203. : !config.printBasicPrototype && val.constructor.name === 'Array'
  204. ? ''
  205. : val.constructor.name + ' ') +
  206. '[' +
  207. (0, _collections.printListItems)(
  208. val,
  209. config,
  210. indentation,
  211. depth,
  212. refs,
  213. printer
  214. ) +
  215. ']';
  216. }
  217. if (toStringed === '[object Map]') {
  218. return hitMaxDepth
  219. ? '[Map]'
  220. : 'Map {' +
  221. (0, _collections.printIteratorEntries)(
  222. val.entries(),
  223. config,
  224. indentation,
  225. depth,
  226. refs,
  227. printer,
  228. ' => '
  229. ) +
  230. '}';
  231. }
  232. if (toStringed === '[object Set]') {
  233. return hitMaxDepth
  234. ? '[Set]'
  235. : 'Set {' +
  236. (0, _collections.printIteratorValues)(
  237. val.values(),
  238. config,
  239. indentation,
  240. depth,
  241. refs,
  242. printer
  243. ) +
  244. '}';
  245. } // Avoid failure to serialize global window object in jsdom test environment.
  246. // For example, not even relevant if window is prop of React element.
  247. return hitMaxDepth || isWindow(val)
  248. ? '[' + getConstructorName(val) + ']'
  249. : (min
  250. ? ''
  251. : !config.printBasicPrototype && getConstructorName(val) === 'Object'
  252. ? ''
  253. : getConstructorName(val) + ' ') +
  254. '{' +
  255. (0, _collections.printObjectProperties)(
  256. val,
  257. config,
  258. indentation,
  259. depth,
  260. refs,
  261. printer
  262. ) +
  263. '}';
  264. }
  265. function isNewPlugin(plugin) {
  266. return plugin.serialize != null;
  267. }
  268. function printPlugin(plugin, val, config, indentation, depth, refs) {
  269. let printed;
  270. try {
  271. printed = isNewPlugin(plugin)
  272. ? plugin.serialize(val, config, indentation, depth, refs, printer)
  273. : plugin.print(
  274. val,
  275. valChild => printer(valChild, config, indentation, depth, refs),
  276. str => {
  277. const indentationNext = indentation + config.indent;
  278. return (
  279. indentationNext +
  280. str.replace(NEWLINE_REGEXP, '\n' + indentationNext)
  281. );
  282. },
  283. {
  284. edgeSpacing: config.spacingOuter,
  285. min: config.min,
  286. spacing: config.spacingInner
  287. },
  288. config.colors
  289. );
  290. } catch (error) {
  291. throw new PrettyFormatPluginError(error.message, error.stack);
  292. }
  293. if (typeof printed !== 'string') {
  294. throw new Error(
  295. `pretty-format: Plugin must return type "string" but instead returned "${typeof printed}".`
  296. );
  297. }
  298. return printed;
  299. }
  300. function findPlugin(plugins, val) {
  301. for (let p = 0; p < plugins.length; p++) {
  302. try {
  303. if (plugins[p].test(val)) {
  304. return plugins[p];
  305. }
  306. } catch (error) {
  307. throw new PrettyFormatPluginError(error.message, error.stack);
  308. }
  309. }
  310. return null;
  311. }
  312. function printer(val, config, indentation, depth, refs, hasCalledToJSON) {
  313. const plugin = findPlugin(config.plugins, val);
  314. if (plugin !== null) {
  315. return printPlugin(plugin, val, config, indentation, depth, refs);
  316. }
  317. const basicResult = printBasicValue(
  318. val,
  319. config.printFunctionName,
  320. config.escapeRegex,
  321. config.escapeString
  322. );
  323. if (basicResult !== null) {
  324. return basicResult;
  325. }
  326. return printComplexValue(
  327. val,
  328. config,
  329. indentation,
  330. depth,
  331. refs,
  332. hasCalledToJSON
  333. );
  334. }
  335. const DEFAULT_THEME = {
  336. comment: 'gray',
  337. content: 'reset',
  338. prop: 'yellow',
  339. tag: 'cyan',
  340. value: 'green'
  341. };
  342. const DEFAULT_THEME_KEYS = Object.keys(DEFAULT_THEME);
  343. const DEFAULT_OPTIONS = {
  344. callToJSON: true,
  345. compareKeys: undefined,
  346. escapeRegex: false,
  347. escapeString: true,
  348. highlight: false,
  349. indent: 2,
  350. maxDepth: Infinity,
  351. min: false,
  352. plugins: [],
  353. printBasicPrototype: true,
  354. printFunctionName: true,
  355. theme: DEFAULT_THEME
  356. };
  357. exports.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
  358. function validateOptions(options) {
  359. Object.keys(options).forEach(key => {
  360. if (!DEFAULT_OPTIONS.hasOwnProperty(key)) {
  361. throw new Error(`pretty-format: Unknown option "${key}".`);
  362. }
  363. });
  364. if (options.min && options.indent !== undefined && options.indent !== 0) {
  365. throw new Error(
  366. 'pretty-format: Options "min" and "indent" cannot be used together.'
  367. );
  368. }
  369. if (options.theme !== undefined) {
  370. if (options.theme === null) {
  371. throw new Error('pretty-format: Option "theme" must not be null.');
  372. }
  373. if (typeof options.theme !== 'object') {
  374. throw new Error(
  375. `pretty-format: Option "theme" must be of type "object" but instead received "${typeof options.theme}".`
  376. );
  377. }
  378. }
  379. }
  380. const getColorsHighlight = options =>
  381. DEFAULT_THEME_KEYS.reduce((colors, key) => {
  382. const value =
  383. options.theme && options.theme[key] !== undefined
  384. ? options.theme[key]
  385. : DEFAULT_THEME[key];
  386. const color = value && _ansiStyles.default[value];
  387. if (
  388. color &&
  389. typeof color.close === 'string' &&
  390. typeof color.open === 'string'
  391. ) {
  392. colors[key] = color;
  393. } else {
  394. throw new Error(
  395. `pretty-format: Option "theme" has a key "${key}" whose value "${value}" is undefined in ansi-styles.`
  396. );
  397. }
  398. return colors;
  399. }, Object.create(null));
  400. const getColorsEmpty = () =>
  401. DEFAULT_THEME_KEYS.reduce((colors, key) => {
  402. colors[key] = {
  403. close: '',
  404. open: ''
  405. };
  406. return colors;
  407. }, Object.create(null));
  408. const getPrintFunctionName = options =>
  409. options && options.printFunctionName !== undefined
  410. ? options.printFunctionName
  411. : DEFAULT_OPTIONS.printFunctionName;
  412. const getEscapeRegex = options =>
  413. options && options.escapeRegex !== undefined
  414. ? options.escapeRegex
  415. : DEFAULT_OPTIONS.escapeRegex;
  416. const getEscapeString = options =>
  417. options && options.escapeString !== undefined
  418. ? options.escapeString
  419. : DEFAULT_OPTIONS.escapeString;
  420. const getConfig = options => {
  421. var _options$printBasicPr;
  422. return {
  423. callToJSON:
  424. options && options.callToJSON !== undefined
  425. ? options.callToJSON
  426. : DEFAULT_OPTIONS.callToJSON,
  427. colors:
  428. options && options.highlight
  429. ? getColorsHighlight(options)
  430. : getColorsEmpty(),
  431. compareKeys:
  432. options && typeof options.compareKeys === 'function'
  433. ? options.compareKeys
  434. : DEFAULT_OPTIONS.compareKeys,
  435. escapeRegex: getEscapeRegex(options),
  436. escapeString: getEscapeString(options),
  437. indent:
  438. options && options.min
  439. ? ''
  440. : createIndent(
  441. options && options.indent !== undefined
  442. ? options.indent
  443. : DEFAULT_OPTIONS.indent
  444. ),
  445. maxDepth:
  446. options && options.maxDepth !== undefined
  447. ? options.maxDepth
  448. : DEFAULT_OPTIONS.maxDepth,
  449. min:
  450. options && options.min !== undefined ? options.min : DEFAULT_OPTIONS.min,
  451. plugins:
  452. options && options.plugins !== undefined
  453. ? options.plugins
  454. : DEFAULT_OPTIONS.plugins,
  455. printBasicPrototype:
  456. (_options$printBasicPr =
  457. options === null || options === void 0
  458. ? void 0
  459. : options.printBasicPrototype) !== null &&
  460. _options$printBasicPr !== void 0
  461. ? _options$printBasicPr
  462. : true,
  463. printFunctionName: getPrintFunctionName(options),
  464. spacingInner: options && options.min ? ' ' : '\n',
  465. spacingOuter: options && options.min ? '' : '\n'
  466. };
  467. };
  468. function createIndent(indent) {
  469. return new Array(indent + 1).join(' ');
  470. }
  471. /**
  472. * Returns a presentation string of your `val` object
  473. * @param val any potential JavaScript object
  474. * @param options Custom settings
  475. */
  476. function format(val, options) {
  477. if (options) {
  478. validateOptions(options);
  479. if (options.plugins) {
  480. const plugin = findPlugin(options.plugins, val);
  481. if (plugin !== null) {
  482. return printPlugin(plugin, val, getConfig(options), '', 0, []);
  483. }
  484. }
  485. }
  486. const basicResult = printBasicValue(
  487. val,
  488. getPrintFunctionName(options),
  489. getEscapeRegex(options),
  490. getEscapeString(options)
  491. );
  492. if (basicResult !== null) {
  493. return basicResult;
  494. }
  495. return printComplexValue(val, getConfig(options), '', 0, []);
  496. }
  497. const plugins = {
  498. AsymmetricMatcher: _AsymmetricMatcher.default,
  499. ConvertAnsi: _ConvertAnsi.default,
  500. DOMCollection: _DOMCollection.default,
  501. DOMElement: _DOMElement.default,
  502. Immutable: _Immutable.default,
  503. ReactElement: _ReactElement.default,
  504. ReactTestComponent: _ReactTestComponent.default
  505. };
  506. exports.plugins = plugins;
  507. var _default = format;
  508. exports.default = _default;