comprodls-sdk 2.113.0 → 2.116.0

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