util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. "use strict";
  2. var es5 = require("./es5");
  3. var canEvaluate = typeof navigator == "undefined";
  4. var errorObj = {e: {}};
  5. var tryCatchTarget;
  6. var globalObject = typeof self !== "undefined" ? self :
  7. typeof window !== "undefined" ? window :
  8. typeof global !== "undefined" ? global :
  9. this !== undefined ? this : null;
  10. function tryCatcher() {
  11. try {
  12. var target = tryCatchTarget;
  13. tryCatchTarget = null;
  14. return target.apply(this, arguments);
  15. } catch (e) {
  16. errorObj.e = e;
  17. return errorObj;
  18. }
  19. }
  20. function tryCatch(fn) {
  21. tryCatchTarget = fn;
  22. return tryCatcher;
  23. }
  24. var inherits = function(Child, Parent) {
  25. var hasProp = {}.hasOwnProperty;
  26. function T() {
  27. this.constructor = Child;
  28. this.constructor$ = Parent;
  29. for (var propertyName in Parent.prototype) {
  30. if (hasProp.call(Parent.prototype, propertyName) &&
  31. propertyName.charAt(propertyName.length-1) !== "$"
  32. ) {
  33. this[propertyName + "$"] = Parent.prototype[propertyName];
  34. }
  35. }
  36. }
  37. T.prototype = Parent.prototype;
  38. Child.prototype = new T();
  39. return Child.prototype;
  40. };
  41. function isPrimitive(val) {
  42. return val == null || val === true || val === false ||
  43. typeof val === "string" || typeof val === "number";
  44. }
  45. function isObject(value) {
  46. return typeof value === "function" ||
  47. typeof value === "object" && value !== null;
  48. }
  49. function maybeWrapAsError(maybeError) {
  50. if (!isPrimitive(maybeError)) return maybeError;
  51. return new Error(safeToString(maybeError));
  52. }
  53. function withAppended(target, appendee) {
  54. var len = target.length;
  55. var ret = new Array(len + 1);
  56. var i;
  57. for (i = 0; i < len; ++i) {
  58. ret[i] = target[i];
  59. }
  60. ret[i] = appendee;
  61. return ret;
  62. }
  63. function getDataPropertyOrDefault(obj, key, defaultValue) {
  64. if (es5.isES5) {
  65. var desc = Object.getOwnPropertyDescriptor(obj, key);
  66. if (desc != null) {
  67. return desc.get == null && desc.set == null
  68. ? desc.value
  69. : defaultValue;
  70. }
  71. } else {
  72. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  73. }
  74. }
  75. function notEnumerableProp(obj, name, value) {
  76. if (isPrimitive(obj)) return obj;
  77. var descriptor = {
  78. value: value,
  79. configurable: true,
  80. enumerable: false,
  81. writable: true
  82. };
  83. es5.defineProperty(obj, name, descriptor);
  84. return obj;
  85. }
  86. function thrower(r) {
  87. throw r;
  88. }
  89. var inheritedDataKeys = (function() {
  90. var excludedPrototypes = [
  91. Array.prototype,
  92. Object.prototype,
  93. Function.prototype
  94. ];
  95. var isExcludedProto = function(val) {
  96. for (var i = 0; i < excludedPrototypes.length; ++i) {
  97. if (excludedPrototypes[i] === val) {
  98. return true;
  99. }
  100. }
  101. return false;
  102. };
  103. if (es5.isES5) {
  104. var getKeys = Object.getOwnPropertyNames;
  105. return function(obj) {
  106. var ret = [];
  107. var visitedKeys = Object.create(null);
  108. while (obj != null && !isExcludedProto(obj)) {
  109. var keys;
  110. try {
  111. keys = getKeys(obj);
  112. } catch (e) {
  113. return ret;
  114. }
  115. for (var i = 0; i < keys.length; ++i) {
  116. var key = keys[i];
  117. if (visitedKeys[key]) continue;
  118. visitedKeys[key] = true;
  119. var desc = Object.getOwnPropertyDescriptor(obj, key);
  120. if (desc != null && desc.get == null && desc.set == null) {
  121. ret.push(key);
  122. }
  123. }
  124. obj = es5.getPrototypeOf(obj);
  125. }
  126. return ret;
  127. };
  128. } else {
  129. var hasProp = {}.hasOwnProperty;
  130. return function(obj) {
  131. if (isExcludedProto(obj)) return [];
  132. var ret = [];
  133. /*jshint forin:false */
  134. enumeration: for (var key in obj) {
  135. if (hasProp.call(obj, key)) {
  136. ret.push(key);
  137. } else {
  138. for (var i = 0; i < excludedPrototypes.length; ++i) {
  139. if (hasProp.call(excludedPrototypes[i], key)) {
  140. continue enumeration;
  141. }
  142. }
  143. ret.push(key);
  144. }
  145. }
  146. return ret;
  147. };
  148. }
  149. })();
  150. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  151. function isClass(fn) {
  152. try {
  153. if (typeof fn === "function") {
  154. var keys = es5.names(fn.prototype);
  155. var hasMethods = es5.isES5 && keys.length > 1;
  156. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  157. !(keys.length === 1 && keys[0] === "constructor");
  158. var hasThisAssignmentAndStaticMethods =
  159. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  160. if (hasMethods || hasMethodsOtherThanConstructor ||
  161. hasThisAssignmentAndStaticMethods) {
  162. return true;
  163. }
  164. }
  165. return false;
  166. } catch (e) {
  167. return false;
  168. }
  169. }
  170. function toFastProperties(obj) {
  171. /*jshint -W027,-W055,-W031*/
  172. function FakeConstructor() {}
  173. FakeConstructor.prototype = obj;
  174. var receiver = new FakeConstructor();
  175. function ic() {
  176. return typeof receiver.foo;
  177. }
  178. ic();
  179. ic();
  180. return obj;
  181. eval(obj);
  182. }
  183. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  184. function isIdentifier(str) {
  185. return rident.test(str);
  186. }
  187. function filledRange(count, prefix, suffix) {
  188. var ret = new Array(count);
  189. for(var i = 0; i < count; ++i) {
  190. ret[i] = prefix + i + suffix;
  191. }
  192. return ret;
  193. }
  194. function safeToString(obj) {
  195. try {
  196. return obj + "";
  197. } catch (e) {
  198. return "[no string representation]";
  199. }
  200. }
  201. function isError(obj) {
  202. return obj instanceof Error ||
  203. (obj !== null &&
  204. typeof obj === "object" &&
  205. typeof obj.message === "string" &&
  206. typeof obj.name === "string");
  207. }
  208. function markAsOriginatingFromRejection(e) {
  209. try {
  210. notEnumerableProp(e, "isOperational", true);
  211. }
  212. catch(ignore) {}
  213. }
  214. function originatesFromRejection(e) {
  215. if (e == null) return false;
  216. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  217. e["isOperational"] === true);
  218. }
  219. function canAttachTrace(obj) {
  220. return isError(obj) && es5.propertyIsWritable(obj, "stack");
  221. }
  222. var ensureErrorObject = (function() {
  223. if (!("stack" in new Error())) {
  224. return function(value) {
  225. if (canAttachTrace(value)) return value;
  226. try {throw new Error(safeToString(value));}
  227. catch(err) {return err;}
  228. };
  229. } else {
  230. return function(value) {
  231. if (canAttachTrace(value)) return value;
  232. return new Error(safeToString(value));
  233. };
  234. }
  235. })();
  236. function classString(obj) {
  237. return {}.toString.call(obj);
  238. }
  239. function copyDescriptors(from, to, filter) {
  240. var keys = es5.names(from);
  241. for (var i = 0; i < keys.length; ++i) {
  242. var key = keys[i];
  243. if (filter(key)) {
  244. try {
  245. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  246. } catch (ignore) {}
  247. }
  248. }
  249. }
  250. var asArray = function(v) {
  251. if (es5.isArray(v)) {
  252. return v;
  253. }
  254. return null;
  255. };
  256. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  257. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  258. return Array.from(v);
  259. } : function(v) {
  260. var ret = [];
  261. var it = v[Symbol.iterator]();
  262. var itResult;
  263. while (!((itResult = it.next()).done)) {
  264. ret.push(itResult.value);
  265. }
  266. return ret;
  267. };
  268. asArray = function(v) {
  269. if (es5.isArray(v)) {
  270. return v;
  271. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  272. return ArrayFrom(v);
  273. }
  274. return null;
  275. };
  276. }
  277. var isNode = typeof process !== "undefined" &&
  278. classString(process).toLowerCase() === "[object process]";
  279. var hasEnvVariables = typeof process !== "undefined" &&
  280. typeof process.env !== "undefined";
  281. function env(key) {
  282. return hasEnvVariables ? process.env[key] : undefined;
  283. }
  284. function getNativePromise() {
  285. if (typeof Promise === "function") {
  286. try {
  287. var promise = new Promise(function(){});
  288. if (classString(promise) === "[object Promise]") {
  289. return Promise;
  290. }
  291. } catch (e) {}
  292. }
  293. }
  294. var reflectHandler;
  295. function contextBind(ctx, cb) {
  296. if (ctx === null ||
  297. typeof cb !== "function" ||
  298. cb === reflectHandler) {
  299. return cb;
  300. }
  301. if (ctx.domain !== null) {
  302. cb = ctx.domain.bind(cb);
  303. }
  304. var async = ctx.async;
  305. if (async !== null) {
  306. var old = cb;
  307. cb = function() {
  308. var $_len = arguments.length + 2;var args = new Array($_len); for(var $_i = 2; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i - 2];};
  309. args[0] = old;
  310. args[1] = this;
  311. return async.runInAsyncScope.apply(async, args);
  312. };
  313. }
  314. return cb;
  315. }
  316. var ret = {
  317. setReflectHandler: function(fn) {
  318. reflectHandler = fn;
  319. },
  320. isClass: isClass,
  321. isIdentifier: isIdentifier,
  322. inheritedDataKeys: inheritedDataKeys,
  323. getDataPropertyOrDefault: getDataPropertyOrDefault,
  324. thrower: thrower,
  325. isArray: es5.isArray,
  326. asArray: asArray,
  327. notEnumerableProp: notEnumerableProp,
  328. isPrimitive: isPrimitive,
  329. isObject: isObject,
  330. isError: isError,
  331. canEvaluate: canEvaluate,
  332. errorObj: errorObj,
  333. tryCatch: tryCatch,
  334. inherits: inherits,
  335. withAppended: withAppended,
  336. maybeWrapAsError: maybeWrapAsError,
  337. toFastProperties: toFastProperties,
  338. filledRange: filledRange,
  339. toString: safeToString,
  340. canAttachTrace: canAttachTrace,
  341. ensureErrorObject: ensureErrorObject,
  342. originatesFromRejection: originatesFromRejection,
  343. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  344. classString: classString,
  345. copyDescriptors: copyDescriptors,
  346. isNode: isNode,
  347. hasEnvVariables: hasEnvVariables,
  348. env: env,
  349. global: globalObject,
  350. getNativePromise: getNativePromise,
  351. contextBind: contextBind
  352. };
  353. ret.isRecentNode = ret.isNode && (function() {
  354. var version;
  355. if (process.versions && process.versions.node) {
  356. version = process.versions.node.split(".").map(Number);
  357. } else if (process.version) {
  358. version = process.version.split(".").map(Number);
  359. }
  360. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  361. })();
  362. ret.nodeSupportsAsyncResource = ret.isNode && (function() {
  363. var supportsAsync = false;
  364. try {
  365. var res = require("async_hooks").AsyncResource;
  366. supportsAsync = typeof res.prototype.runInAsyncScope === "function";
  367. } catch (e) {
  368. supportsAsync = false;
  369. }
  370. return supportsAsync;
  371. })();
  372. if (ret.isNode) ret.toFastProperties(process);
  373. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  374. module.exports = ret;