console.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @polyfill
  8. * @nolint
  9. * @format
  10. */
  11. /* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, no-control-regex */
  12. /**
  13. * This pipes all of our console logging functions to native logging so that
  14. * JavaScript errors in required modules show up in Xcode via NSLog.
  15. */
  16. const inspect = (function() {
  17. // Copyright Joyent, Inc. and other Node contributors.
  18. //
  19. // Permission is hereby granted, free of charge, to any person obtaining a
  20. // copy of this software and associated documentation files (the
  21. // "Software"), to deal in the Software without restriction, including
  22. // without limitation the rights to use, copy, modify, merge, publish,
  23. // distribute, sublicense, and/or sell copies of the Software, and to permit
  24. // persons to whom the Software is furnished to do so, subject to the
  25. // following conditions:
  26. //
  27. // The above copyright notice and this permission notice shall be included
  28. // in all copies or substantial portions of the Software.
  29. //
  30. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  31. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  32. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  33. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  34. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  35. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  36. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  37. //
  38. // https://github.com/joyent/node/blob/master/lib/util.js
  39. function inspect(obj, opts) {
  40. var ctx = {
  41. seen: [],
  42. formatValueCalls: 0,
  43. stylize: stylizeNoColor,
  44. };
  45. return formatValue(ctx, obj, opts.depth);
  46. }
  47. function stylizeNoColor(str, styleType) {
  48. return str;
  49. }
  50. function arrayToHash(array) {
  51. var hash = {};
  52. array.forEach(function(val, idx) {
  53. hash[val] = true;
  54. });
  55. return hash;
  56. }
  57. function formatValue(ctx, value, recurseTimes) {
  58. ctx.formatValueCalls++;
  59. if (ctx.formatValueCalls > 200) {
  60. return `[TOO BIG formatValueCalls ${
  61. ctx.formatValueCalls
  62. } exceeded limit of 200]`;
  63. }
  64. // Primitive types cannot have properties
  65. var primitive = formatPrimitive(ctx, value);
  66. if (primitive) {
  67. return primitive;
  68. }
  69. // Look up the keys of the object.
  70. var keys = Object.keys(value);
  71. var visibleKeys = arrayToHash(keys);
  72. // IE doesn't make error fields non-enumerable
  73. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  74. if (
  75. isError(value) &&
  76. (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)
  77. ) {
  78. return formatError(value);
  79. }
  80. // Some type of object without properties can be shortcutted.
  81. if (keys.length === 0) {
  82. if (isFunction(value)) {
  83. var name = value.name ? ': ' + value.name : '';
  84. return ctx.stylize('[Function' + name + ']', 'special');
  85. }
  86. if (isRegExp(value)) {
  87. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  88. }
  89. if (isDate(value)) {
  90. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  91. }
  92. if (isError(value)) {
  93. return formatError(value);
  94. }
  95. }
  96. var base = '',
  97. array = false,
  98. braces = ['{', '}'];
  99. // Make Array say that they are Array
  100. if (isArray(value)) {
  101. array = true;
  102. braces = ['[', ']'];
  103. }
  104. // Make functions say that they are functions
  105. if (isFunction(value)) {
  106. var n = value.name ? ': ' + value.name : '';
  107. base = ' [Function' + n + ']';
  108. }
  109. // Make RegExps say that they are RegExps
  110. if (isRegExp(value)) {
  111. base = ' ' + RegExp.prototype.toString.call(value);
  112. }
  113. // Make dates with properties first say the date
  114. if (isDate(value)) {
  115. base = ' ' + Date.prototype.toUTCString.call(value);
  116. }
  117. // Make error with message first say the error
  118. if (isError(value)) {
  119. base = ' ' + formatError(value);
  120. }
  121. if (keys.length === 0 && (!array || value.length == 0)) {
  122. return braces[0] + base + braces[1];
  123. }
  124. if (recurseTimes < 0) {
  125. if (isRegExp(value)) {
  126. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  127. } else {
  128. return ctx.stylize('[Object]', 'special');
  129. }
  130. }
  131. ctx.seen.push(value);
  132. var output;
  133. if (array) {
  134. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  135. } else {
  136. output = keys.map(function(key) {
  137. return formatProperty(
  138. ctx,
  139. value,
  140. recurseTimes,
  141. visibleKeys,
  142. key,
  143. array,
  144. );
  145. });
  146. }
  147. ctx.seen.pop();
  148. return reduceToSingleString(output, base, braces);
  149. }
  150. function formatPrimitive(ctx, value) {
  151. if (isUndefined(value)) return ctx.stylize('undefined', 'undefined');
  152. if (isString(value)) {
  153. var simple =
  154. "'" +
  155. JSON.stringify(value)
  156. .replace(/^"|"$/g, '')
  157. .replace(/'/g, "\\'")
  158. .replace(/\\"/g, '"') +
  159. "'";
  160. return ctx.stylize(simple, 'string');
  161. }
  162. if (isNumber(value)) return ctx.stylize('' + value, 'number');
  163. if (isBoolean(value)) return ctx.stylize('' + value, 'boolean');
  164. // For some reason typeof null is "object", so special case here.
  165. if (isNull(value)) return ctx.stylize('null', 'null');
  166. }
  167. function formatError(value) {
  168. return '[' + Error.prototype.toString.call(value) + ']';
  169. }
  170. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  171. var output = [];
  172. for (var i = 0, l = value.length; i < l; ++i) {
  173. if (hasOwnProperty(value, String(i))) {
  174. output.push(
  175. formatProperty(
  176. ctx,
  177. value,
  178. recurseTimes,
  179. visibleKeys,
  180. String(i),
  181. true,
  182. ),
  183. );
  184. } else {
  185. output.push('');
  186. }
  187. }
  188. keys.forEach(function(key) {
  189. if (!key.match(/^\d+$/)) {
  190. output.push(
  191. formatProperty(ctx, value, recurseTimes, visibleKeys, key, true),
  192. );
  193. }
  194. });
  195. return output;
  196. }
  197. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  198. var name, str, desc;
  199. desc = Object.getOwnPropertyDescriptor(value, key) || {value: value[key]};
  200. if (desc.get) {
  201. if (desc.set) {
  202. str = ctx.stylize('[Getter/Setter]', 'special');
  203. } else {
  204. str = ctx.stylize('[Getter]', 'special');
  205. }
  206. } else {
  207. if (desc.set) {
  208. str = ctx.stylize('[Setter]', 'special');
  209. }
  210. }
  211. if (!hasOwnProperty(visibleKeys, key)) {
  212. name = '[' + key + ']';
  213. }
  214. if (!str) {
  215. if (ctx.seen.indexOf(desc.value) < 0) {
  216. if (isNull(recurseTimes)) {
  217. str = formatValue(ctx, desc.value, null);
  218. } else {
  219. str = formatValue(ctx, desc.value, recurseTimes - 1);
  220. }
  221. if (str.indexOf('\n') > -1) {
  222. if (array) {
  223. str = str
  224. .split('\n')
  225. .map(function(line) {
  226. return ' ' + line;
  227. })
  228. .join('\n')
  229. .substr(2);
  230. } else {
  231. str =
  232. '\n' +
  233. str
  234. .split('\n')
  235. .map(function(line) {
  236. return ' ' + line;
  237. })
  238. .join('\n');
  239. }
  240. }
  241. } else {
  242. str = ctx.stylize('[Circular]', 'special');
  243. }
  244. }
  245. if (isUndefined(name)) {
  246. if (array && key.match(/^\d+$/)) {
  247. return str;
  248. }
  249. name = JSON.stringify('' + key);
  250. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  251. name = name.substr(1, name.length - 2);
  252. name = ctx.stylize(name, 'name');
  253. } else {
  254. name = name
  255. .replace(/'/g, "\\'")
  256. .replace(/\\"/g, '"')
  257. .replace(/(^"|"$)/g, "'");
  258. name = ctx.stylize(name, 'string');
  259. }
  260. }
  261. return name + ': ' + str;
  262. }
  263. function reduceToSingleString(output, base, braces) {
  264. var numLinesEst = 0;
  265. var length = output.reduce(function(prev, cur) {
  266. numLinesEst++;
  267. if (cur.indexOf('\n') >= 0) numLinesEst++;
  268. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  269. }, 0);
  270. if (length > 60) {
  271. return (
  272. braces[0] +
  273. (base === '' ? '' : base + '\n ') +
  274. ' ' +
  275. output.join(',\n ') +
  276. ' ' +
  277. braces[1]
  278. );
  279. }
  280. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  281. }
  282. // NOTE: These type checking functions intentionally don't use `instanceof`
  283. // because it is fragile and can be easily faked with `Object.create()`.
  284. function isArray(ar) {
  285. return Array.isArray(ar);
  286. }
  287. function isBoolean(arg) {
  288. return typeof arg === 'boolean';
  289. }
  290. function isNull(arg) {
  291. return arg === null;
  292. }
  293. function isNullOrUndefined(arg) {
  294. return arg == null;
  295. }
  296. function isNumber(arg) {
  297. return typeof arg === 'number';
  298. }
  299. function isString(arg) {
  300. return typeof arg === 'string';
  301. }
  302. function isSymbol(arg) {
  303. return typeof arg === 'symbol';
  304. }
  305. function isUndefined(arg) {
  306. return arg === void 0;
  307. }
  308. function isRegExp(re) {
  309. return isObject(re) && objectToString(re) === '[object RegExp]';
  310. }
  311. function isObject(arg) {
  312. return typeof arg === 'object' && arg !== null;
  313. }
  314. function isDate(d) {
  315. return isObject(d) && objectToString(d) === '[object Date]';
  316. }
  317. function isError(e) {
  318. return (
  319. isObject(e) &&
  320. (objectToString(e) === '[object Error]' || e instanceof Error)
  321. );
  322. }
  323. function isFunction(arg) {
  324. return typeof arg === 'function';
  325. }
  326. function objectToString(o) {
  327. return Object.prototype.toString.call(o);
  328. }
  329. function hasOwnProperty(obj, prop) {
  330. return Object.prototype.hasOwnProperty.call(obj, prop);
  331. }
  332. return inspect;
  333. })();
  334. const OBJECT_COLUMN_NAME = '(index)';
  335. const LOG_LEVELS = {
  336. trace: 0,
  337. info: 1,
  338. warn: 2,
  339. error: 3,
  340. };
  341. const INSPECTOR_LEVELS = [];
  342. INSPECTOR_LEVELS[LOG_LEVELS.trace] = 'debug';
  343. INSPECTOR_LEVELS[LOG_LEVELS.info] = 'log';
  344. INSPECTOR_LEVELS[LOG_LEVELS.warn] = 'warning';
  345. INSPECTOR_LEVELS[LOG_LEVELS.error] = 'error';
  346. // Strip the inner function in getNativeLogFunction(), if in dev also
  347. // strip method printing to originalConsole.
  348. const INSPECTOR_FRAMES_TO_SKIP = __DEV__ ? 2 : 1;
  349. function getNativeLogFunction(level) {
  350. return function() {
  351. let str;
  352. if (arguments.length === 1 && typeof arguments[0] === 'string') {
  353. str = arguments[0];
  354. } else {
  355. str = Array.prototype.map
  356. .call(arguments, function(arg) {
  357. return inspect(arg, {depth: 10});
  358. })
  359. .join(', ');
  360. }
  361. // TRICKY
  362. // If more than one argument is provided, the code above collapses them all
  363. // into a single formatted string. This transform wraps string arguments in
  364. // single quotes (e.g. "foo" -> "'foo'") which then breaks the "Warning:"
  365. // check below. So it's important that we look at the first argument, rather
  366. // than the formatted argument string.
  367. const firstArg = arguments[0];
  368. let logLevel = level;
  369. if (
  370. typeof firstArg === 'string' &&
  371. firstArg.slice(0, 9) === 'Warning: ' &&
  372. logLevel >= LOG_LEVELS.error
  373. ) {
  374. // React warnings use console.error so that a stack trace is shown,
  375. // but we don't (currently) want these to show a redbox
  376. // (Note: Logic duplicated in ExceptionsManager.js.)
  377. logLevel = LOG_LEVELS.warn;
  378. }
  379. if (global.__inspectorLog) {
  380. global.__inspectorLog(
  381. INSPECTOR_LEVELS[logLevel],
  382. str,
  383. [].slice.call(arguments),
  384. INSPECTOR_FRAMES_TO_SKIP,
  385. );
  386. }
  387. if (groupStack.length) {
  388. str = groupFormat('', str);
  389. }
  390. global.nativeLoggingHook(str, logLevel);
  391. };
  392. }
  393. function repeat(element, n) {
  394. return Array.apply(null, Array(n)).map(function() {
  395. return element;
  396. });
  397. }
  398. function consoleTablePolyfill(rows) {
  399. // convert object -> array
  400. if (!Array.isArray(rows)) {
  401. var data = rows;
  402. rows = [];
  403. for (var key in data) {
  404. if (data.hasOwnProperty(key)) {
  405. var row = data[key];
  406. row[OBJECT_COLUMN_NAME] = key;
  407. rows.push(row);
  408. }
  409. }
  410. }
  411. if (rows.length === 0) {
  412. global.nativeLoggingHook('', LOG_LEVELS.info);
  413. return;
  414. }
  415. var columns = Object.keys(rows[0]).sort();
  416. var stringRows = [];
  417. var columnWidths = [];
  418. // Convert each cell to a string. Also
  419. // figure out max cell width for each column
  420. columns.forEach(function(k, i) {
  421. columnWidths[i] = k.length;
  422. for (var j = 0; j < rows.length; j++) {
  423. var cellStr = (rows[j][k] || '?').toString();
  424. stringRows[j] = stringRows[j] || [];
  425. stringRows[j][i] = cellStr;
  426. columnWidths[i] = Math.max(columnWidths[i], cellStr.length);
  427. }
  428. });
  429. // Join all elements in the row into a single string with | separators
  430. // (appends extra spaces to each cell to make separators | aligned)
  431. function joinRow(row, space) {
  432. var cells = row.map(function(cell, i) {
  433. var extraSpaces = repeat(' ', columnWidths[i] - cell.length).join('');
  434. return cell + extraSpaces;
  435. });
  436. space = space || ' ';
  437. return cells.join(space + '|' + space);
  438. }
  439. var separators = columnWidths.map(function(columnWidth) {
  440. return repeat('-', columnWidth).join('');
  441. });
  442. var separatorRow = joinRow(separators, '-');
  443. var header = joinRow(columns);
  444. var table = [header, separatorRow];
  445. for (var i = 0; i < rows.length; i++) {
  446. table.push(joinRow(stringRows[i]));
  447. }
  448. // Notice extra empty line at the beginning.
  449. // Native logging hook adds "RCTLog >" at the front of every
  450. // logged string, which would shift the header and screw up
  451. // the table
  452. global.nativeLoggingHook('\n' + table.join('\n'), LOG_LEVELS.info);
  453. }
  454. const GROUP_PAD = '\u2502'; // Box light vertical
  455. const GROUP_OPEN = '\u2510'; // Box light down+left
  456. const GROUP_CLOSE = '\u2518'; // Box light up+left
  457. const groupStack = [];
  458. function groupFormat(prefix, msg) {
  459. // Insert group formatting before the console message
  460. return groupStack.join('') + prefix + ' ' + (msg || '');
  461. }
  462. function consoleGroupPolyfill(label) {
  463. global.nativeLoggingHook(groupFormat(GROUP_OPEN, label), LOG_LEVELS.info);
  464. groupStack.push(GROUP_PAD);
  465. }
  466. function consoleGroupCollapsedPolyfill(label) {
  467. global.nativeLoggingHook(groupFormat(GROUP_CLOSE, label), LOG_LEVELS.info);
  468. groupStack.push(GROUP_PAD);
  469. }
  470. function consoleGroupEndPolyfill() {
  471. groupStack.pop();
  472. global.nativeLoggingHook(groupFormat(GROUP_CLOSE), LOG_LEVELS.info);
  473. }
  474. function consoleAssertPolyfill(expression, label) {
  475. if (!expression) {
  476. global.nativeLoggingHook('Assertion failed: ' + label, LOG_LEVELS.error);
  477. }
  478. }
  479. if (global.nativeLoggingHook) {
  480. const originalConsole = global.console;
  481. // Preserve the original `console` as `originalConsole`
  482. if (__DEV__ && originalConsole) {
  483. const descriptor = Object.getOwnPropertyDescriptor(global, 'console');
  484. if (descriptor) {
  485. Object.defineProperty(global, 'originalConsole', descriptor);
  486. }
  487. }
  488. global.console = {
  489. error: getNativeLogFunction(LOG_LEVELS.error),
  490. info: getNativeLogFunction(LOG_LEVELS.info),
  491. log: getNativeLogFunction(LOG_LEVELS.info),
  492. warn: getNativeLogFunction(LOG_LEVELS.warn),
  493. trace: getNativeLogFunction(LOG_LEVELS.trace),
  494. debug: getNativeLogFunction(LOG_LEVELS.trace),
  495. table: consoleTablePolyfill,
  496. group: consoleGroupPolyfill,
  497. groupEnd: consoleGroupEndPolyfill,
  498. groupCollapsed: consoleGroupCollapsedPolyfill,
  499. assert: consoleAssertPolyfill,
  500. };
  501. Object.defineProperty(console, '_isPolyfilled', {
  502. value: true,
  503. enumerable: false,
  504. });
  505. // If available, also call the original `console` method since that is
  506. // sometimes useful. Ex: on OS X, this will let you see rich output in
  507. // the Safari Web Inspector console.
  508. if (__DEV__ && originalConsole) {
  509. Object.keys(console).forEach(methodName => {
  510. const reactNativeMethod = console[methodName];
  511. if (originalConsole[methodName]) {
  512. console[methodName] = function() {
  513. // TODO(T43930203): remove this special case once originalConsole.assert properly checks
  514. // the condition
  515. if (methodName === 'assert') {
  516. if (!arguments[0]) {
  517. originalConsole.assert(...arguments);
  518. }
  519. } else {
  520. originalConsole[methodName](...arguments);
  521. }
  522. reactNativeMethod.apply(console, arguments);
  523. };
  524. }
  525. });
  526. // The following methods are not supported by this polyfill but
  527. // we still should pass them to original console if they are
  528. // supported by it.
  529. ['clear', 'dir', 'dirxml', 'profile', 'profileEnd'].forEach(methodName => {
  530. if (typeof originalConsole[methodName] === 'function') {
  531. console[methodName] = function() {
  532. originalConsole[methodName](...arguments);
  533. };
  534. }
  535. });
  536. }
  537. } else if (!global.console) {
  538. function stub() {}
  539. const log = global.print || stub;
  540. global.console = {
  541. debug: log,
  542. error: log,
  543. info: log,
  544. log: log,
  545. trace: log,
  546. warn: log,
  547. assert(expression, label) {
  548. if (!expression) {
  549. log('Assertion failed: ' + label);
  550. }
  551. },
  552. clear: stub,
  553. dir: stub,
  554. dirxml: stub,
  555. group: stub,
  556. groupCollapsed: stub,
  557. groupEnd: stub,
  558. profile: stub,
  559. profileEnd: stub,
  560. table: stub,
  561. };
  562. Object.defineProperty(console, '_isPolyfilled', {
  563. value: true,
  564. enumerable: false,
  565. });
  566. }