devalue.cjs.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. 'use strict';
  2. var consola = require('consola');
  3. var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  4. var unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
  5. var reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
  6. var escaped = {
  7. '<': '\\u003C',
  8. '>': '\\u003E',
  9. '/': '\\u002F',
  10. '\\': '\\\\',
  11. '\b': '\\b',
  12. '\f': '\\f',
  13. '\n': '\\n',
  14. '\r': '\\r',
  15. '\t': '\\t',
  16. '\0': '\\0',
  17. '\u2028': '\\u2028',
  18. '\u2029': '\\u2029'
  19. };
  20. var objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join('\0');
  21. // workaround to disable warnings, see https://github.com/nuxt/nuxt.js/issues/4026 for details
  22. var defaultLogLevel = process.env.NUXT_ENV_DEVALUE_LOG_LEVEL || 'warn';
  23. var logLimit = parseInt(process.env.NUXT_ENV_DEVALUE_LOG_LIMIT) || 99;
  24. function devalue(value, level) {
  25. if (level === void 0) { level = defaultLogLevel; }
  26. var counts = new Map();
  27. var logNum = 0;
  28. function log(message) {
  29. if (logNum < logLimit) {
  30. consola[level](message);
  31. logNum += 1;
  32. }
  33. }
  34. function walk(thing) {
  35. if (typeof thing === 'function') {
  36. consola[level]("Cannot stringify a function " + thing.name);
  37. return;
  38. }
  39. if (counts.has(thing)) {
  40. counts.set(thing, counts.get(thing) + 1);
  41. return;
  42. }
  43. counts.set(thing, 1);
  44. if (!isPrimitive(thing)) {
  45. var type = getType(thing);
  46. switch (type) {
  47. case 'Number':
  48. case 'String':
  49. case 'Boolean':
  50. case 'Date':
  51. case 'RegExp':
  52. return;
  53. case 'Array':
  54. thing.forEach(walk);
  55. break;
  56. case 'Set':
  57. case 'Map':
  58. Array.from(thing).forEach(walk);
  59. break;
  60. default:
  61. var proto = Object.getPrototypeOf(thing);
  62. if (proto !== Object.prototype &&
  63. proto !== null &&
  64. Object.getOwnPropertyNames(proto).sort().join('\0') !== objectProtoOwnPropertyNames) {
  65. if (typeof thing.toJSON !== "function") {
  66. log("Cannot stringify arbitrary non-POJOs " + thing.constructor.name);
  67. }
  68. }
  69. else if (Object.getOwnPropertySymbols(thing).length > 0) {
  70. log("Cannot stringify POJOs with symbolic keys " + Object.getOwnPropertySymbols(thing).map(function (symbol) { return symbol.toString(); }));
  71. }
  72. else {
  73. Object.keys(thing).forEach(function (key) { return walk(thing[key]); });
  74. }
  75. }
  76. }
  77. }
  78. walk(value);
  79. var names = new Map();
  80. Array.from(counts)
  81. .filter(function (entry) { return entry[1] > 1; })
  82. .sort(function (a, b) { return b[1] - a[1]; })
  83. .forEach(function (entry, i) {
  84. names.set(entry[0], getName(i));
  85. });
  86. function stringify(thing) {
  87. if (names.has(thing)) {
  88. return names.get(thing);
  89. }
  90. if (isPrimitive(thing)) {
  91. return stringifyPrimitive(thing);
  92. }
  93. var type = getType(thing);
  94. switch (type) {
  95. case 'Number':
  96. case 'String':
  97. case 'Boolean':
  98. return "Object(" + stringify(thing.valueOf()) + ")";
  99. case 'RegExp':
  100. return thing.toString();
  101. case 'Date':
  102. return "new Date(" + thing.getTime() + ")";
  103. case 'Array':
  104. var members = thing.map(function (v, i) { return i in thing ? stringify(v) : ''; });
  105. var tail = thing.length === 0 || (thing.length - 1 in thing) ? '' : ',';
  106. return "[" + members.join(',') + tail + "]";
  107. case 'Set':
  108. case 'Map':
  109. return "new " + type + "([" + Array.from(thing).map(stringify).join(',') + "])";
  110. default:
  111. if (thing.toJSON) {
  112. var json = thing.toJSON();
  113. if (getType(json) === 'String') {
  114. // Try to parse the returned data
  115. try {
  116. json = JSON.parse(json);
  117. }
  118. catch (e) { }
  119. }
  120. return stringify(json);
  121. }
  122. if (Object.getPrototypeOf(thing) === null) {
  123. if (Object.keys(thing).length === 0) {
  124. return 'Object.create(null)';
  125. }
  126. return "Object.create(null,{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":{writable:true,enumerable:true,value:" + stringify(thing[key]) + "}"; }).join(',') + "})";
  127. }
  128. return "{" + Object.keys(thing).map(function (key) { return safeKey(key) + ":" + stringify(thing[key]); }).join(',') + "}";
  129. }
  130. }
  131. var str = stringify(value);
  132. if (names.size) {
  133. var params_1 = [];
  134. var statements_1 = [];
  135. var values_1 = [];
  136. names.forEach(function (name, thing) {
  137. params_1.push(name);
  138. if (isPrimitive(thing)) {
  139. values_1.push(stringifyPrimitive(thing));
  140. return;
  141. }
  142. var type = getType(thing);
  143. switch (type) {
  144. case 'Number':
  145. case 'String':
  146. case 'Boolean':
  147. values_1.push("Object(" + stringify(thing.valueOf()) + ")");
  148. break;
  149. case 'RegExp':
  150. values_1.push(thing.toString());
  151. break;
  152. case 'Date':
  153. values_1.push("new Date(" + thing.getTime() + ")");
  154. break;
  155. case 'Array':
  156. values_1.push("Array(" + thing.length + ")");
  157. thing.forEach(function (v, i) {
  158. statements_1.push(name + "[" + i + "]=" + stringify(v));
  159. });
  160. break;
  161. case 'Set':
  162. values_1.push("new Set");
  163. statements_1.push(name + "." + Array.from(thing).map(function (v) { return "add(" + stringify(v) + ")"; }).join('.'));
  164. break;
  165. case 'Map':
  166. values_1.push("new Map");
  167. statements_1.push(name + "." + Array.from(thing).map(function (_a) {
  168. var k = _a[0], v = _a[1];
  169. return "set(" + stringify(k) + ", " + stringify(v) + ")";
  170. }).join('.'));
  171. break;
  172. default:
  173. values_1.push(Object.getPrototypeOf(thing) === null ? 'Object.create(null)' : '{}');
  174. Object.keys(thing).forEach(function (key) {
  175. statements_1.push("" + name + safeProp(key) + "=" + stringify(thing[key]));
  176. });
  177. }
  178. });
  179. statements_1.push("return " + str);
  180. return "(function(" + params_1.join(',') + "){" + statements_1.join(';') + "}(" + values_1.join(',') + "))";
  181. }
  182. else {
  183. return str;
  184. }
  185. }
  186. function getName(num) {
  187. var name = '';
  188. do {
  189. name = chars[num % chars.length] + name;
  190. num = ~~(num / chars.length) - 1;
  191. } while (num >= 0);
  192. return reserved.test(name) ? name + "0" : name;
  193. }
  194. function isPrimitive(thing) {
  195. return Object(thing) !== thing;
  196. }
  197. function stringifyPrimitive(thing) {
  198. if (typeof thing === 'string')
  199. return stringifyString(thing);
  200. if (thing === void 0)
  201. return 'void 0';
  202. if (thing === 0 && 1 / thing < 0)
  203. return '-0';
  204. var str = String(thing);
  205. if (typeof thing === 'number')
  206. return str.replace(/^(-)?0\./, '$1.');
  207. return str;
  208. }
  209. function getType(thing) {
  210. return Object.prototype.toString.call(thing).slice(8, -1);
  211. }
  212. function escapeUnsafeChar(c) {
  213. return escaped[c] || c;
  214. }
  215. function escapeUnsafeChars(str) {
  216. return str.replace(unsafeChars, escapeUnsafeChar);
  217. }
  218. function safeKey(key) {
  219. return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify((key)));
  220. }
  221. function safeProp(key) {
  222. return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? "." + key : "[" + escapeUnsafeChars(JSON.stringify(key)) + "]";
  223. }
  224. function stringifyString(str) {
  225. var result = '"';
  226. for (var i = 0; i < str.length; i += 1) {
  227. var char = str.charAt(i);
  228. var code = char.charCodeAt(0);
  229. if (char === '"') {
  230. result += '\\"';
  231. }
  232. else if (char in escaped) {
  233. result += escaped[char];
  234. }
  235. else if (code >= 0xd800 && code <= 0xdfff) {
  236. var next = str.charCodeAt(i + 1);
  237. // If this is the beginning of a [high, low] surrogate pair,
  238. // add the next two characters, otherwise escape
  239. if (code <= 0xdbff && (next >= 0xdc00 && next <= 0xdfff)) {
  240. result += char + str[++i];
  241. }
  242. else {
  243. result += "\\u" + code.toString(16).toUpperCase();
  244. }
  245. }
  246. else {
  247. result += char;
  248. }
  249. }
  250. result += '"';
  251. return result;
  252. }
  253. module.exports = devalue;