index.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. module.exports = (function() {
  2. var __MODS__ = {};
  3. var __DEFINE__ = function(modId, func, req) { var m = { exports: {}, _tempexports: {} }; __MODS__[modId] = { status: 0, func: func, req: req, m: m }; };
  4. var __REQUIRE__ = function(modId, source) { if(!__MODS__[modId]) return require(source); if(!__MODS__[modId].status) { var m = __MODS__[modId].m; m._exports = m._tempexports; var desp = Object.getOwnPropertyDescriptor(m, "exports"); if (desp && desp.configurable) Object.defineProperty(m, "exports", { set: function (val) { if(typeof val === "object" && val !== m._exports) { m._exports.__proto__ = val.__proto__; Object.keys(val).forEach(function (k) { m._exports[k] = val[k]; }); } m._tempexports = val }, get: function () { return m._tempexports; } }); __MODS__[modId].status = 1; __MODS__[modId].func(__MODS__[modId].req, m, m.exports); } return __MODS__[modId].m.exports; };
  5. var __REQUIRE_WILDCARD__ = function(obj) { if(obj && obj.__esModule) { return obj; } else { var newObj = {}; if(obj != null) { for(var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) newObj[k] = obj[k]; } } newObj.default = obj; return newObj; } };
  6. var __REQUIRE_DEFAULT__ = function(obj) { return obj && obj.__esModule ? obj.default : obj; };
  7. __DEFINE__(1710576073078, function(require, module, exports) {
  8. Object.defineProperty(exports, '__esModule', { value: true });
  9. function _extends() {
  10. _extends = Object.assign ? Object.assign.bind() : function (target) {
  11. for (var i = 1; i < arguments.length; i++) {
  12. var source = arguments[i];
  13. for (var key in source) {
  14. if (Object.prototype.hasOwnProperty.call(source, key)) {
  15. target[key] = source[key];
  16. }
  17. }
  18. }
  19. return target;
  20. };
  21. return _extends.apply(this, arguments);
  22. }
  23. function _inheritsLoose(subClass, superClass) {
  24. subClass.prototype = Object.create(superClass.prototype);
  25. subClass.prototype.constructor = subClass;
  26. _setPrototypeOf(subClass, superClass);
  27. }
  28. function _getPrototypeOf(o) {
  29. _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
  30. return o.__proto__ || Object.getPrototypeOf(o);
  31. };
  32. return _getPrototypeOf(o);
  33. }
  34. function _setPrototypeOf(o, p) {
  35. _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  36. o.__proto__ = p;
  37. return o;
  38. };
  39. return _setPrototypeOf(o, p);
  40. }
  41. function _isNativeReflectConstruct() {
  42. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  43. if (Reflect.construct.sham) return false;
  44. if (typeof Proxy === "function") return true;
  45. try {
  46. Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  47. return true;
  48. } catch (e) {
  49. return false;
  50. }
  51. }
  52. function _construct(Parent, args, Class) {
  53. if (_isNativeReflectConstruct()) {
  54. _construct = Reflect.construct.bind();
  55. } else {
  56. _construct = function _construct(Parent, args, Class) {
  57. var a = [null];
  58. a.push.apply(a, args);
  59. var Constructor = Function.bind.apply(Parent, a);
  60. var instance = new Constructor();
  61. if (Class) _setPrototypeOf(instance, Class.prototype);
  62. return instance;
  63. };
  64. }
  65. return _construct.apply(null, arguments);
  66. }
  67. function _isNativeFunction(fn) {
  68. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  69. }
  70. function _wrapNativeSuper(Class) {
  71. var _cache = typeof Map === "function" ? new Map() : undefined;
  72. _wrapNativeSuper = function _wrapNativeSuper(Class) {
  73. if (Class === null || !_isNativeFunction(Class)) return Class;
  74. if (typeof Class !== "function") {
  75. throw new TypeError("Super expression must either be null or a function");
  76. }
  77. if (typeof _cache !== "undefined") {
  78. if (_cache.has(Class)) return _cache.get(Class);
  79. _cache.set(Class, Wrapper);
  80. }
  81. function Wrapper() {
  82. return _construct(Class, arguments, _getPrototypeOf(this).constructor);
  83. }
  84. Wrapper.prototype = Object.create(Class.prototype, {
  85. constructor: {
  86. value: Wrapper,
  87. enumerable: false,
  88. writable: true,
  89. configurable: true
  90. }
  91. });
  92. return _setPrototypeOf(Wrapper, Class);
  93. };
  94. return _wrapNativeSuper(Class);
  95. }
  96. /* eslint no-console:0 */
  97. var formatRegExp = /%[sdj%]/g;
  98. var warning = function warning() {}; // don't print warning message when in production env or node runtime
  99. if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production' && typeof window !== 'undefined' && typeof document !== 'undefined') {
  100. warning = function warning(type, errors) {
  101. if (typeof console !== 'undefined' && console.warn && typeof ASYNC_VALIDATOR_NO_WARNING === 'undefined') {
  102. if (errors.every(function (e) {
  103. return typeof e === 'string';
  104. })) {
  105. console.warn(type, errors);
  106. }
  107. }
  108. };
  109. }
  110. function convertFieldsError(errors) {
  111. if (!errors || !errors.length) return null;
  112. var fields = {};
  113. errors.forEach(function (error) {
  114. var field = error.field;
  115. fields[field] = fields[field] || [];
  116. fields[field].push(error);
  117. });
  118. return fields;
  119. }
  120. function format(template) {
  121. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  122. args[_key - 1] = arguments[_key];
  123. }
  124. var i = 0;
  125. var len = args.length;
  126. if (typeof template === 'function') {
  127. return template.apply(null, args);
  128. }
  129. if (typeof template === 'string') {
  130. var str = template.replace(formatRegExp, function (x) {
  131. if (x === '%%') {
  132. return '%';
  133. }
  134. if (i >= len) {
  135. return x;
  136. }
  137. switch (x) {
  138. case '%s':
  139. return String(args[i++]);
  140. case '%d':
  141. return Number(args[i++]);
  142. case '%j':
  143. try {
  144. return JSON.stringify(args[i++]);
  145. } catch (_) {
  146. return '[Circular]';
  147. }
  148. break;
  149. default:
  150. return x;
  151. }
  152. });
  153. return str;
  154. }
  155. return template;
  156. }
  157. function isNativeStringType(type) {
  158. return type === 'string' || type === 'url' || type === 'hex' || type === 'email' || type === 'date' || type === 'pattern';
  159. }
  160. function isEmptyValue(value, type) {
  161. if (value === undefined || value === null) {
  162. return true;
  163. }
  164. if (type === 'array' && Array.isArray(value) && !value.length) {
  165. return true;
  166. }
  167. if (isNativeStringType(type) && typeof value === 'string' && !value) {
  168. return true;
  169. }
  170. return false;
  171. }
  172. function asyncParallelArray(arr, func, callback) {
  173. var results = [];
  174. var total = 0;
  175. var arrLength = arr.length;
  176. function count(errors) {
  177. results.push.apply(results, errors || []);
  178. total++;
  179. if (total === arrLength) {
  180. callback(results);
  181. }
  182. }
  183. arr.forEach(function (a) {
  184. func(a, count);
  185. });
  186. }
  187. function asyncSerialArray(arr, func, callback) {
  188. var index = 0;
  189. var arrLength = arr.length;
  190. function next(errors) {
  191. if (errors && errors.length) {
  192. callback(errors);
  193. return;
  194. }
  195. var original = index;
  196. index = index + 1;
  197. if (original < arrLength) {
  198. func(arr[original], next);
  199. } else {
  200. callback([]);
  201. }
  202. }
  203. next([]);
  204. }
  205. function flattenObjArr(objArr) {
  206. var ret = [];
  207. Object.keys(objArr).forEach(function (k) {
  208. ret.push.apply(ret, objArr[k] || []);
  209. });
  210. return ret;
  211. }
  212. var AsyncValidationError = /*#__PURE__*/function (_Error) {
  213. _inheritsLoose(AsyncValidationError, _Error);
  214. function AsyncValidationError(errors, fields) {
  215. var _this;
  216. _this = _Error.call(this, 'Async Validation Error') || this;
  217. _this.errors = errors;
  218. _this.fields = fields;
  219. return _this;
  220. }
  221. return AsyncValidationError;
  222. }( /*#__PURE__*/_wrapNativeSuper(Error));
  223. function asyncMap(objArr, option, func, callback, source) {
  224. if (option.first) {
  225. var _pending = new Promise(function (resolve, reject) {
  226. var next = function next(errors) {
  227. callback(errors);
  228. return errors.length ? reject(new AsyncValidationError(errors, convertFieldsError(errors))) : resolve(source);
  229. };
  230. var flattenArr = flattenObjArr(objArr);
  231. asyncSerialArray(flattenArr, func, next);
  232. });
  233. _pending["catch"](function (e) {
  234. return e;
  235. });
  236. return _pending;
  237. }
  238. var firstFields = option.firstFields === true ? Object.keys(objArr) : option.firstFields || [];
  239. var objArrKeys = Object.keys(objArr);
  240. var objArrLength = objArrKeys.length;
  241. var total = 0;
  242. var results = [];
  243. var pending = new Promise(function (resolve, reject) {
  244. var next = function next(errors) {
  245. results.push.apply(results, errors);
  246. total++;
  247. if (total === objArrLength) {
  248. callback(results);
  249. return results.length ? reject(new AsyncValidationError(results, convertFieldsError(results))) : resolve(source);
  250. }
  251. };
  252. if (!objArrKeys.length) {
  253. callback(results);
  254. resolve(source);
  255. }
  256. objArrKeys.forEach(function (key) {
  257. var arr = objArr[key];
  258. if (firstFields.indexOf(key) !== -1) {
  259. asyncSerialArray(arr, func, next);
  260. } else {
  261. asyncParallelArray(arr, func, next);
  262. }
  263. });
  264. });
  265. pending["catch"](function (e) {
  266. return e;
  267. });
  268. return pending;
  269. }
  270. function isErrorObj(obj) {
  271. return !!(obj && obj.message !== undefined);
  272. }
  273. function getValue(value, path) {
  274. var v = value;
  275. for (var i = 0; i < path.length; i++) {
  276. if (v == undefined) {
  277. return v;
  278. }
  279. v = v[path[i]];
  280. }
  281. return v;
  282. }
  283. function complementError(rule, source) {
  284. return function (oe) {
  285. var fieldValue;
  286. if (rule.fullFields) {
  287. fieldValue = getValue(source, rule.fullFields);
  288. } else {
  289. fieldValue = source[oe.field || rule.fullField];
  290. }
  291. if (isErrorObj(oe)) {
  292. oe.field = oe.field || rule.fullField;
  293. oe.fieldValue = fieldValue;
  294. return oe;
  295. }
  296. return {
  297. message: typeof oe === 'function' ? oe() : oe,
  298. fieldValue: fieldValue,
  299. field: oe.field || rule.fullField
  300. };
  301. };
  302. }
  303. function deepMerge(target, source) {
  304. if (source) {
  305. for (var s in source) {
  306. if (source.hasOwnProperty(s)) {
  307. var value = source[s];
  308. if (typeof value === 'object' && typeof target[s] === 'object') {
  309. target[s] = _extends({}, target[s], value);
  310. } else {
  311. target[s] = value;
  312. }
  313. }
  314. }
  315. }
  316. return target;
  317. }
  318. var required$1 = function required(rule, value, source, errors, options, type) {
  319. if (rule.required && (!source.hasOwnProperty(rule.field) || isEmptyValue(value, type || rule.type))) {
  320. errors.push(format(options.messages.required, rule.fullField));
  321. }
  322. };
  323. /**
  324. * Rule for validating whitespace.
  325. *
  326. * @param rule The validation rule.
  327. * @param value The value of the field on the source object.
  328. * @param source The source object being validated.
  329. * @param errors An array of errors that this rule may add
  330. * validation errors to.
  331. * @param options The validation options.
  332. * @param options.messages The validation messages.
  333. */
  334. var whitespace = function whitespace(rule, value, source, errors, options) {
  335. if (/^\s+$/.test(value) || value === '') {
  336. errors.push(format(options.messages.whitespace, rule.fullField));
  337. }
  338. };
  339. // https://github.com/kevva/url-regex/blob/master/index.js
  340. var urlReg;
  341. var getUrlRegex = (function () {
  342. if (urlReg) {
  343. return urlReg;
  344. }
  345. var word = '[a-fA-F\\d:]';
  346. var b = function b(options) {
  347. return options && options.includeBoundaries ? "(?:(?<=\\s|^)(?=" + word + ")|(?<=" + word + ")(?=\\s|$))" : '';
  348. };
  349. var v4 = '(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}';
  350. var v6seg = '[a-fA-F\\d]{1,4}';
  351. var v6 = ("\n(?:\n(?:" + v6seg + ":){7}(?:" + v6seg + "|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:" + v6seg + ":){6}(?:" + v4 + "|:" + v6seg + "|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:" + v6seg + ":){5}(?::" + v4 + "|(?::" + v6seg + "){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:" + v6seg + ":){4}(?:(?::" + v6seg + "){0,1}:" + v4 + "|(?::" + v6seg + "){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:" + v6seg + ":){3}(?:(?::" + v6seg + "){0,2}:" + v4 + "|(?::" + v6seg + "){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:" + v6seg + ":){2}(?:(?::" + v6seg + "){0,3}:" + v4 + "|(?::" + v6seg + "){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:" + v6seg + ":){1}(?:(?::" + v6seg + "){0,4}:" + v4 + "|(?::" + v6seg + "){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::" + v6seg + "){0,5}:" + v4 + "|(?::" + v6seg + "){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm, '').replace(/\n/g, '').trim(); // Pre-compile only the exact regexes because adding a global flag make regexes stateful
  352. var v46Exact = new RegExp("(?:^" + v4 + "$)|(?:^" + v6 + "$)");
  353. var v4exact = new RegExp("^" + v4 + "$");
  354. var v6exact = new RegExp("^" + v6 + "$");
  355. var ip = function ip(options) {
  356. return options && options.exact ? v46Exact : new RegExp("(?:" + b(options) + v4 + b(options) + ")|(?:" + b(options) + v6 + b(options) + ")", 'g');
  357. };
  358. ip.v4 = function (options) {
  359. return options && options.exact ? v4exact : new RegExp("" + b(options) + v4 + b(options), 'g');
  360. };
  361. ip.v6 = function (options) {
  362. return options && options.exact ? v6exact : new RegExp("" + b(options) + v6 + b(options), 'g');
  363. };
  364. var protocol = "(?:(?:[a-z]+:)?//)";
  365. var auth = '(?:\\S+(?::\\S*)?@)?';
  366. var ipv4 = ip.v4().source;
  367. var ipv6 = ip.v6().source;
  368. var host = "(?:(?:[a-z\\u00a1-\\uffff0-9][-_]*)*[a-z\\u00a1-\\uffff0-9]+)";
  369. var domain = "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*";
  370. var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
  371. var port = '(?::\\d{2,5})?';
  372. var path = '(?:[/?#][^\\s"]*)?';
  373. var regex = "(?:" + protocol + "|www\\.)" + auth + "(?:localhost|" + ipv4 + "|" + ipv6 + "|" + host + domain + tld + ")" + port + path;
  374. urlReg = new RegExp("(?:^" + regex + "$)", 'i');
  375. return urlReg;
  376. });
  377. /* eslint max-len:0 */
  378. var pattern$2 = {
  379. // http://emailregex.com/
  380. email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+\.)+[a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{2,}))$/,
  381. // url: new RegExp(
  382. // '^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
  383. // 'i',
  384. // ),
  385. hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i
  386. };
  387. var types = {
  388. integer: function integer(value) {
  389. return types.number(value) && parseInt(value, 10) === value;
  390. },
  391. "float": function float(value) {
  392. return types.number(value) && !types.integer(value);
  393. },
  394. array: function array(value) {
  395. return Array.isArray(value);
  396. },
  397. regexp: function regexp(value) {
  398. if (value instanceof RegExp) {
  399. return true;
  400. }
  401. try {
  402. return !!new RegExp(value);
  403. } catch (e) {
  404. return false;
  405. }
  406. },
  407. date: function date(value) {
  408. return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear === 'function' && !isNaN(value.getTime());
  409. },
  410. number: function number(value) {
  411. if (isNaN(value)) {
  412. return false;
  413. }
  414. return typeof value === 'number';
  415. },
  416. object: function object(value) {
  417. return typeof value === 'object' && !types.array(value);
  418. },
  419. method: function method(value) {
  420. return typeof value === 'function';
  421. },
  422. email: function email(value) {
  423. return typeof value === 'string' && value.length <= 320 && !!value.match(pattern$2.email);
  424. },
  425. url: function url(value) {
  426. return typeof value === 'string' && value.length <= 2048 && !!value.match(getUrlRegex());
  427. },
  428. hex: function hex(value) {
  429. return typeof value === 'string' && !!value.match(pattern$2.hex);
  430. }
  431. };
  432. var type$1 = function type(rule, value, source, errors, options) {
  433. if (rule.required && value === undefined) {
  434. required$1(rule, value, source, errors, options);
  435. return;
  436. }
  437. var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex'];
  438. var ruleType = rule.type;
  439. if (custom.indexOf(ruleType) > -1) {
  440. if (!types[ruleType](value)) {
  441. errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
  442. } // straight typeof check
  443. } else if (ruleType && typeof value !== rule.type) {
  444. errors.push(format(options.messages.types[ruleType], rule.fullField, rule.type));
  445. }
  446. };
  447. var range = function range(rule, value, source, errors, options) {
  448. var len = typeof rule.len === 'number';
  449. var min = typeof rule.min === 'number';
  450. var max = typeof rule.max === 'number'; // 正则匹配码点范围从U+010000一直到U+10FFFF的文字(补充平面Supplementary Plane)
  451. var spRegexp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
  452. var val = value;
  453. var key = null;
  454. var num = typeof value === 'number';
  455. var str = typeof value === 'string';
  456. var arr = Array.isArray(value);
  457. if (num) {
  458. key = 'number';
  459. } else if (str) {
  460. key = 'string';
  461. } else if (arr) {
  462. key = 'array';
  463. } // if the value is not of a supported type for range validation
  464. // the validation rule rule should use the
  465. // type property to also test for a particular type
  466. if (!key) {
  467. return false;
  468. }
  469. if (arr) {
  470. val = value.length;
  471. }
  472. if (str) {
  473. // 处理码点大于U+010000的文字length属性不准确的bug,如"𠮷𠮷𠮷".lenght !== 3
  474. val = value.replace(spRegexp, '_').length;
  475. }
  476. if (len) {
  477. if (val !== rule.len) {
  478. errors.push(format(options.messages[key].len, rule.fullField, rule.len));
  479. }
  480. } else if (min && !max && val < rule.min) {
  481. errors.push(format(options.messages[key].min, rule.fullField, rule.min));
  482. } else if (max && !min && val > rule.max) {
  483. errors.push(format(options.messages[key].max, rule.fullField, rule.max));
  484. } else if (min && max && (val < rule.min || val > rule.max)) {
  485. errors.push(format(options.messages[key].range, rule.fullField, rule.min, rule.max));
  486. }
  487. };
  488. var ENUM$1 = 'enum';
  489. var enumerable$1 = function enumerable(rule, value, source, errors, options) {
  490. rule[ENUM$1] = Array.isArray(rule[ENUM$1]) ? rule[ENUM$1] : [];
  491. if (rule[ENUM$1].indexOf(value) === -1) {
  492. errors.push(format(options.messages[ENUM$1], rule.fullField, rule[ENUM$1].join(', ')));
  493. }
  494. };
  495. var pattern$1 = function pattern(rule, value, source, errors, options) {
  496. if (rule.pattern) {
  497. if (rule.pattern instanceof RegExp) {
  498. // if a RegExp instance is passed, reset `lastIndex` in case its `global`
  499. // flag is accidentally set to `true`, which in a validation scenario
  500. // is not necessary and the result might be misleading
  501. rule.pattern.lastIndex = 0;
  502. if (!rule.pattern.test(value)) {
  503. errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  504. }
  505. } else if (typeof rule.pattern === 'string') {
  506. var _pattern = new RegExp(rule.pattern);
  507. if (!_pattern.test(value)) {
  508. errors.push(format(options.messages.pattern.mismatch, rule.fullField, value, rule.pattern));
  509. }
  510. }
  511. }
  512. };
  513. var rules = {
  514. required: required$1,
  515. whitespace: whitespace,
  516. type: type$1,
  517. range: range,
  518. "enum": enumerable$1,
  519. pattern: pattern$1
  520. };
  521. var string = function string(rule, value, callback, source, options) {
  522. var errors = [];
  523. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  524. if (validate) {
  525. if (isEmptyValue(value, 'string') && !rule.required) {
  526. return callback();
  527. }
  528. rules.required(rule, value, source, errors, options, 'string');
  529. if (!isEmptyValue(value, 'string')) {
  530. rules.type(rule, value, source, errors, options);
  531. rules.range(rule, value, source, errors, options);
  532. rules.pattern(rule, value, source, errors, options);
  533. if (rule.whitespace === true) {
  534. rules.whitespace(rule, value, source, errors, options);
  535. }
  536. }
  537. }
  538. callback(errors);
  539. };
  540. var method = function method(rule, value, callback, source, options) {
  541. var errors = [];
  542. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  543. if (validate) {
  544. if (isEmptyValue(value) && !rule.required) {
  545. return callback();
  546. }
  547. rules.required(rule, value, source, errors, options);
  548. if (value !== undefined) {
  549. rules.type(rule, value, source, errors, options);
  550. }
  551. }
  552. callback(errors);
  553. };
  554. var number = function number(rule, value, callback, source, options) {
  555. var errors = [];
  556. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  557. if (validate) {
  558. if (value === '') {
  559. value = undefined;
  560. }
  561. if (isEmptyValue(value) && !rule.required) {
  562. return callback();
  563. }
  564. rules.required(rule, value, source, errors, options);
  565. if (value !== undefined) {
  566. rules.type(rule, value, source, errors, options);
  567. rules.range(rule, value, source, errors, options);
  568. }
  569. }
  570. callback(errors);
  571. };
  572. var _boolean = function _boolean(rule, value, callback, source, options) {
  573. var errors = [];
  574. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  575. if (validate) {
  576. if (isEmptyValue(value) && !rule.required) {
  577. return callback();
  578. }
  579. rules.required(rule, value, source, errors, options);
  580. if (value !== undefined) {
  581. rules.type(rule, value, source, errors, options);
  582. }
  583. }
  584. callback(errors);
  585. };
  586. var regexp = function regexp(rule, value, callback, source, options) {
  587. var errors = [];
  588. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  589. if (validate) {
  590. if (isEmptyValue(value) && !rule.required) {
  591. return callback();
  592. }
  593. rules.required(rule, value, source, errors, options);
  594. if (!isEmptyValue(value)) {
  595. rules.type(rule, value, source, errors, options);
  596. }
  597. }
  598. callback(errors);
  599. };
  600. var integer = function integer(rule, value, callback, source, options) {
  601. var errors = [];
  602. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  603. if (validate) {
  604. if (isEmptyValue(value) && !rule.required) {
  605. return callback();
  606. }
  607. rules.required(rule, value, source, errors, options);
  608. if (value !== undefined) {
  609. rules.type(rule, value, source, errors, options);
  610. rules.range(rule, value, source, errors, options);
  611. }
  612. }
  613. callback(errors);
  614. };
  615. var floatFn = function floatFn(rule, value, callback, source, options) {
  616. var errors = [];
  617. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  618. if (validate) {
  619. if (isEmptyValue(value) && !rule.required) {
  620. return callback();
  621. }
  622. rules.required(rule, value, source, errors, options);
  623. if (value !== undefined) {
  624. rules.type(rule, value, source, errors, options);
  625. rules.range(rule, value, source, errors, options);
  626. }
  627. }
  628. callback(errors);
  629. };
  630. var array = function array(rule, value, callback, source, options) {
  631. var errors = [];
  632. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  633. if (validate) {
  634. if ((value === undefined || value === null) && !rule.required) {
  635. return callback();
  636. }
  637. rules.required(rule, value, source, errors, options, 'array');
  638. if (value !== undefined && value !== null) {
  639. rules.type(rule, value, source, errors, options);
  640. rules.range(rule, value, source, errors, options);
  641. }
  642. }
  643. callback(errors);
  644. };
  645. var object = function object(rule, value, callback, source, options) {
  646. var errors = [];
  647. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  648. if (validate) {
  649. if (isEmptyValue(value) && !rule.required) {
  650. return callback();
  651. }
  652. rules.required(rule, value, source, errors, options);
  653. if (value !== undefined) {
  654. rules.type(rule, value, source, errors, options);
  655. }
  656. }
  657. callback(errors);
  658. };
  659. var ENUM = 'enum';
  660. var enumerable = function enumerable(rule, value, callback, source, options) {
  661. var errors = [];
  662. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  663. if (validate) {
  664. if (isEmptyValue(value) && !rule.required) {
  665. return callback();
  666. }
  667. rules.required(rule, value, source, errors, options);
  668. if (value !== undefined) {
  669. rules[ENUM](rule, value, source, errors, options);
  670. }
  671. }
  672. callback(errors);
  673. };
  674. var pattern = function pattern(rule, value, callback, source, options) {
  675. var errors = [];
  676. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  677. if (validate) {
  678. if (isEmptyValue(value, 'string') && !rule.required) {
  679. return callback();
  680. }
  681. rules.required(rule, value, source, errors, options);
  682. if (!isEmptyValue(value, 'string')) {
  683. rules.pattern(rule, value, source, errors, options);
  684. }
  685. }
  686. callback(errors);
  687. };
  688. var date = function date(rule, value, callback, source, options) {
  689. // console.log('integer rule called %j', rule);
  690. var errors = [];
  691. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field); // console.log('validate on %s value', value);
  692. if (validate) {
  693. if (isEmptyValue(value, 'date') && !rule.required) {
  694. return callback();
  695. }
  696. rules.required(rule, value, source, errors, options);
  697. if (!isEmptyValue(value, 'date')) {
  698. var dateObject;
  699. if (value instanceof Date) {
  700. dateObject = value;
  701. } else {
  702. dateObject = new Date(value);
  703. }
  704. rules.type(rule, dateObject, source, errors, options);
  705. if (dateObject) {
  706. rules.range(rule, dateObject.getTime(), source, errors, options);
  707. }
  708. }
  709. }
  710. callback(errors);
  711. };
  712. var required = function required(rule, value, callback, source, options) {
  713. var errors = [];
  714. var type = Array.isArray(value) ? 'array' : typeof value;
  715. rules.required(rule, value, source, errors, options, type);
  716. callback(errors);
  717. };
  718. var type = function type(rule, value, callback, source, options) {
  719. var ruleType = rule.type;
  720. var errors = [];
  721. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  722. if (validate) {
  723. if (isEmptyValue(value, ruleType) && !rule.required) {
  724. return callback();
  725. }
  726. rules.required(rule, value, source, errors, options, ruleType);
  727. if (!isEmptyValue(value, ruleType)) {
  728. rules.type(rule, value, source, errors, options);
  729. }
  730. }
  731. callback(errors);
  732. };
  733. var any = function any(rule, value, callback, source, options) {
  734. var errors = [];
  735. var validate = rule.required || !rule.required && source.hasOwnProperty(rule.field);
  736. if (validate) {
  737. if (isEmptyValue(value) && !rule.required) {
  738. return callback();
  739. }
  740. rules.required(rule, value, source, errors, options);
  741. }
  742. callback(errors);
  743. };
  744. var validators = {
  745. string: string,
  746. method: method,
  747. number: number,
  748. "boolean": _boolean,
  749. regexp: regexp,
  750. integer: integer,
  751. "float": floatFn,
  752. array: array,
  753. object: object,
  754. "enum": enumerable,
  755. pattern: pattern,
  756. date: date,
  757. url: type,
  758. hex: type,
  759. email: type,
  760. required: required,
  761. any: any
  762. };
  763. function newMessages() {
  764. return {
  765. "default": 'Validation error on field %s',
  766. required: '%s is required',
  767. "enum": '%s must be one of %s',
  768. whitespace: '%s cannot be empty',
  769. date: {
  770. format: '%s date %s is invalid for format %s',
  771. parse: '%s date could not be parsed, %s is invalid ',
  772. invalid: '%s date %s is invalid'
  773. },
  774. types: {
  775. string: '%s is not a %s',
  776. method: '%s is not a %s (function)',
  777. array: '%s is not an %s',
  778. object: '%s is not an %s',
  779. number: '%s is not a %s',
  780. date: '%s is not a %s',
  781. "boolean": '%s is not a %s',
  782. integer: '%s is not an %s',
  783. "float": '%s is not a %s',
  784. regexp: '%s is not a valid %s',
  785. email: '%s is not a valid %s',
  786. url: '%s is not a valid %s',
  787. hex: '%s is not a valid %s'
  788. },
  789. string: {
  790. len: '%s must be exactly %s characters',
  791. min: '%s must be at least %s characters',
  792. max: '%s cannot be longer than %s characters',
  793. range: '%s must be between %s and %s characters'
  794. },
  795. number: {
  796. len: '%s must equal %s',
  797. min: '%s cannot be less than %s',
  798. max: '%s cannot be greater than %s',
  799. range: '%s must be between %s and %s'
  800. },
  801. array: {
  802. len: '%s must be exactly %s in length',
  803. min: '%s cannot be less than %s in length',
  804. max: '%s cannot be greater than %s in length',
  805. range: '%s must be between %s and %s in length'
  806. },
  807. pattern: {
  808. mismatch: '%s value %s does not match pattern %s'
  809. },
  810. clone: function clone() {
  811. var cloned = JSON.parse(JSON.stringify(this));
  812. cloned.clone = this.clone;
  813. return cloned;
  814. }
  815. };
  816. }
  817. var messages = newMessages();
  818. /**
  819. * Encapsulates a validation schema.
  820. *
  821. * @param descriptor An object declaring validation rules
  822. * for this schema.
  823. */
  824. var Schema = /*#__PURE__*/function () {
  825. // ========================= Static =========================
  826. // ======================== Instance ========================
  827. function Schema(descriptor) {
  828. this.rules = null;
  829. this._messages = messages;
  830. this.define(descriptor);
  831. }
  832. var _proto = Schema.prototype;
  833. _proto.define = function define(rules) {
  834. var _this = this;
  835. if (!rules) {
  836. throw new Error('Cannot configure a schema with no rules');
  837. }
  838. if (typeof rules !== 'object' || Array.isArray(rules)) {
  839. throw new Error('Rules must be an object');
  840. }
  841. this.rules = {};
  842. Object.keys(rules).forEach(function (name) {
  843. var item = rules[name];
  844. _this.rules[name] = Array.isArray(item) ? item : [item];
  845. });
  846. };
  847. _proto.messages = function messages(_messages) {
  848. if (_messages) {
  849. this._messages = deepMerge(newMessages(), _messages);
  850. }
  851. return this._messages;
  852. };
  853. _proto.validate = function validate(source_, o, oc) {
  854. var _this2 = this;
  855. if (o === void 0) {
  856. o = {};
  857. }
  858. if (oc === void 0) {
  859. oc = function oc() {};
  860. }
  861. var source = source_;
  862. var options = o;
  863. var callback = oc;
  864. if (typeof options === 'function') {
  865. callback = options;
  866. options = {};
  867. }
  868. if (!this.rules || Object.keys(this.rules).length === 0) {
  869. if (callback) {
  870. callback(null, source);
  871. }
  872. return Promise.resolve(source);
  873. }
  874. function complete(results) {
  875. var errors = [];
  876. var fields = {};
  877. function add(e) {
  878. if (Array.isArray(e)) {
  879. var _errors;
  880. errors = (_errors = errors).concat.apply(_errors, e);
  881. } else {
  882. errors.push(e);
  883. }
  884. }
  885. for (var i = 0; i < results.length; i++) {
  886. add(results[i]);
  887. }
  888. if (!errors.length) {
  889. callback(null, source);
  890. } else {
  891. fields = convertFieldsError(errors);
  892. callback(errors, fields);
  893. }
  894. }
  895. if (options.messages) {
  896. var messages$1 = this.messages();
  897. if (messages$1 === messages) {
  898. messages$1 = newMessages();
  899. }
  900. deepMerge(messages$1, options.messages);
  901. options.messages = messages$1;
  902. } else {
  903. options.messages = this.messages();
  904. }
  905. var series = {};
  906. var keys = options.keys || Object.keys(this.rules);
  907. keys.forEach(function (z) {
  908. var arr = _this2.rules[z];
  909. var value = source[z];
  910. arr.forEach(function (r) {
  911. var rule = r;
  912. if (typeof rule.transform === 'function') {
  913. if (source === source_) {
  914. source = _extends({}, source);
  915. }
  916. value = source[z] = rule.transform(value);
  917. }
  918. if (typeof rule === 'function') {
  919. rule = {
  920. validator: rule
  921. };
  922. } else {
  923. rule = _extends({}, rule);
  924. } // Fill validator. Skip if nothing need to validate
  925. rule.validator = _this2.getValidationMethod(rule);
  926. if (!rule.validator) {
  927. return;
  928. }
  929. rule.field = z;
  930. rule.fullField = rule.fullField || z;
  931. rule.type = _this2.getType(rule);
  932. series[z] = series[z] || [];
  933. series[z].push({
  934. rule: rule,
  935. value: value,
  936. source: source,
  937. field: z
  938. });
  939. });
  940. });
  941. var errorFields = {};
  942. return asyncMap(series, options, function (data, doIt) {
  943. var rule = data.rule;
  944. var deep = (rule.type === 'object' || rule.type === 'array') && (typeof rule.fields === 'object' || typeof rule.defaultField === 'object');
  945. deep = deep && (rule.required || !rule.required && data.value);
  946. rule.field = data.field;
  947. function addFullField(key, schema) {
  948. return _extends({}, schema, {
  949. fullField: rule.fullField + "." + key,
  950. fullFields: rule.fullFields ? [].concat(rule.fullFields, [key]) : [key]
  951. });
  952. }
  953. function cb(e) {
  954. if (e === void 0) {
  955. e = [];
  956. }
  957. var errorList = Array.isArray(e) ? e : [e];
  958. if (!options.suppressWarning && errorList.length) {
  959. Schema.warning('async-validator:', errorList);
  960. }
  961. if (errorList.length && rule.message !== undefined) {
  962. errorList = [].concat(rule.message);
  963. } // Fill error info
  964. var filledErrors = errorList.map(complementError(rule, source));
  965. if (options.first && filledErrors.length) {
  966. errorFields[rule.field] = 1;
  967. return doIt(filledErrors);
  968. }
  969. if (!deep) {
  970. doIt(filledErrors);
  971. } else {
  972. // if rule is required but the target object
  973. // does not exist fail at the rule level and don't
  974. // go deeper
  975. if (rule.required && !data.value) {
  976. if (rule.message !== undefined) {
  977. filledErrors = [].concat(rule.message).map(complementError(rule, source));
  978. } else if (options.error) {
  979. filledErrors = [options.error(rule, format(options.messages.required, rule.field))];
  980. }
  981. return doIt(filledErrors);
  982. }
  983. var fieldsSchema = {};
  984. if (rule.defaultField) {
  985. Object.keys(data.value).map(function (key) {
  986. fieldsSchema[key] = rule.defaultField;
  987. });
  988. }
  989. fieldsSchema = _extends({}, fieldsSchema, data.rule.fields);
  990. var paredFieldsSchema = {};
  991. Object.keys(fieldsSchema).forEach(function (field) {
  992. var fieldSchema = fieldsSchema[field];
  993. var fieldSchemaList = Array.isArray(fieldSchema) ? fieldSchema : [fieldSchema];
  994. paredFieldsSchema[field] = fieldSchemaList.map(addFullField.bind(null, field));
  995. });
  996. var schema = new Schema(paredFieldsSchema);
  997. schema.messages(options.messages);
  998. if (data.rule.options) {
  999. data.rule.options.messages = options.messages;
  1000. data.rule.options.error = options.error;
  1001. }
  1002. schema.validate(data.value, data.rule.options || options, function (errs) {
  1003. var finalErrors = [];
  1004. if (filledErrors && filledErrors.length) {
  1005. finalErrors.push.apply(finalErrors, filledErrors);
  1006. }
  1007. if (errs && errs.length) {
  1008. finalErrors.push.apply(finalErrors, errs);
  1009. }
  1010. doIt(finalErrors.length ? finalErrors : null);
  1011. });
  1012. }
  1013. }
  1014. var res;
  1015. if (rule.asyncValidator) {
  1016. res = rule.asyncValidator(rule, data.value, cb, data.source, options);
  1017. } else if (rule.validator) {
  1018. try {
  1019. res = rule.validator(rule, data.value, cb, data.source, options);
  1020. } catch (error) {
  1021. console.error == null ? void 0 : console.error(error); // rethrow to report error
  1022. if (!options.suppressValidatorError) {
  1023. setTimeout(function () {
  1024. throw error;
  1025. }, 0);
  1026. }
  1027. cb(error.message);
  1028. }
  1029. if (res === true) {
  1030. cb();
  1031. } else if (res === false) {
  1032. cb(typeof rule.message === 'function' ? rule.message(rule.fullField || rule.field) : rule.message || (rule.fullField || rule.field) + " fails");
  1033. } else if (res instanceof Array) {
  1034. cb(res);
  1035. } else if (res instanceof Error) {
  1036. cb(res.message);
  1037. }
  1038. }
  1039. if (res && res.then) {
  1040. res.then(function () {
  1041. return cb();
  1042. }, function (e) {
  1043. return cb(e);
  1044. });
  1045. }
  1046. }, function (results) {
  1047. complete(results);
  1048. }, source);
  1049. };
  1050. _proto.getType = function getType(rule) {
  1051. if (rule.type === undefined && rule.pattern instanceof RegExp) {
  1052. rule.type = 'pattern';
  1053. }
  1054. if (typeof rule.validator !== 'function' && rule.type && !validators.hasOwnProperty(rule.type)) {
  1055. throw new Error(format('Unknown rule type %s', rule.type));
  1056. }
  1057. return rule.type || 'string';
  1058. };
  1059. _proto.getValidationMethod = function getValidationMethod(rule) {
  1060. if (typeof rule.validator === 'function') {
  1061. return rule.validator;
  1062. }
  1063. var keys = Object.keys(rule);
  1064. var messageIndex = keys.indexOf('message');
  1065. if (messageIndex !== -1) {
  1066. keys.splice(messageIndex, 1);
  1067. }
  1068. if (keys.length === 1 && keys[0] === 'required') {
  1069. return validators.required;
  1070. }
  1071. return validators[this.getType(rule)] || undefined;
  1072. };
  1073. return Schema;
  1074. }();
  1075. Schema.register = function register(type, validator) {
  1076. if (typeof validator !== 'function') {
  1077. throw new Error('Cannot register a validator by type, validator is not a function');
  1078. }
  1079. validators[type] = validator;
  1080. };
  1081. Schema.warning = warning;
  1082. Schema.messages = messages;
  1083. Schema.validators = validators;
  1084. exports["default"] = Schema;
  1085. //# sourceMappingURL=index.js.map
  1086. }, function(modId) {var map = {}; return __REQUIRE__(map[modId], modId); })
  1087. return __REQUIRE__(1710576073078);
  1088. })()
  1089. //miniprogram-npm-outsideDeps=[]
  1090. //# sourceMappingURL=index.js.map