comprodls-sdk 2.119.1-security → 2.120.0-security

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1007,13 +1007,129 @@ module.exports = {
1007
1007
  * comproDLS SDK Validator Helper Module
1008
1008
  * This module contains validation helper functions for comproDLS SDK
1009
1009
  ************************************************************/
1010
- var validator = require('validate.js');
1010
+
1011
1011
  var errors = require('./errors');
1012
1012
  var DLSError = errors.DLSError;
1013
1013
 
1014
- exports.validate = validate;
1015
- exports.isAuthenticated = validateIsAuthenticated;
1016
- exports.isAuthenticatedV2 = validateIsAuthenticatedV2;
1014
+ /*********************************
1015
+ * Core validator utilities
1016
+ * Each validator follows the signature:
1017
+ * fn(field, value, options) → DLSError | undefined
1018
+ *
1019
+ * - field : the constraint key name e.g. 'organization', 'token', 'token.access_token'
1020
+ * - value : the value from the options object for that field
1021
+ * - options : the rule config, can be `true` or `{ message: '...' }`
1022
+ * For `contains`, options is a string or array of required keys.
1023
+ *
1024
+ * Returning a DLSError which stops validation immediately.
1025
+ * Returning undefined means the check passed.
1026
+ **********************************/
1027
+ var validators = {
1028
+ /**
1029
+ * Fails if value is null, undefined, or blank/whitespace-only string or empty object.
1030
+ */
1031
+ presence: function(field, value, options) {
1032
+ if (value === undefined || value === null || value === '' ||
1033
+ (typeof value == 'string' && value.trim() === '') ||
1034
+ (typeof value == 'object' && Object.keys(value).length === 0)
1035
+ ) {
1036
+ return createError(options.message || field + ' can\'t be blank');
1037
+ }
1038
+ },
1039
+
1040
+ /**
1041
+ * Fails if value is not a string.
1042
+ */
1043
+ isString: function(field, value, options) {
1044
+ if (typeof value !== 'string') {
1045
+ return createError(options.message || field + ' is not a valid string');
1046
+ }
1047
+ },
1048
+
1049
+ /**
1050
+ * Fails if value is not an object.
1051
+ */
1052
+ isObject: function(field, value, options) {
1053
+ if (typeof value !== 'object' || Array.isArray(value)) {
1054
+ return createError(options.message || field + ' is not a valid object');
1055
+ }
1056
+ },
1057
+
1058
+ /**
1059
+ * Fails if the object does not have the required key(s).
1060
+ */
1061
+ contains: function(field, value, options) {
1062
+ var keys = Array.isArray(options) ? options : typeof options === 'string' ? [options] : [];
1063
+
1064
+ for (var i = 0; i < keys.length; i++) {
1065
+ var requiredKey = keys[i];
1066
+
1067
+ if (!value.hasOwnProperty(requiredKey)) {
1068
+ return createError(options.message || field + ' does not contain ' + requiredKey);
1069
+ }
1070
+ }
1071
+ }
1072
+ };
1073
+
1074
+ /*********************************
1075
+ * Core validate function
1076
+ *
1077
+ * Iterates over each field in constraints, resolves its value from options,
1078
+ * then runs each rule's validator function in order.
1079
+ * Returns the first error encountered or undefined if all pass.
1080
+ *
1081
+ * @param {Object} options - The input object to validate
1082
+ * @param {Object} constraints - Map of field names to their rule constraints
1083
+ * @returns {DLSError | undefined}
1084
+ **********************************/
1085
+ function validate(options, constraints) {
1086
+ for (var field in constraints) {
1087
+ var fieldConstraintsObj = constraints[field];
1088
+ var value = getValue(options, field);
1089
+
1090
+ for (var ruleName in fieldConstraintsObj) {
1091
+ var ruleOptions = fieldConstraintsObj[ruleName];
1092
+ var validatorFn = validators[ruleName];
1093
+
1094
+ if (!validatorFn) { continue; }
1095
+
1096
+ // Pass field name, field value, and field's rule constraint value to the validator function
1097
+ var error = validatorFn(field, value, ruleOptions);
1098
+ if (error) { return error; }
1099
+ }
1100
+ }
1101
+
1102
+ return undefined;
1103
+ }
1104
+
1105
+ /*********************************
1106
+ * Private helpers
1107
+ **********************************/
1108
+ function getValue(obj, path) {
1109
+ var keys = path.split('.');
1110
+ var result = obj;
1111
+
1112
+ for (var i = 0; i < keys.length; i++) {
1113
+ if (result === undefined || result === null) { return undefined; }
1114
+ result = result[keys[i]];
1115
+ }
1116
+
1117
+ return result;
1118
+ }
1119
+
1120
+ function createError(message) {
1121
+ var msg = message || 'Validation error';
1122
+ msg = msg.charAt(0).toUpperCase() + msg.slice(1);
1123
+
1124
+ return new DLSError(errors.ERROR_TYPES.SDK_ERROR, {
1125
+ message: msg,
1126
+ description: msg
1127
+ });
1128
+ }
1129
+
1130
+ /*********************************
1131
+ * Exported auth validators
1132
+ **********************************/
1017
1133
 
1018
1134
  /**
1019
1135
  * This function validates if the SDK instance is authenticated.
@@ -1030,22 +1146,10 @@ function validateIsAuthenticatedV2(orgId, token) {
1030
1146
  return new DLSError(errors.ERROR_TYPES.SDK_ERROR, errObj);
1031
1147
  };
1032
1148
 
1033
- function validate(options, constraints) {
1034
- var err = {};
1035
- var validation_errors = validator(options, constraints);
1036
- if (validation_errors) {
1037
- for (var validation_error in validation_errors) {
1038
- err.message = err.description = validation_errors[validation_error][0];
1039
- err = new DLSError(errors.ERROR_TYPES.SDK_ERROR, err);
1040
- return err;
1041
- }
1042
- } else {
1043
- return undefined;
1044
- }
1045
- };
1046
-
1047
1149
  /**
1048
- * This function is deprecated. Please use validateIsAuthenticatedV2 instead.
1150
+ * Validates if SDK instance is authenticated by checking presence of orgId and token.
1151
+ * @param {String} orgId - Organization ID
1152
+ * @param {Object} token - Token object { access_token: 'string' }
1049
1153
  */
1050
1154
  function validateIsAuthenticated(orgId, token) {
1051
1155
  var validate_options = {
@@ -1053,52 +1157,26 @@ function validateIsAuthenticated(orgId, token) {
1053
1157
  'token': token
1054
1158
  };
1055
1159
 
1160
+ var errMsg = 'SDK Instance does not have valid orgid or token. ' +
1161
+ 'Please authenticate using authWithCredentials or authWithToken method.';
1162
+
1056
1163
  var validate_constraints = {
1057
1164
  'organization': {
1058
- 'presence': {
1059
- 'message' : '^SDK Instance does not have valid orgid or token. Please authenticate using authWithCredentials or authWithToken method.'
1060
- }
1165
+ 'presence': { 'message': errMsg }
1061
1166
  },
1062
1167
  'token': {
1063
- 'presence': {
1064
- 'message' : '^SDK Instance does not have valid orgid or token. Please authenticate using authWithCredentials or authWithToken method.'
1065
- }
1168
+ 'presence': { 'message': errMsg }
1066
1169
  }
1067
1170
  };
1068
1171
 
1069
1172
  return validate(validate_options, validate_constraints);
1070
1173
  };
1071
1174
 
1072
- /*********************************
1073
- * Private Function definitions
1074
- **********************************/
1075
- validator.validators.isString = function(value, options) {
1076
- if (!validator.isString(value)) {
1077
- return options.message || 'is not a valid string';
1078
- }
1079
- };
1080
-
1081
- validator.validators.isObject = function(value, options) {
1082
- if (!validator.isObject(value)) {
1083
- return options.message || 'is not a valid object';
1084
- }
1085
- };
1086
-
1087
- validator.validators.contains = function(value, options) {
1088
- if (validator.isArray(options)) {
1089
- for (var key in options) {
1090
- if (!value || !value.hasOwnProperty(options[key])) {
1091
- return options.message || 'does not contain ' + options[key];
1092
- }
1093
- }
1094
- } else if (validator.isString(options)) {
1095
- if (!value || !value.hasOwnProperty(options)) {
1096
- return options.message || 'does not contain ' + options;
1097
- }
1098
- }
1099
- };
1175
+ exports.validate = validate;
1176
+ exports.isAuthenticated = validateIsAuthenticated;
1177
+ exports.isAuthenticatedV2 = validateIsAuthenticatedV2;
1100
1178
 
1101
- },{"./errors":6,"validate.js":44}],9:[function(require,module,exports){
1179
+ },{"./errors":6}],9:[function(require,module,exports){
1102
1180
  /*************************************************************************
1103
1181
  *
1104
1182
  * COMPRO CONFIDENTIAL
@@ -18154,1093 +18232,5 @@ exports.cleanHeader = function(header, changesOrigin){
18154
18232
  return header;
18155
18233
  };
18156
18234
 
18157
- },{}],44:[function(require,module,exports){
18158
- /*!
18159
- * validate.js 0.9.0
18160
- *
18161
- * (c) 2013-2015 Nicklas Ansman, 2013 Wrapp
18162
- * Validate.js may be freely distributed under the MIT license.
18163
- * For all details and documentation:
18164
- * http://validatejs.org/
18165
- */
18166
-
18167
- (function(exports, module, define) {
18168
- "use strict";
18169
-
18170
- // The main function that calls the validators specified by the constraints.
18171
- // The options are the following:
18172
- // - format (string) - An option that controls how the returned value is formatted
18173
- // * flat - Returns a flat array of just the error messages
18174
- // * grouped - Returns the messages grouped by attribute (default)
18175
- // * detailed - Returns an array of the raw validation data
18176
- // - fullMessages (boolean) - If `true` (default) the attribute name is prepended to the error.
18177
- //
18178
- // Please note that the options are also passed to each validator.
18179
- var validate = function(attributes, constraints, options) {
18180
- options = v.extend({}, v.options, options);
18181
-
18182
- var results = v.runValidations(attributes, constraints, options)
18183
- , attr
18184
- , validator;
18185
-
18186
- for (attr in results) {
18187
- for (validator in results[attr]) {
18188
- if (v.isPromise(results[attr][validator])) {
18189
- throw new Error("Use validate.async if you want support for promises");
18190
- }
18191
- }
18192
- }
18193
- return validate.processValidationResults(results, options);
18194
- };
18195
-
18196
- var v = validate;
18197
-
18198
- // Copies over attributes from one or more sources to a single destination.
18199
- // Very much similar to underscore's extend.
18200
- // The first argument is the target object and the remaining arguments will be
18201
- // used as sources.
18202
- v.extend = function(obj) {
18203
- [].slice.call(arguments, 1).forEach(function(source) {
18204
- for (var attr in source) {
18205
- obj[attr] = source[attr];
18206
- }
18207
- });
18208
- return obj;
18209
- };
18210
-
18211
- v.extend(validate, {
18212
- // This is the version of the library as a semver.
18213
- // The toString function will allow it to be coerced into a string
18214
- version: {
18215
- major: 0,
18216
- minor: 9,
18217
- patch: 0,
18218
- metadata: null,
18219
- toString: function() {
18220
- var version = v.format("%{major}.%{minor}.%{patch}", v.version);
18221
- if (!v.isEmpty(v.version.metadata)) {
18222
- version += "+" + v.version.metadata;
18223
- }
18224
- return version;
18225
- }
18226
- },
18227
-
18228
- // Below is the dependencies that are used in validate.js
18229
-
18230
- // The constructor of the Promise implementation.
18231
- // If you are using Q.js, RSVP or any other A+ compatible implementation
18232
- // override this attribute to be the constructor of that promise.
18233
- // Since jQuery promises aren't A+ compatible they won't work.
18234
- Promise: typeof Promise !== "undefined" ? Promise : /* istanbul ignore next */ null,
18235
-
18236
- EMPTY_STRING_REGEXP: /^\s*$/,
18237
-
18238
- // Runs the validators specified by the constraints object.
18239
- // Will return an array of the format:
18240
- // [{attribute: "<attribute name>", error: "<validation result>"}, ...]
18241
- runValidations: function(attributes, constraints, options) {
18242
- var results = []
18243
- , attr
18244
- , validatorName
18245
- , value
18246
- , validators
18247
- , validator
18248
- , validatorOptions
18249
- , error;
18250
-
18251
- if (v.isDomElement(attributes) || v.isJqueryElement(attributes)) {
18252
- attributes = v.collectFormValues(attributes);
18253
- }
18254
-
18255
- // Loops through each constraints, finds the correct validator and run it.
18256
- for (attr in constraints) {
18257
- value = v.getDeepObjectValue(attributes, attr);
18258
- // This allows the constraints for an attribute to be a function.
18259
- // The function will be called with the value, attribute name, the complete dict of
18260
- // attributes as well as the options and constraints passed in.
18261
- // This is useful when you want to have different
18262
- // validations depending on the attribute value.
18263
- validators = v.result(constraints[attr], value, attributes, attr, options, constraints);
18264
-
18265
- for (validatorName in validators) {
18266
- validator = v.validators[validatorName];
18267
-
18268
- if (!validator) {
18269
- error = v.format("Unknown validator %{name}", {name: validatorName});
18270
- throw new Error(error);
18271
- }
18272
-
18273
- validatorOptions = validators[validatorName];
18274
- // This allows the options to be a function. The function will be
18275
- // called with the value, attribute name, the complete dict of
18276
- // attributes as well as the options and constraints passed in.
18277
- // This is useful when you want to have different
18278
- // validations depending on the attribute value.
18279
- validatorOptions = v.result(validatorOptions, value, attributes, attr, options, constraints);
18280
- if (!validatorOptions) {
18281
- continue;
18282
- }
18283
- results.push({
18284
- attribute: attr,
18285
- value: value,
18286
- validator: validatorName,
18287
- globalOptions: options,
18288
- attributes: attributes,
18289
- options: validatorOptions,
18290
- error: validator.call(validator,
18291
- value,
18292
- validatorOptions,
18293
- attr,
18294
- attributes,
18295
- options)
18296
- });
18297
- }
18298
- }
18299
-
18300
- return results;
18301
- },
18302
-
18303
- // Takes the output from runValidations and converts it to the correct
18304
- // output format.
18305
- processValidationResults: function(errors, options) {
18306
- var attr;
18307
-
18308
- errors = v.pruneEmptyErrors(errors, options);
18309
- errors = v.expandMultipleErrors(errors, options);
18310
- errors = v.convertErrorMessages(errors, options);
18311
-
18312
- switch (options.format || "grouped") {
18313
- case "detailed":
18314
- // Do nothing more to the errors
18315
- break;
18316
-
18317
- case "flat":
18318
- errors = v.flattenErrorsToArray(errors);
18319
- break;
18320
-
18321
- case "grouped":
18322
- errors = v.groupErrorsByAttribute(errors);
18323
- for (attr in errors) {
18324
- errors[attr] = v.flattenErrorsToArray(errors[attr]);
18325
- }
18326
- break;
18327
-
18328
- default:
18329
- throw new Error(v.format("Unknown format %{format}", options));
18330
- }
18331
-
18332
- return v.isEmpty(errors) ? undefined : errors;
18333
- },
18334
-
18335
- // Runs the validations with support for promises.
18336
- // This function will return a promise that is settled when all the
18337
- // validation promises have been completed.
18338
- // It can be called even if no validations returned a promise.
18339
- async: function(attributes, constraints, options) {
18340
- options = v.extend({}, v.async.options, options);
18341
-
18342
- var WrapErrors = options.wrapErrors || function(errors) {
18343
- return errors;
18344
- };
18345
-
18346
- // Removes unknown attributes
18347
- if (options.cleanAttributes !== false) {
18348
- attributes = v.cleanAttributes(attributes, constraints);
18349
- }
18350
-
18351
- var results = v.runValidations(attributes, constraints, options);
18352
-
18353
- return new v.Promise(function(resolve, reject) {
18354
- v.waitForResults(results).then(function() {
18355
- var errors = v.processValidationResults(results, options);
18356
- if (errors) {
18357
- reject(new WrapErrors(errors, options, attributes, constraints));
18358
- } else {
18359
- resolve(attributes);
18360
- }
18361
- }, function(err) {
18362
- reject(err);
18363
- });
18364
- });
18365
- },
18366
-
18367
- single: function(value, constraints, options) {
18368
- options = v.extend({}, v.single.options, options, {
18369
- format: "flat",
18370
- fullMessages: false
18371
- });
18372
- return v({single: value}, {single: constraints}, options);
18373
- },
18374
-
18375
- // Returns a promise that is resolved when all promises in the results array
18376
- // are settled. The promise returned from this function is always resolved,
18377
- // never rejected.
18378
- // This function modifies the input argument, it replaces the promises
18379
- // with the value returned from the promise.
18380
- waitForResults: function(results) {
18381
- // Create a sequence of all the results starting with a resolved promise.
18382
- return results.reduce(function(memo, result) {
18383
- // If this result isn't a promise skip it in the sequence.
18384
- if (!v.isPromise(result.error)) {
18385
- return memo;
18386
- }
18387
-
18388
- return memo.then(function() {
18389
- return result.error.then(
18390
- function(error) {
18391
- result.error = error || null;
18392
- },
18393
- function(error) {
18394
- if (error instanceof Error) {
18395
- throw error;
18396
- }
18397
- v.error("Rejecting promises with the result is deprecated. Please use the resolve callback instead.");
18398
- result.error = error;
18399
- }
18400
- );
18401
- });
18402
- }, new v.Promise(function(r) { r(); })); // A resolved promise
18403
- },
18404
-
18405
- // If the given argument is a call: function the and: function return the value
18406
- // otherwise just return the value. Additional arguments will be passed as
18407
- // arguments to the function.
18408
- // Example:
18409
- // ```
18410
- // result('foo') // 'foo'
18411
- // result(Math.max, 1, 2) // 2
18412
- // ```
18413
- result: function(value) {
18414
- var args = [].slice.call(arguments, 1);
18415
- if (typeof value === 'function') {
18416
- value = value.apply(null, args);
18417
- }
18418
- return value;
18419
- },
18420
-
18421
- // Checks if the value is a number. This function does not consider NaN a
18422
- // number like many other `isNumber` functions do.
18423
- isNumber: function(value) {
18424
- return typeof value === 'number' && !isNaN(value);
18425
- },
18426
-
18427
- // Returns false if the object is not a function
18428
- isFunction: function(value) {
18429
- return typeof value === 'function';
18430
- },
18431
-
18432
- // A simple check to verify that the value is an integer. Uses `isNumber`
18433
- // and a simple modulo check.
18434
- isInteger: function(value) {
18435
- return v.isNumber(value) && value % 1 === 0;
18436
- },
18437
-
18438
- // Uses the `Object` function to check if the given argument is an object.
18439
- isObject: function(obj) {
18440
- return obj === Object(obj);
18441
- },
18442
-
18443
- // Simply checks if the object is an instance of a date
18444
- isDate: function(obj) {
18445
- return obj instanceof Date;
18446
- },
18447
-
18448
- // Returns false if the object is `null` of `undefined`
18449
- isDefined: function(obj) {
18450
- return obj !== null && obj !== undefined;
18451
- },
18452
-
18453
- // Checks if the given argument is a promise. Anything with a `then`
18454
- // function is considered a promise.
18455
- isPromise: function(p) {
18456
- return !!p && v.isFunction(p.then);
18457
- },
18458
-
18459
- isJqueryElement: function(o) {
18460
- return o && v.isString(o.jquery);
18461
- },
18462
-
18463
- isDomElement: function(o) {
18464
- if (!o) {
18465
- return false;
18466
- }
18467
-
18468
- if (!v.isFunction(o.querySelectorAll) || !v.isFunction(o.querySelector)) {
18469
- return false;
18470
- }
18471
-
18472
- if (v.isObject(document) && o === document) {
18473
- return true;
18474
- }
18475
-
18476
- // http://stackoverflow.com/a/384380/699304
18477
- /* istanbul ignore else */
18478
- if (typeof HTMLElement === "object") {
18479
- return o instanceof HTMLElement;
18480
- } else {
18481
- return o &&
18482
- typeof o === "object" &&
18483
- o !== null &&
18484
- o.nodeType === 1 &&
18485
- typeof o.nodeName === "string";
18486
- }
18487
- },
18488
-
18489
- isEmpty: function(value) {
18490
- var attr;
18491
-
18492
- // Null and undefined are empty
18493
- if (!v.isDefined(value)) {
18494
- return true;
18495
- }
18496
-
18497
- // functions are non empty
18498
- if (v.isFunction(value)) {
18499
- return false;
18500
- }
18501
-
18502
- // Whitespace only strings are empty
18503
- if (v.isString(value)) {
18504
- return v.EMPTY_STRING_REGEXP.test(value);
18505
- }
18506
-
18507
- // For arrays we use the length property
18508
- if (v.isArray(value)) {
18509
- return value.length === 0;
18510
- }
18511
-
18512
- // Dates have no attributes but aren't empty
18513
- if (v.isDate(value)) {
18514
- return false;
18515
- }
18516
-
18517
- // If we find at least one property we consider it non empty
18518
- if (v.isObject(value)) {
18519
- for (attr in value) {
18520
- return false;
18521
- }
18522
- return true;
18523
- }
18524
-
18525
- return false;
18526
- },
18527
-
18528
- // Formats the specified strings with the given values like so:
18529
- // ```
18530
- // format("Foo: %{foo}", {foo: "bar"}) // "Foo bar"
18531
- // ```
18532
- // If you want to write %{...} without having it replaced simply
18533
- // prefix it with % like this `Foo: %%{foo}` and it will be returned
18534
- // as `"Foo: %{foo}"`
18535
- format: v.extend(function(str, vals) {
18536
- if (!v.isString(str)) {
18537
- return str;
18538
- }
18539
- return str.replace(v.format.FORMAT_REGEXP, function(m0, m1, m2) {
18540
- if (m1 === '%') {
18541
- return "%{" + m2 + "}";
18542
- } else {
18543
- return String(vals[m2]);
18544
- }
18545
- });
18546
- }, {
18547
- // Finds %{key} style patterns in the given string
18548
- FORMAT_REGEXP: /(%?)%\{([^\}]+)\}/g
18549
- }),
18550
-
18551
- // "Prettifies" the given string.
18552
- // Prettifying means replacing [.\_-] with spaces as well as splitting
18553
- // camel case words.
18554
- prettify: function(str) {
18555
- if (v.isNumber(str)) {
18556
- // If there are more than 2 decimals round it to two
18557
- if ((str * 100) % 1 === 0) {
18558
- return "" + str;
18559
- } else {
18560
- return parseFloat(Math.round(str * 100) / 100).toFixed(2);
18561
- }
18562
- }
18563
-
18564
- if (v.isArray(str)) {
18565
- return str.map(function(s) { return v.prettify(s); }).join(", ");
18566
- }
18567
-
18568
- if (v.isObject(str)) {
18569
- return str.toString();
18570
- }
18571
-
18572
- // Ensure the string is actually a string
18573
- str = "" + str;
18574
-
18575
- return str
18576
- // Splits keys separated by periods
18577
- .replace(/([^\s])\.([^\s])/g, '$1 $2')
18578
- // Removes backslashes
18579
- .replace(/\\+/g, '')
18580
- // Replaces - and - with space
18581
- .replace(/[_-]/g, ' ')
18582
- // Splits camel cased words
18583
- .replace(/([a-z])([A-Z])/g, function(m0, m1, m2) {
18584
- return "" + m1 + " " + m2.toLowerCase();
18585
- })
18586
- .toLowerCase();
18587
- },
18588
-
18589
- stringifyValue: function(value) {
18590
- return v.prettify(value);
18591
- },
18592
-
18593
- isString: function(value) {
18594
- return typeof value === 'string';
18595
- },
18596
-
18597
- isArray: function(value) {
18598
- return {}.toString.call(value) === '[object Array]';
18599
- },
18600
-
18601
- contains: function(obj, value) {
18602
- if (!v.isDefined(obj)) {
18603
- return false;
18604
- }
18605
- if (v.isArray(obj)) {
18606
- return obj.indexOf(value) !== -1;
18607
- }
18608
- return value in obj;
18609
- },
18610
-
18611
- forEachKeyInKeypath: function(object, keypath, callback) {
18612
- if (!v.isString(keypath)) {
18613
- return undefined;
18614
- }
18615
-
18616
- var key = ""
18617
- , i
18618
- , escape = false;
18619
-
18620
- for (i = 0; i < keypath.length; ++i) {
18621
- switch (keypath[i]) {
18622
- case '.':
18623
- if (escape) {
18624
- escape = false;
18625
- key += '.';
18626
- } else {
18627
- object = callback(object, key, false);
18628
- key = "";
18629
- }
18630
- break;
18631
-
18632
- case '\\':
18633
- if (escape) {
18634
- escape = false;
18635
- key += '\\';
18636
- } else {
18637
- escape = true;
18638
- }
18639
- break;
18640
-
18641
- default:
18642
- escape = false;
18643
- key += keypath[i];
18644
- break;
18645
- }
18646
- }
18647
-
18648
- return callback(object, key, true);
18649
- },
18650
-
18651
- getDeepObjectValue: function(obj, keypath) {
18652
- if (!v.isObject(obj)) {
18653
- return undefined;
18654
- }
18655
-
18656
- return v.forEachKeyInKeypath(obj, keypath, function(obj, key) {
18657
- if (v.isObject(obj)) {
18658
- return obj[key];
18659
- }
18660
- });
18661
- },
18662
-
18663
- // This returns an object with all the values of the form.
18664
- // It uses the input name as key and the value as value
18665
- // So for example this:
18666
- // <input type="text" name="email" value="foo@bar.com" />
18667
- // would return:
18668
- // {email: "foo@bar.com"}
18669
- collectFormValues: function(form, options) {
18670
- var values = {}
18671
- , i
18672
- , input
18673
- , inputs
18674
- , value;
18675
-
18676
- if (v.isJqueryElement(form)) {
18677
- form = form[0];
18678
- }
18679
-
18680
- if (!form) {
18681
- return values;
18682
- }
18683
-
18684
- options = options || {};
18685
-
18686
- inputs = form.querySelectorAll("input[name], textarea[name]");
18687
- for (i = 0; i < inputs.length; ++i) {
18688
- input = inputs.item(i);
18689
-
18690
- if (v.isDefined(input.getAttribute("data-ignored"))) {
18691
- continue;
18692
- }
18693
-
18694
- value = v.sanitizeFormValue(input.value, options);
18695
- if (input.type === "number") {
18696
- value = value ? +value : null;
18697
- } else if (input.type === "checkbox") {
18698
- if (input.attributes.value) {
18699
- if (!input.checked) {
18700
- value = values[input.name] || null;
18701
- }
18702
- } else {
18703
- value = input.checked;
18704
- }
18705
- } else if (input.type === "radio") {
18706
- if (!input.checked) {
18707
- value = values[input.name] || null;
18708
- }
18709
- }
18710
- values[input.name] = value;
18711
- }
18712
-
18713
- inputs = form.querySelectorAll("select[name]");
18714
- for (i = 0; i < inputs.length; ++i) {
18715
- input = inputs.item(i);
18716
- value = v.sanitizeFormValue(input.options[input.selectedIndex].value, options);
18717
- values[input.name] = value;
18718
- }
18719
-
18720
- return values;
18721
- },
18722
-
18723
- sanitizeFormValue: function(value, options) {
18724
- if (options.trim && v.isString(value)) {
18725
- value = value.trim();
18726
- }
18727
-
18728
- if (options.nullify !== false && value === "") {
18729
- return null;
18730
- }
18731
- return value;
18732
- },
18733
-
18734
- capitalize: function(str) {
18735
- if (!v.isString(str)) {
18736
- return str;
18737
- }
18738
- return str[0].toUpperCase() + str.slice(1);
18739
- },
18740
-
18741
- // Remove all errors who's error attribute is empty (null or undefined)
18742
- pruneEmptyErrors: function(errors) {
18743
- return errors.filter(function(error) {
18744
- return !v.isEmpty(error.error);
18745
- });
18746
- },
18747
-
18748
- // In
18749
- // [{error: ["err1", "err2"], ...}]
18750
- // Out
18751
- // [{error: "err1", ...}, {error: "err2", ...}]
18752
- //
18753
- // All attributes in an error with multiple messages are duplicated
18754
- // when expanding the errors.
18755
- expandMultipleErrors: function(errors) {
18756
- var ret = [];
18757
- errors.forEach(function(error) {
18758
- // Removes errors without a message
18759
- if (v.isArray(error.error)) {
18760
- error.error.forEach(function(msg) {
18761
- ret.push(v.extend({}, error, {error: msg}));
18762
- });
18763
- } else {
18764
- ret.push(error);
18765
- }
18766
- });
18767
- return ret;
18768
- },
18769
-
18770
- // Converts the error mesages by prepending the attribute name unless the
18771
- // message is prefixed by ^
18772
- convertErrorMessages: function(errors, options) {
18773
- options = options || {};
18774
-
18775
- var ret = [];
18776
- errors.forEach(function(errorInfo) {
18777
- var error = v.result(errorInfo.error,
18778
- errorInfo.value,
18779
- errorInfo.attribute,
18780
- errorInfo.options,
18781
- errorInfo.attributes,
18782
- errorInfo.globalOptions);
18783
-
18784
- if (!v.isString(error)) {
18785
- ret.push(errorInfo);
18786
- return;
18787
- }
18788
-
18789
- if (error[0] === '^') {
18790
- error = error.slice(1);
18791
- } else if (options.fullMessages !== false) {
18792
- error = v.capitalize(v.prettify(errorInfo.attribute)) + " " + error;
18793
- }
18794
- error = error.replace(/\\\^/g, "^");
18795
- error = v.format(error, {value: v.stringifyValue(errorInfo.value)});
18796
- ret.push(v.extend({}, errorInfo, {error: error}));
18797
- });
18798
- return ret;
18799
- },
18800
-
18801
- // In:
18802
- // [{attribute: "<attributeName>", ...}]
18803
- // Out:
18804
- // {"<attributeName>": [{attribute: "<attributeName>", ...}]}
18805
- groupErrorsByAttribute: function(errors) {
18806
- var ret = {};
18807
- errors.forEach(function(error) {
18808
- var list = ret[error.attribute];
18809
- if (list) {
18810
- list.push(error);
18811
- } else {
18812
- ret[error.attribute] = [error];
18813
- }
18814
- });
18815
- return ret;
18816
- },
18817
-
18818
- // In:
18819
- // [{error: "<message 1>", ...}, {error: "<message 2>", ...}]
18820
- // Out:
18821
- // ["<message 1>", "<message 2>"]
18822
- flattenErrorsToArray: function(errors) {
18823
- return errors.map(function(error) { return error.error; });
18824
- },
18825
-
18826
- cleanAttributes: function(attributes, whitelist) {
18827
- function whitelistCreator(obj, key, last) {
18828
- if (v.isObject(obj[key])) {
18829
- return obj[key];
18830
- }
18831
- return (obj[key] = last ? true : {});
18832
- }
18833
-
18834
- function buildObjectWhitelist(whitelist) {
18835
- var ow = {}
18836
- , lastObject
18837
- , attr;
18838
- for (attr in whitelist) {
18839
- if (!whitelist[attr]) {
18840
- continue;
18841
- }
18842
- v.forEachKeyInKeypath(ow, attr, whitelistCreator);
18843
- }
18844
- return ow;
18845
- }
18846
-
18847
- function cleanRecursive(attributes, whitelist) {
18848
- if (!v.isObject(attributes)) {
18849
- return attributes;
18850
- }
18851
-
18852
- var ret = v.extend({}, attributes)
18853
- , w
18854
- , attribute;
18855
-
18856
- for (attribute in attributes) {
18857
- w = whitelist[attribute];
18858
-
18859
- if (v.isObject(w)) {
18860
- ret[attribute] = cleanRecursive(ret[attribute], w);
18861
- } else if (!w) {
18862
- delete ret[attribute];
18863
- }
18864
- }
18865
- return ret;
18866
- }
18867
-
18868
- if (!v.isObject(whitelist) || !v.isObject(attributes)) {
18869
- return {};
18870
- }
18871
-
18872
- whitelist = buildObjectWhitelist(whitelist);
18873
- return cleanRecursive(attributes, whitelist);
18874
- },
18875
-
18876
- exposeModule: function(validate, root, exports, module, define) {
18877
- if (exports) {
18878
- if (module && module.exports) {
18879
- exports = module.exports = validate;
18880
- }
18881
- exports.validate = validate;
18882
- } else {
18883
- root.validate = validate;
18884
- if (validate.isFunction(define) && define.amd) {
18885
- define([], function () { return validate; });
18886
- }
18887
- }
18888
- },
18889
-
18890
- warn: function(msg) {
18891
- if (typeof console !== "undefined" && console.warn) {
18892
- console.warn("[validate.js] " + msg);
18893
- }
18894
- },
18895
-
18896
- error: function(msg) {
18897
- if (typeof console !== "undefined" && console.error) {
18898
- console.error("[validate.js] " + msg);
18899
- }
18900
- }
18901
- });
18902
-
18903
- validate.validators = {
18904
- // Presence validates that the value isn't empty
18905
- presence: function(value, options) {
18906
- options = v.extend({}, this.options, options);
18907
- if (v.isEmpty(value)) {
18908
- return options.message || this.message || "can't be blank";
18909
- }
18910
- },
18911
- length: function(value, options, attribute) {
18912
- // Empty values are allowed
18913
- if (v.isEmpty(value)) {
18914
- return;
18915
- }
18916
-
18917
- options = v.extend({}, this.options, options);
18918
-
18919
- var is = options.is
18920
- , maximum = options.maximum
18921
- , minimum = options.minimum
18922
- , tokenizer = options.tokenizer || function(val) { return val; }
18923
- , err
18924
- , errors = [];
18925
-
18926
- value = tokenizer(value);
18927
- var length = value.length;
18928
- if(!v.isNumber(length)) {
18929
- v.error(v.format("Attribute %{attr} has a non numeric value for `length`", {attr: attribute}));
18930
- return options.message || this.notValid || "has an incorrect length";
18931
- }
18932
-
18933
- // Is checks
18934
- if (v.isNumber(is) && length !== is) {
18935
- err = options.wrongLength ||
18936
- this.wrongLength ||
18937
- "is the wrong length (should be %{count} characters)";
18938
- errors.push(v.format(err, {count: is}));
18939
- }
18940
-
18941
- if (v.isNumber(minimum) && length < minimum) {
18942
- err = options.tooShort ||
18943
- this.tooShort ||
18944
- "is too short (minimum is %{count} characters)";
18945
- errors.push(v.format(err, {count: minimum}));
18946
- }
18947
-
18948
- if (v.isNumber(maximum) && length > maximum) {
18949
- err = options.tooLong ||
18950
- this.tooLong ||
18951
- "is too long (maximum is %{count} characters)";
18952
- errors.push(v.format(err, {count: maximum}));
18953
- }
18954
-
18955
- if (errors.length > 0) {
18956
- return options.message || errors;
18957
- }
18958
- },
18959
- numericality: function(value, options) {
18960
- // Empty values are fine
18961
- if (v.isEmpty(value)) {
18962
- return;
18963
- }
18964
-
18965
- options = v.extend({}, this.options, options);
18966
-
18967
- var errors = []
18968
- , name
18969
- , count
18970
- , checks = {
18971
- greaterThan: function(v, c) { return v > c; },
18972
- greaterThanOrEqualTo: function(v, c) { return v >= c; },
18973
- equalTo: function(v, c) { return v === c; },
18974
- lessThan: function(v, c) { return v < c; },
18975
- lessThanOrEqualTo: function(v, c) { return v <= c; }
18976
- };
18977
-
18978
- // Coerce the value to a number unless we're being strict.
18979
- if (options.noStrings !== true && v.isString(value)) {
18980
- value = +value;
18981
- }
18982
-
18983
- // If it's not a number we shouldn't continue since it will compare it.
18984
- if (!v.isNumber(value)) {
18985
- return options.message || options.notValid || this.notValid || "is not a number";
18986
- }
18987
-
18988
- // Same logic as above, sort of. Don't bother with comparisons if this
18989
- // doesn't pass.
18990
- if (options.onlyInteger && !v.isInteger(value)) {
18991
- return options.message || options.notInteger || this.notInteger || "must be an integer";
18992
- }
18993
-
18994
- for (name in checks) {
18995
- count = options[name];
18996
- if (v.isNumber(count) && !checks[name](value, count)) {
18997
- // This picks the default message if specified
18998
- // For example the greaterThan check uses the message from
18999
- // this.notGreaterThan so we capitalize the name and prepend "not"
19000
- var key = "not" + v.capitalize(name);
19001
- var msg = options[key] || this[key] || "must be %{type} %{count}";
19002
-
19003
- errors.push(v.format(msg, {
19004
- count: count,
19005
- type: v.prettify(name)
19006
- }));
19007
- }
19008
- }
19009
-
19010
- if (options.odd && value % 2 !== 1) {
19011
- errors.push(options.notOdd || this.notOdd || "must be odd");
19012
- }
19013
- if (options.even && value % 2 !== 0) {
19014
- errors.push(options.notEven || this.notEven || "must be even");
19015
- }
19016
-
19017
- if (errors.length) {
19018
- return options.message || errors;
19019
- }
19020
- },
19021
- datetime: v.extend(function(value, options) {
19022
- if (!v.isFunction(this.parse) || !v.isFunction(this.format)) {
19023
- throw new Error("Both the parse and format functions needs to be set to use the datetime/date validator");
19024
- }
19025
-
19026
- // Empty values are fine
19027
- if (v.isEmpty(value)) {
19028
- return;
19029
- }
19030
-
19031
- options = v.extend({}, this.options, options);
19032
-
19033
- var err
19034
- , errors = []
19035
- , earliest = options.earliest ? this.parse(options.earliest, options) : NaN
19036
- , latest = options.latest ? this.parse(options.latest, options) : NaN;
19037
-
19038
- value = this.parse(value, options);
19039
-
19040
- // 86400000 is the number of seconds in a day, this is used to remove
19041
- // the time from the date
19042
- if (isNaN(value) || options.dateOnly && value % 86400000 !== 0) {
19043
- return options.message || this.notValid || "must be a valid date";
19044
- }
19045
-
19046
- if (!isNaN(earliest) && value < earliest) {
19047
- err = this.tooEarly || "must be no earlier than %{date}";
19048
- err = v.format(err, {date: this.format(earliest, options)});
19049
- errors.push(err);
19050
- }
19051
-
19052
- if (!isNaN(latest) && value > latest) {
19053
- err = this.tooLate || "must be no later than %{date}";
19054
- err = v.format(err, {date: this.format(latest, options)});
19055
- errors.push(err);
19056
- }
19057
-
19058
- if (errors.length) {
19059
- return options.message || errors;
19060
- }
19061
- }, {
19062
- parse: null,
19063
- format: null
19064
- }),
19065
- date: function(value, options) {
19066
- options = v.extend({}, options, {dateOnly: true});
19067
- return v.validators.datetime.call(v.validators.datetime, value, options);
19068
- },
19069
- format: function(value, options) {
19070
- if (v.isString(options) || (options instanceof RegExp)) {
19071
- options = {pattern: options};
19072
- }
19073
-
19074
- options = v.extend({}, this.options, options);
19075
-
19076
- var message = options.message || this.message || "is invalid"
19077
- , pattern = options.pattern
19078
- , match;
19079
-
19080
- // Empty values are allowed
19081
- if (v.isEmpty(value)) {
19082
- return;
19083
- }
19084
- if (!v.isString(value)) {
19085
- return message;
19086
- }
19087
-
19088
- if (v.isString(pattern)) {
19089
- pattern = new RegExp(options.pattern, options.flags);
19090
- }
19091
- match = pattern.exec(value);
19092
- if (!match || match[0].length != value.length) {
19093
- return message;
19094
- }
19095
- },
19096
- inclusion: function(value, options) {
19097
- // Empty values are fine
19098
- if (v.isEmpty(value)) {
19099
- return;
19100
- }
19101
- if (v.isArray(options)) {
19102
- options = {within: options};
19103
- }
19104
- options = v.extend({}, this.options, options);
19105
- if (v.contains(options.within, value)) {
19106
- return;
19107
- }
19108
- var message = options.message ||
19109
- this.message ||
19110
- "^%{value} is not included in the list";
19111
- return v.format(message, {value: value});
19112
- },
19113
- exclusion: function(value, options) {
19114
- // Empty values are fine
19115
- if (v.isEmpty(value)) {
19116
- return;
19117
- }
19118
- if (v.isArray(options)) {
19119
- options = {within: options};
19120
- }
19121
- options = v.extend({}, this.options, options);
19122
- if (!v.contains(options.within, value)) {
19123
- return;
19124
- }
19125
- var message = options.message || this.message || "^%{value} is restricted";
19126
- return v.format(message, {value: value});
19127
- },
19128
- email: v.extend(function(value, options) {
19129
- options = v.extend({}, this.options, options);
19130
- var message = options.message || this.message || "is not a valid email";
19131
- // Empty values are fine
19132
- if (v.isEmpty(value)) {
19133
- return;
19134
- }
19135
- if (!v.isString(value)) {
19136
- return message;
19137
- }
19138
- if (!this.PATTERN.exec(value)) {
19139
- return message;
19140
- }
19141
- }, {
19142
- PATTERN: /^[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9\u007F-\uffff!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i
19143
- }),
19144
- equality: function(value, options, attribute, attributes) {
19145
- if (v.isEmpty(value)) {
19146
- return;
19147
- }
19148
-
19149
- if (v.isString(options)) {
19150
- options = {attribute: options};
19151
- }
19152
- options = v.extend({}, this.options, options);
19153
- var message = options.message ||
19154
- this.message ||
19155
- "is not equal to %{attribute}";
19156
-
19157
- if (v.isEmpty(options.attribute) || !v.isString(options.attribute)) {
19158
- throw new Error("The attribute must be a non empty string");
19159
- }
19160
-
19161
- var otherValue = v.getDeepObjectValue(attributes, options.attribute)
19162
- , comparator = options.comparator || function(v1, v2) {
19163
- return v1 === v2;
19164
- };
19165
-
19166
- if (!comparator(value, otherValue, options, attribute, attributes)) {
19167
- return v.format(message, {attribute: v.prettify(options.attribute)});
19168
- }
19169
- },
19170
-
19171
- // A URL validator that is used to validate URLs with the ability to
19172
- // restrict schemes and some domains.
19173
- url: function(value, options) {
19174
- if (v.isEmpty(value)) {
19175
- return;
19176
- }
19177
-
19178
- options = v.extend({}, this.options, options);
19179
-
19180
- var message = options.message || this.message || "is not a valid url"
19181
- , schemes = options.schemes || this.schemes || ['http', 'https']
19182
- , allowLocal = options.allowLocal || this.allowLocal || false;
19183
-
19184
- if (!v.isString(value)) {
19185
- return message;
19186
- }
19187
-
19188
- // https://gist.github.com/dperini/729294
19189
- var regex =
19190
- "^" +
19191
- // schemes
19192
- "(?:(?:" + schemes.join("|") + "):\\/\\/)" +
19193
- // credentials
19194
- "(?:\\S+(?::\\S*)?@)?";
19195
-
19196
- regex += "(?:";
19197
-
19198
- var hostname =
19199
- "(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)" +
19200
- "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*" +
19201
- "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))";
19202
-
19203
- // This ia a special case for the localhost hostname
19204
- if (allowLocal) {
19205
- hostname = "(?:localhost|" + hostname + ")";
19206
- } else {
19207
- // private & local addresses
19208
- regex +=
19209
- "(?!10(?:\\.\\d{1,3}){3})" +
19210
- "(?!127(?:\\.\\d{1,3}){3})" +
19211
- "(?!169\\.254(?:\\.\\d{1,3}){2})" +
19212
- "(?!192\\.168(?:\\.\\d{1,3}){2})" +
19213
- "(?!172" +
19214
- "\\.(?:1[6-9]|2\\d|3[0-1])" +
19215
- "(?:\\.\\d{1,3})" +
19216
- "{2})";
19217
- }
19218
-
19219
- // reserved addresses
19220
- regex +=
19221
- "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
19222
- "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
19223
- "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
19224
- "|" +
19225
- hostname +
19226
- // port number
19227
- "(?::\\d{2,5})?" +
19228
- // path
19229
- "(?:\\/[^\\s]*)?" +
19230
- "$";
19231
-
19232
- var PATTERN = new RegExp(regex, 'i');
19233
- if (!PATTERN.exec(value)) {
19234
- return message;
19235
- }
19236
- }
19237
- };
19238
-
19239
- validate.exposeModule(validate, this, exports, module, define);
19240
- }).call(this,
19241
- typeof exports !== 'undefined' ? /* istanbul ignore next */ exports : null,
19242
- typeof module !== 'undefined' ? /* istanbul ignore next */ module : null,
19243
- typeof define !== 'undefined' ? /* istanbul ignore next */ define : null);
19244
-
19245
18235
  },{}]},{},[1])(1)
19246
18236
  });