@postman/wsdl-to-postman
Version:
Convert a given WSDL specification (1.1) to Postman Collection
26,477 lines • 879 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.xsd2jsonschemafaker = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const XsdAttributes = require('./src/xmlschema/xsdAttributes');
const XsdAttributeValues = require('./src/xmlschema/xsdAttributeValues');
const XsdElements = require('./src/xmlschema/xsdElements');
const XsdNodeTypes = require('./src/xmlschema/xsdNodeTypes');
const XsdFile = require('./src/xmlschema/xsdFileXmlDom');
const JsonSchemaTypes = require('./src/jsonschema/jsonSchemaTypes');
const JsonSchemaFormats = require('./src/jsonschema/jsonSchemaFormats');
const JsonSchemaFile = require('./src/jsonschema/jsonSchemaFile');
const JsonSchemaFileDraft04 = require('./src/jsonschema/jsonSchemaFileDraft04');
const JsonSchemaFileDraft06 = require('./src/jsonschema/jsonSchemaFileDraft06');
const JsonSchemaFileDraft07 = require('./src/jsonschema/jsonSchemaFileDraft07');
const JsonSchemaRef = require('./src/jsonschema/jsonSchemaRef');
const DefaultConversionVisitor = require('./src/visitors/defaultConversionVisitor');
const BaseConversionVisitor = require('./src/visitors/baseConversionVisitor');
const XmlUsageVisitor = require('./src/visitors/xmlUsageVisitor');
const XmlUsageVisitorSum = require('./src/visitors/xmlUsageVisitorSum');
const Xsd2JsonSchema = require('./src/xsd2JsonSchema');
const Processor = require('./src/processor');
const ConverterDraft04 = require('./src/converterDraft04');
const ConverterDraft06 = require('./src/converterDraft06');
const ConverterDraft07 = require('./src/converterDraft07');
const BaseSpecialCaseIdentifier = require('./src/baseSpecialCaseIdentifier');
const BuiltInTypeConverter = require('./src/builtInTypeConverter');
const NamespaceManager = require('./src/namespaceManager');
const PropertyDefinable = require('./src/propertyDefinable');
const DepthFirstTraversal = require('./src/depthFirstTraversal');
const Constants = require('./src/constants');
const ParsingState = require('./src/parsingState').ParsingState;
const State = require('./src/parsingState').State;
const ForwardReference = require('./src/forwardReference');
// XML Schema modules
module.exports.XsdAttributes = XsdAttributes;
module.exports.XsdAttributeValues = XsdAttributeValues;
module.exports.XsdElements = XsdElements;
module.exports.XsdNodeTypes = XsdNodeTypes;
module.exports.XsdFile = XsdFile;
// JSON Schema modules
module.exports.JsonSchemaTypes = JsonSchemaTypes;
module.exports.JsonSchemaFormats = JsonSchemaFormats;
module.exports.JsonSchemaFile = JsonSchemaFile;
module.exports.JsonSchemaFileDraft04 = JsonSchemaFileDraft04;
module.exports.JsonSchemaFileDraft06 = JsonSchemaFileDraft06;
module.exports.JsonSchemaFileDraft07 = JsonSchemaFileDraft07;
module.exports.JsonSchemaRef = JsonSchemaRef;
// Visitors
module.exports.DefaultConversionVisitor = DefaultConversionVisitor;
module.exports.BaseConversionVisitor = BaseConversionVisitor;
module.exports.XmlUsageVisitor = XmlUsageVisitor;
module.exports.XmlUsageVisitorSum = XmlUsageVisitorSum;
// Core modules
module.exports.Xsd2JsonSchema = Xsd2JsonSchema;
module.exports.Processor = Processor;
module.exports.ConverterDraft04 = ConverterDraft04;
module.exports.ConverterDraft06 = ConverterDraft06;
module.exports.ConverterDraft07 = ConverterDraft07;
module.exports.BaseSpecialCaseIdentifier = BaseSpecialCaseIdentifier;
module.exports.BuiltInTypeConverter = BuiltInTypeConverter;
module.exports.NamespaceManager = NamespaceManager;
module.exports.PropertyDefinable = PropertyDefinable;
module.exports.DepthFirstTraversal = DepthFirstTraversal;
module.exports.Constants = Constants;
module.exports.ParsingState = ParsingState;
module.exports.State = State;
module.exports.ForwardReference = ForwardReference;
},{"./src/baseSpecialCaseIdentifier":89,"./src/builtInTypeConverter":90,"./src/constants":91,"./src/converterDraft04":92,"./src/converterDraft06":93,"./src/converterDraft07":94,"./src/depthFirstTraversal":95,"./src/forwardReference":96,"./src/jsonschema/jsonSchemaFile":97,"./src/jsonschema/jsonSchemaFileDraft04":98,"./src/jsonschema/jsonSchemaFileDraft06":99,"./src/jsonschema/jsonSchemaFileDraft07":100,"./src/jsonschema/jsonSchemaFormats":101,"./src/jsonschema/jsonSchemaRef":102,"./src/jsonschema/jsonSchemaTypes":106,"./src/namespaceManager":107,"./src/parsingState":108,"./src/processor":109,"./src/propertyDefinable":110,"./src/visitors/baseConversionVisitor":114,"./src/visitors/defaultConversionVisitor":115,"./src/visitors/xmlUsageVisitor":117,"./src/visitors/xmlUsageVisitorSum":118,"./src/xmlschema/xsdAttributeValues":119,"./src/xmlschema/xsdAttributes":120,"./src/xmlschema/xsdElements":121,"./src/xmlschema/xsdFileXmlDom":122,"./src/xmlschema/xsdNodeTypes":123,"./src/xsd2JsonSchema":124}],2:[function(require,module,exports){
(function (Buffer){(function (){
var clone = (function() {
'use strict';
function _instanceof(obj, type) {
return type != null && obj instanceof type;
}
var nativeMap;
try {
nativeMap = Map;
} catch(_) {
// maybe a reference error because no `Map`. Give it a dummy value that no
// value will ever be an instanceof.
nativeMap = function() {};
}
var nativeSet;
try {
nativeSet = Set;
} catch(_) {
nativeSet = function() {};
}
var nativePromise;
try {
nativePromise = Promise;
} catch(_) {
nativePromise = function() {};
}
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
* @param `includeNonEnumerable` - set to true if the non-enumerable properties
* should be cloned as well. Non-enumerable properties on the prototype
* chain will be ignored. (optional - false by default)
*/
function clone(parent, circular, depth, prototype, includeNonEnumerable) {
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
includeNonEnumerable = circular.includeNonEnumerable;
circular = circular.circular;
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (_instanceof(parent, nativeMap)) {
child = new nativeMap();
} else if (_instanceof(parent, nativeSet)) {
child = new nativeSet();
} else if (_instanceof(parent, nativePromise)) {
child = new nativePromise(function (resolve, reject) {
parent.then(function(value) {
resolve(_clone(value, depth - 1));
}, function(err) {
reject(_clone(err, depth - 1));
});
});
} else if (clone.__isArray(parent)) {
child = [];
} else if (clone.__isRegExp(parent)) {
child = new RegExp(parent.source, __getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (clone.__isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
if (Buffer.allocUnsafe) {
// Node.js >= 4.5.0
child = Buffer.allocUnsafe(parent.length);
} else {
// Older Node.js versions
child = new Buffer(parent.length);
}
parent.copy(child);
return child;
} else if (_instanceof(parent, Error)) {
child = Object.create(parent);
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
if (_instanceof(parent, nativeMap)) {
parent.forEach(function(value, key) {
var keyChild = _clone(key, depth - 1);
var valueChild = _clone(value, depth - 1);
child.set(keyChild, valueChild);
});
}
if (_instanceof(parent, nativeSet)) {
parent.forEach(function(value) {
var entryChild = _clone(value, depth - 1);
child.add(entryChild);
});
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(parent);
for (var i = 0; i < symbols.length; i++) {
// Don't need to worry about cloning a symbol because it is a primitive,
// like a number or string.
var symbol = symbols[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {
continue;
}
child[symbol] = _clone(parent[symbol], depth - 1);
if (!descriptor.enumerable) {
Object.defineProperty(child, symbol, {
enumerable: false
});
}
}
}
if (includeNonEnumerable) {
var allPropertyNames = Object.getOwnPropertyNames(parent);
for (var i = 0; i < allPropertyNames.length; i++) {
var propertyName = allPropertyNames[i];
var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);
if (descriptor && descriptor.enumerable) {
continue;
}
child[propertyName] = _clone(parent[propertyName], depth - 1);
Object.defineProperty(child, propertyName, {
enumerable: false
});
}
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function clonePrototype(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
// private utility functions
function __objToStr(o) {
return Object.prototype.toString.call(o);
}
clone.__objToStr = __objToStr;
function __isDate(o) {
return typeof o === 'object' && __objToStr(o) === '[object Date]';
}
clone.__isDate = __isDate;
function __isArray(o) {
return typeof o === 'object' && __objToStr(o) === '[object Array]';
}
clone.__isArray = __isArray;
function __isRegExp(o) {
return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
}
clone.__isRegExp = __isRegExp;
function __getRegExpFlags(re) {
var flags = '';
if (re.global) flags += 'g';
if (re.ignoreCase) flags += 'i';
if (re.multiline) flags += 'm';
return flags;
}
clone.__getRegExpFlags = __getRegExpFlags;
return clone;
})();
if (typeof module === 'object' && module.exports) {
module.exports = clone;
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"buffer":126}],3:[function(require,module,exports){
(function (process){(function (){
"use strict";
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
/**
* Colors.
*/
exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
} // Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
} // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
var c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
var index = 0;
var lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, function (match) {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
*
* @api public
*/
function log() {
var _console;
// This hackery is required for IE8/9, where
// the `console.log` function doesn't have 'apply'
return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
var r;
try {
r = exports.storage.getItem('debug');
} catch (error) {} // Swallow
// XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
var formatters = module.exports.formatters;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
}).call(this)}).call(this,require('_process'))
},{"./common":4,"_process":129}],4:[function(require,module,exports){
"use strict";
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
Object.keys(env).forEach(function (key) {
createDebug[key] = env[key];
});
/**
* Active `debug` instances.
*/
createDebug.instances = [];
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
var hash = 0;
for (var i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
var prevTime;
function debug() {
// Disabled?
if (!debug.enabled) {
return;
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var self = debug; // Set `diff` timestamp
var curr = Number(new Date());
var ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
} // Apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return match;
}
index++;
var formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
var val = args[index];
match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
}); // Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
var logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.enabled = createDebug.enabled(namespace);
debug.useColors = createDebug.useColors();
debug.color = selectColor(namespace);
debug.destroy = destroy;
debug.extend = extend; // Debug.formatArgs = formatArgs;
// debug.rawLog = rawLog;
// env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
createDebug.instances.push(debug);
return debug;
}
function destroy() {
var index = createDebug.instances.indexOf(this);
if (index !== -1) {
createDebug.instances.splice(index, 1);
return true;
}
return false;
}
function extend(namespace, delimiter) {
return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.names = [];
createDebug.skips = [];
var i;
var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
var len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
for (i = 0; i < createDebug.instances.length; i++) {
var instance = createDebug.instances[i];
instance.enabled = createDebug.enabled(instance.namespace);
}
}
/**
* Disable debug output.
*
* @api public
*/
function disable() {
createDebug.enable('');
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
var i;
var len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
},{"ms":6}],5:[function(require,module,exports){
'use strict';
/* globals Symbol: false, Uint8Array: false, WeakMap: false */
/*!
* deep-eql
* Copyright(c) 2013 Jake Luer <jake@alogicalparadox.com>
* MIT Licensed
*/
var type = require('type-detect');
function FakeMap() {
this._key = 'chai/deep-eql__' + Math.random() + Date.now();
}
FakeMap.prototype = {
get: function getMap(key) {
return key[this._key];
},
set: function setMap(key, value) {
if (Object.isExtensible(key)) {
Object.defineProperty(key, this._key, {
value: value,
configurable: true,
});
}
},
};
var MemoizeMap = typeof WeakMap === 'function' ? WeakMap : FakeMap;
/*!
* Check to see if the MemoizeMap has recorded a result of the two operands
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {MemoizeMap} memoizeMap
* @returns {Boolean|null} result
*/
function memoizeCompare(leftHandOperand, rightHandOperand, memoizeMap) {
// Technically, WeakMap keys can *only* be objects, not primitives.
if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) {
return null;
}
var leftHandMap = memoizeMap.get(leftHandOperand);
if (leftHandMap) {
var result = leftHandMap.get(rightHandOperand);
if (typeof result === 'boolean') {
return result;
}
}
return null;
}
/*!
* Set the result of the equality into the MemoizeMap
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {MemoizeMap} memoizeMap
* @param {Boolean} result
*/
function memoizeSet(leftHandOperand, rightHandOperand, memoizeMap, result) {
// Technically, WeakMap keys can *only* be objects, not primitives.
if (!memoizeMap || isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) {
return;
}
var leftHandMap = memoizeMap.get(leftHandOperand);
if (leftHandMap) {
leftHandMap.set(rightHandOperand, result);
} else {
leftHandMap = new MemoizeMap();
leftHandMap.set(rightHandOperand, result);
memoizeMap.set(leftHandOperand, leftHandMap);
}
}
/*!
* Primary Export
*/
module.exports = deepEqual;
module.exports.MemoizeMap = MemoizeMap;
/**
* Assert deeply nested sameValue equality between two objects of any type.
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {Object} [options] (optional) Additional options
* @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality.
* @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of
complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular
references to blow the stack.
* @return {Boolean} equal match
*/
function deepEqual(leftHandOperand, rightHandOperand, options) {
// If we have a comparator, we can't assume anything; so bail to its check first.
if (options && options.comparator) {
return extensiveDeepEqual(leftHandOperand, rightHandOperand, options);
}
var simpleResult = simpleEqual(leftHandOperand, rightHandOperand);
if (simpleResult !== null) {
return simpleResult;
}
// Deeper comparisons are pushed through to a larger function
return extensiveDeepEqual(leftHandOperand, rightHandOperand, options);
}
/**
* Many comparisons can be canceled out early via simple equality or primitive checks.
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @return {Boolean|null} equal match
*/
function simpleEqual(leftHandOperand, rightHandOperand) {
// Equal references (except for Numbers) can be returned early
if (leftHandOperand === rightHandOperand) {
// Handle +-0 cases
return leftHandOperand !== 0 || 1 / leftHandOperand === 1 / rightHandOperand;
}
// handle NaN cases
if (
leftHandOperand !== leftHandOperand && // eslint-disable-line no-self-compare
rightHandOperand !== rightHandOperand // eslint-disable-line no-self-compare
) {
return true;
}
// Anything that is not an 'object', i.e. symbols, functions, booleans, numbers,
// strings, and undefined, can be compared by reference.
if (isPrimitive(leftHandOperand) || isPrimitive(rightHandOperand)) {
// Easy out b/c it would have passed the first equality check
return false;
}
return null;
}
/*!
* The main logic of the `deepEqual` function.
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {Object} [options] (optional) Additional options
* @param {Array} [options.comparator] (optional) Override default algorithm, determining custom equality.
* @param {Array} [options.memoize] (optional) Provide a custom memoization object which will cache the results of
complex objects for a speed boost. By passing `false` you can disable memoization, but this will cause circular
references to blow the stack.
* @return {Boolean} equal match
*/
function extensiveDeepEqual(leftHandOperand, rightHandOperand, options) {
options = options || {};
options.memoize = options.memoize === false ? false : options.memoize || new MemoizeMap();
var comparator = options && options.comparator;
// Check if a memoized result exists.
var memoizeResultLeft = memoizeCompare(leftHandOperand, rightHandOperand, options.memoize);
if (memoizeResultLeft !== null) {
return memoizeResultLeft;
}
var memoizeResultRight = memoizeCompare(rightHandOperand, leftHandOperand, options.memoize);
if (memoizeResultRight !== null) {
return memoizeResultRight;
}
// If a comparator is present, use it.
if (comparator) {
var comparatorResult = comparator(leftHandOperand, rightHandOperand);
// Comparators may return null, in which case we want to go back to default behavior.
if (comparatorResult === false || comparatorResult === true) {
memoizeSet(leftHandOperand, rightHandOperand, options.memoize, comparatorResult);
return comparatorResult;
}
// To allow comparators to override *any* behavior, we ran them first. Since it didn't decide
// what to do, we need to make sure to return the basic tests first before we move on.
var simpleResult = simpleEqual(leftHandOperand, rightHandOperand);
if (simpleResult !== null) {
// Don't memoize this, it takes longer to set/retrieve than to just compare.
return simpleResult;
}
}
var leftHandType = type(leftHandOperand);
if (leftHandType !== type(rightHandOperand)) {
memoizeSet(leftHandOperand, rightHandOperand, options.memoize, false);
return false;
}
// Temporarily set the operands in the memoize object to prevent blowing the stack
memoizeSet(leftHandOperand, rightHandOperand, options.memoize, true);
var result = extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options);
memoizeSet(leftHandOperand, rightHandOperand, options.memoize, result);
return result;
}
function extensiveDeepEqualByType(leftHandOperand, rightHandOperand, leftHandType, options) {
switch (leftHandType) {
case 'String':
case 'Number':
case 'Boolean':
case 'Date':
// If these types are their instance types (e.g. `new Number`) then re-deepEqual against their values
return deepEqual(leftHandOperand.valueOf(), rightHandOperand.valueOf());
case 'Promise':
case 'Symbol':
case 'function':
case 'WeakMap':
case 'WeakSet':
return leftHandOperand === rightHandOperand;
case 'Error':
return keysEqual(leftHandOperand, rightHandOperand, [ 'name', 'message', 'code' ], options);
case 'Arguments':
case 'Int8Array':
case 'Uint8Array':
case 'Uint8ClampedArray':
case 'Int16Array':
case 'Uint16Array':
case 'Int32Array':
case 'Uint32Array':
case 'Float32Array':
case 'Float64Array':
case 'Array':
return iterableEqual(leftHandOperand, rightHandOperand, options);
case 'RegExp':
return regexpEqual(leftHandOperand, rightHandOperand);
case 'Generator':
return generatorEqual(leftHandOperand, rightHandOperand, options);
case 'DataView':
return iterableEqual(new Uint8Array(leftHandOperand.buffer), new Uint8Array(rightHandOperand.buffer), options);
case 'ArrayBuffer':
return iterableEqual(new Uint8Array(leftHandOperand), new Uint8Array(rightHandOperand), options);
case 'Set':
return entriesEqual(leftHandOperand, rightHandOperand, options);
case 'Map':
return entriesEqual(leftHandOperand, rightHandOperand, options);
default:
return objectEqual(leftHandOperand, rightHandOperand, options);
}
}
/*!
* Compare two Regular Expressions for equality.
*
* @param {RegExp} leftHandOperand
* @param {RegExp} rightHandOperand
* @return {Boolean} result
*/
function regexpEqual(leftHandOperand, rightHandOperand) {
return leftHandOperand.toString() === rightHandOperand.toString();
}
/*!
* Compare two Sets/Maps for equality. Faster than other equality functions.
*
* @param {Set} leftHandOperand
* @param {Set} rightHandOperand
* @param {Object} [options] (Optional)
* @return {Boolean} result
*/
function entriesEqual(leftHandOperand, rightHandOperand, options) {
// IE11 doesn't support Set#entries or Set#@@iterator, so we need manually populate using Set#forEach
if (leftHandOperand.size !== rightHandOperand.size) {
return false;
}
if (leftHandOperand.size === 0) {
return true;
}
var leftHandItems = [];
var rightHandItems = [];
leftHandOperand.forEach(function gatherEntries(key, value) {
leftHandItems.push([ key, value ]);
});
rightHandOperand.forEach(function gatherEntries(key, value) {
rightHandItems.push([ key, value ]);
});
return iterableEqual(leftHandItems.sort(), rightHandItems.sort(), options);
}
/*!
* Simple equality for flat iterable objects such as Arrays, TypedArrays or Node.js buffers.
*
* @param {Iterable} leftHandOperand
* @param {Iterable} rightHandOperand
* @param {Object} [options] (Optional)
* @return {Boolean} result
*/
function iterableEqual(leftHandOperand, rightHandOperand, options) {
var length = leftHandOperand.length;
if (length !== rightHandOperand.length) {
return false;
}
if (length === 0) {
return true;
}
var index = -1;
while (++index < length) {
if (deepEqual(leftHandOperand[index], rightHandOperand[index], options) === false) {
return false;
}
}
return true;
}
/*!
* Simple equality for generator objects such as those returned by generator functions.
*
* @param {Iterable} leftHandOperand
* @param {Iterable} rightHandOperand
* @param {Object} [options] (Optional)
* @return {Boolean} result
*/
function generatorEqual(leftHandOperand, rightHandOperand, options) {
return iterableEqual(getGeneratorEntries(leftHandOperand), getGeneratorEntries(rightHandOperand), options);
}
/*!
* Determine if the given object has an @@iterator function.
*
* @param {Object} target
* @return {Boolean} `true` if the object has an @@iterator function.
*/
function hasIteratorFunction(target) {
return typeof Symbol !== 'undefined' &&
typeof target === 'object' &&
typeof Symbol.iterator !== 'undefined' &&
typeof target[Symbol.iterator] === 'function';
}
/*!
* Gets all iterator entries from the given Object. If the Object has no @@iterator function, returns an empty array.
* This will consume the iterator - which could have side effects depending on the @@iterator implementation.
*
* @param {Object} target
* @returns {Array} an array of entries from the @@iterator function
*/
function getIteratorEntries(target) {
if (hasIteratorFunction(target)) {
try {
return getGeneratorEntries(target[Symbol.iterator]());
} catch (iteratorError) {
return [];
}
}
return [];
}
/*!
* Gets all entries from a Generator. This will consume the generator - which could have side effects.
*
* @param {Generator} target
* @returns {Array} an array of entries from the Generator.
*/
function getGeneratorEntries(generator) {
var generatorResult = generator.next();
var accumulator = [ generatorResult.value ];
while (generatorResult.done === false) {
generatorResult = generator.next();
accumulator.push(generatorResult.value);
}
return accumulator;
}
/*!
* Gets all own and inherited enumerable keys from a target.
*
* @param {Object} target
* @returns {Array} an array of own and inherited enumerable keys from the target.
*/
function getEnumerableKeys(target) {
var keys = [];
for (var key in target) {
keys.push(key);
}
return keys;
}
/*!
* Determines if two objects have matching values, given a set of keys. Defers to deepEqual for the equality check of
* each key. If any value of the given key is not equal, the function will return false (early).
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {Array} keys An array of keys to compare the values of leftHandOperand and rightHandOperand against
* @param {Object} [options] (Optional)
* @return {Boolean} result
*/
function keysEqual(leftHandOperand, rightHandOperand, keys, options) {
var length = keys.length;
if (length === 0) {
return true;
}
for (var i = 0; i < length; i += 1) {
if (deepEqual(leftHandOperand[keys[i]], rightHandOperand[keys[i]], options) === false) {
return false;
}
}
return true;
}
/*!
* Recursively check the equality of two Objects. Once basic sameness has been established it will defer to `deepEqual`
* for each enumerable key in the object.
*
* @param {Mixed} leftHandOperand
* @param {Mixed} rightHandOperand
* @param {Object} [options] (Optional)
* @return {Boolean} result
*/
function objectEqual(leftHandOperand, rightHandOperand, options) {
var leftHandKeys = getEnumerableKeys(leftHandOperand);
var rightHandKeys = getEnumerableKeys(rightHandOperand);
if (leftHandKeys.length && leftHandKeys.length === rightHandKeys.length) {
leftHandKeys.sort();
rightHandKeys.sort();
if (iterableEqual(leftHandKeys, rightHandKeys) === false) {
return false;
}
return keysEqual(leftHandOperand, rightHandOperand, leftHandKeys, options);
}
var leftHandEntries = getIteratorEntries(leftHandOperand);
var rightHandEntries = getIteratorEntries(rightHandOperand);
if (leftHandEntries.length && leftHandEntries.length === rightHandEntries.length) {
leftHandEntries.sort();
rightHandEntries.sort();
return iterableEqual(leftHandEntries, rightHandEntries, options);
}
if (leftHandKeys.length === 0 &&
leftHandEntries.length === 0 &&
rightHandKeys.length === 0 &&
rightHandEntries.length === 0) {
return true;
}
return false;
}
/*!
* Returns true if the argument is a primitive.
*
* This intentionally returns true for all objects that can be compared by reference,
* including functions and symbols.
*
* @param {Mixed} value
* @return {Boolean} result
*/
function isPrimitive(value) {
return value === null || typeof value !== 'object';
}
},{"type-detect":8}],6:[function(require,module,exports){
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
},{}],7:[function(require,module,exports){
(function (process){(function (){
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
}
}
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
var res = '';
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47 /*/*/)
break;
else
code = 47 /*/*/;
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf('/');
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += '/..';
else
res = '..';
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += '/' + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 /*.*/ && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = '';
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === undefined)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return '/' + resolvedPath;
else
return '/';
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return '.';
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return '.';
var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute);
if (path.length === 0 && !isAbsolute) path = '.';
if (path.length > 0 && trailingSeparator) path += '/';
if (isAbsolute) return '/' + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
},
join: function join() {
if (arguments.length === 0)
return '.';
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === undefined)
joined = arg;
else
joined += '/' + arg;
}
}
if (joined === undefined)
return '.';
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return '';
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return '';
// Trim any leading backslashes
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
// Trim any leading backslashes
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47 /*/*/)
lastCommonSep = i;
}
var out = '';
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0)
out += '..';
else
out += '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47 /*/*/)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
},
basename: function basename(path, ext) {
if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return '';
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format('/', pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: '', dir: '', base: '', ext: '', name: '' };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute = code === 47 /*/*/;
var start;
if (isAbsolute) {
ret.root = '/';
start = 1;
} else {
start = 0;
}
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
var i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';
return ret;
},
sep: '/',
delimiter: ':',
win32: null,
posix: null
};
posix.posix = posix;
module.exports = posix;
}).call(this)}).call(this,require('_process'))
},{"_process":129}],8:[function(require,module,exports){
(function (global){(function (){
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.typeDetect = factory());
}(this, (function () { 'use strict';
/* !
* type-detect
* Copyright(c) 2013 jake luer <jake@alogicalparadox.com>
* MIT Licensed
*/
var promiseExists = typeof Promise === 'function';
/* eslint-disable no-undef */
var globalObject = typeof self === 'object' ? self : global; // eslint-disable-line id-blacklist
var symbolExists = typeof Symbol !== 'undefined';
var mapExists = typeof Map !== 'undefined';
var setExists = typeof Set !== 'undefined';
var weakMapExists = typeof WeakMap !== 'undefined';
var weakSetExists = typeof WeakSet !== 'undefined';
var dataViewExists = typeof DataView !== 'undefined';
var symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined';
var symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined';
var setEntriesExists = setExists && typeof Set.prototype.entries === 'function';
var mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function';
var setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries());
var mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries());
var arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function';
var arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]());
var stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function';
var stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]());
var toStringLeftSliceLength = 8;
var toStringRightSliceLength = -1;
/**
* ### typeOf (obj)
*
* Uses `Object.prototype.toString` to determine the type of an object,
* normalising behaviour across engine versions & well optimised.
*
* @param {Mixed} object
* @return {String} object type
* @api public
*/
function typeDetect(obj) {
/* ! Speed optimisation
* Pre:
* string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled)
* boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled)
* number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled)
* undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled)
* function x 2,556,769 ops/sec ±1.73% (77 runs sampled)
* Post:
* string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled)
* boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled)
* number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled)
* undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled)
* function x 31,296,870 ops/sec ±0.96% (83 runs sampled)
*/
var typeofObj = typeof obj;
if (typeofObj !== 'object') {
return typeofObj;
}
/* ! Speed optimisation
* Pre:
* null x 28,645,765 ops/sec ±1.17% (82 runs sampled)
* Post:
* null x 36,428,962 ops/sec ±1.37% (84 runs sampled)
*/
if (obj === null) {
return 'null';
}
/* ! Spec Conformance
* Test: `Object.prototype.toString.call(window)``
* - Node === "[object global]"
* - Chrome === "[object global]"
* - Firefox === "[object Window]"
* - PhantomJS === "[object Window]"
* - Safari === "[object Window]"
* - IE 11 === "[object Window]"
* - IE Edge === "[object Window]"
* Test: `Object.prototype.toString.call(this)``
* - Chrome Worker === "[object global]"
* - Firefox Worker === "[object DedicatedWorkerGlobalScope]"
* - Safari Worker === "[object DedicatedWorkerGlobalScope]"
* - IE 11 Worker === "[object WorkerGlobalScope]"
* - IE Edge Worker === "[object WorkerGlobalScope]"
*/
if (obj === globalObject) {
return 'global';
}
/* ! Speed optimisation
* Pre:
* array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled)
* Post:
* array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled)
*/
if (
Array.isArray(obj) &&
(symbolToStringTagExists === false || !(Symbol.toStringTag in obj))
) {
return 'Array';
}
// Not caching existence of `window` and related properties due to potential
// for `window` to be unset before tests in quasi-browser environments.
if (typeof window === 'object' && window !== null) {
/* ! Spec Conformance
* (https://html.spec.whatwg.org/multipage/browsers.html#location)
* WhatWG HTML$7.7.3 - The `Location` interface
* Test: `Object.prototype.toString.call(window.location)``
* - IE <=11 === "[object Object]"
* - IE Edge <=13 === "[object Object]"
*/
if (typeof window.location === 'object' && obj === window.location) {
return 'Location';
}
/* ! Spec Conformance
* (https://html.spec.whatwg.org/#document)
* WhatWG HTML$3.1.1 - The `Document` object
* Note: Most browsers currently adher to the W3C DOM Level 2 spec
* (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268)
* which suggests that browsers should use HTMLTableCellElement for
* both TD and TH elements. WhatWG separates these.
* WhatWG HTML states:
* > For historical reasons, Window objects must also have a
* > writable, configurable, non-enumerable property named
* > HTMLDocument whose value is the Document interface object.
* Test: `Object.prototype.toString.call(document)``
* - Chrome === "[object HTMLDocument]"
* - Firefox === "[object HTMLDocument]"
* - Safari === "[object HTMLDocument]"
* - IE <=10 === "[object Document]"
* - IE 11 === "[object HTMLDocument]"
* - IE Edge <=13 === "[object HTMLDocument]"
*/
if (typeof window.document === 'object' && obj === window.document) {
return 'Document';
}
if (typeof window.navigator === 'object') {
/* ! Spec Conformance
* (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray)
* WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray
* Test: `Object.prototype.toString.call(navigator.mimeTypes)``
* - IE <=10 === "[object MSMimeTypesCollection]"
*/
if (typeof window.navigator.mimeTypes === 'object' &&
obj === window.navigator.mimeTypes) {
return 'MimeTypeArray';
}
/* ! Spec Conformance
* (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
* WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray
* Test: `Object.prototype.toString.call(navigator.plugins)``
* - IE <=10 === "[object MSPluginsCollection]"
*/
if (typeof window.navigator.plugins === 'object' &&
obj === window.navigator.plugins) {
return 'PluginArray';
}
}
if ((typeof window.HTMLElement === 'function' ||
typeof window.HTMLElement === 'object') &&
obj instanceof window.HTMLElement) {
/* ! Spec Conformance
* (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray)
* WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement`
* Test: `Object.prototype.toString.call(document.createElement('blockquote'))``
* - IE <=10 === "[object HTMLBlockElement]"
*/
if (obj.tagName === 'BLOCKQUOTE') {
return 'HTMLQuoteElement';
}
/* ! Spec Conformance
* (https://html.spec.whatwg.org/#htmltabledatacellelement)
* WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement`
* Note: Most browsers currently adher to the W3C DOM Level 2 spec
* (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
* which suggests that browsers should use HTMLTableCellElement for
* both TD and TH elements. WhatWG separates these.
* Test: Object.prototype.toString.call(document.createElement('td'))
* - Chrome === "[object HTMLTableCellElement]"
* - Firefox === "[object HTMLTableCellElement]"
* - Safari === "[object HTMLTableCellElement]"
*/
if (obj.tagName === 'TD') {
return 'HTMLTableDataCellElement';
}
/* ! Spec Conformance
* (https://html.spec.whatwg.org/#htmltableheadercellelement)
* WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement`
* Note: Most browsers currently adher to the W3C DOM Level 2 spec
* (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075)
* which suggests that browsers should use HTMLTableCellElement for
* both TD and TH elements. WhatWG separates these.
* Test: Object.prototype.toString.call(document.createElement('th'))
* - Chrome === "[object HTMLTableCellElement]"
* - Firefox === "[object HTMLTableCellElement]"
* - Safari === "[object HTMLTableCellElement]"
*/
if (obj.tagName === 'TH') {
return 'HTMLTableHeaderCellElement';
}
}
}
/* ! Speed optimisation
* Pre:
* Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled)
* Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled)
* Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled)
* Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled)
* Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled)
* Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled)
* Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled)
* Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled)
* Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled)
* Post:
* Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled)
* Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled)
* Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled)
* Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled)
* Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled)
* Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled)
* Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled)
* Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled)
* Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled)
*/
var stringTag = (symbolToStringTagExists && obj[Symbol.toStringTag]);
if (typeof stringTag === 'string') {
return stringTag;
}
var objPrototype = Object.getPrototypeOf(obj);
/* ! Speed optimisation
* Pre:
* regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled)
* regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled)
* Post:
* regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled)
* regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled)
*/
if (objPrototype === RegExp.prototype) {
return 'RegExp';
}
/* ! Speed optimisation
* Pre:
* date x 2,130,074 ops/sec ±4.42% (68 runs sampled)
* Post:
* date x 3,953,779 ops/sec ±1.35% (77 runs sampled)
*/
if (objPrototype === Date.prototype) {
return 'Date';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag)
* ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise":
* Test: `Object.prototype.toString.call(Promise.resolve())``
* - Chrome <=47 === "[object Object]"
* - Edge <=20 === "[object Object]"
* - Firefox 29-Latest === "[object Promise]"
* - Safari 7.1-Latest === "[object Promise]"
*/
if (promiseExists && objPrototype === Promise.prototype) {
return 'Promise';
}
/* ! Speed optimisation
* Pre:
* set x 2,222,186 ops/sec ±1.31% (82 runs sampled)
* Post:
* set x 4,545,879 ops/sec ±1.13% (83 runs sampled)
*/
if (setExists && objPrototype === Set.prototype) {
return 'Set';
}
/* ! Speed optimisation
* Pre:
* map x 2,396,842 ops/sec ±1.59% (81 runs sampled)
* Post:
* map x 4,183,945 ops/sec ±6.59% (82 runs sampled)
*/
if (mapExists && objPrototype === Map.prototype) {
return 'Map';
}
/* ! Speed optimisation
* Pre:
* weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled)
* Post:
* weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled)
*/
if (weakSetExists && objPrototype === WeakSet.prototype) {
return 'WeakSet';
}
/* ! Speed optimisation
* Pre:
* weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled)
* Post:
* weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled)
*/
if (weakMapExists && objPrototype === WeakMap.prototype) {
return 'WeakMap';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag)
* ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView":
* Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))``
* - Edge <=13 === "[object Object]"
*/
if (dataViewExists && objPrototype === DataView.prototype) {
return 'DataView';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag)
* ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator":
* Test: `Object.prototype.toString.call(new Map().entries())``
* - Edge <=13 === "[object Object]"
*/
if (mapExists && objPrototype === mapIteratorPrototype) {
return 'Map Iterator';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag)
* ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator":
* Test: `Object.prototype.toString.call(new Set().entries())``
* - Edge <=13 === "[object Object]"
*/
if (setExists && objPrototype === setIteratorPrototype) {
return 'Set Iterator';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag)
* ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator":
* Test: `Object.prototype.toString.call([][Symbol.iterator]())``
* - Edge <=13 === "[object Object]"
*/
if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) {
return 'Array Iterator';
}
/* ! Spec Conformance
* (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag)
* ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator":
* Test: `Object.prototype.toString.call(''[Symbol.iterator]())``
* - Edge <=13 === "[object Object]"
*/
if (stringIteratorExists && objPrototype === stringIteratorPrototype) {
return 'String Iterator';
}
/* ! Speed optimisation
* Pre:
* object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled)
* Post:
* object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled)
*/
if (objPrototype === null) {
return 'Object';
}
return Object
.prototype
.toString
.call(obj)
.slice(toStringLeftSliceLength, toStringRightSliceLength);
}
return typeDetect;
})));
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],9:[function(require,module,exports){
/*!
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.6
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (typeof module === 'object' && module.exports) {
// Node
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals (root is window)
root.IPv6 = factory(root);
}
}(this, function (root) {
'use strict';
/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
var _out = IPv6.best(_in);
var _expected = "fe80::204:61ff:fe9d:f156";
console.log(_in, _out, _expected, _out === _expected);
*/
// save current IPv6 variable, if any
var _IPv6 = root && root.IPv6;
function bestPresentation(address) {
// based on:
// Javascript to test an IPv6 address for proper format, and to
// present the "best text representation" according to IETF Draft RFC at
// http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
// 8 Feb 2010 Rich Brown, Dartware, LLC
// Please feel free to use this code as long as you provide a link to
// http://www.intermapper.com
// http://intermapper.com/support/tools/IPV6-Validator.aspx
// http://download.dartware.com/thirdparty/ipv6validator.js
var _address = address.toLowerCase();
var segments = _address.split(':');
var length = segments.length;
var total = 8;
// trim colons (:: or ::a:b:c… or …a:b:c::)
if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
// must have been ::
// remove first two items
segments.shift();
segments.shift();
} else if (segments[0] === '' && segments[1] === '') {
// must have been ::xxxx
// remove the first item
segments.shift();
} else if (segments[length - 1] === '' && segments[length - 2] === '') {
// must have been xxxx::
segments.pop();
}
length = segments.length;
// adjust total segments for IPv4 trailer
if (segments[length - 1].indexOf('.') !== -1) {
// found a "." which means IPv4
total = 7;
}
// fill empty segments them with "0000"
var pos;
for (pos = 0; pos < length; pos++) {
if (segments[pos] === '') {
break;
}
}
if (pos < total) {
segments.splice(pos, 1, '0000');
while (segments.length < total) {
segments.splice(pos, 0, '0000');
}
}
// strip leading zeros
var _segments;
for (var i = 0; i < total; i++) {
_segments = segments[i].split('');
for (var j = 0; j < 3 ; j++) {
if (_segments[0] === '0' && _segments.length > 1) {
_segments.splice(0,1);
} else {
break;
}
}
segments[i] = _segments.join('');
}
// find longest sequence of zeroes and coalesce them into one segment
var best = -1;
var _best = 0;
var _current = 0;
var current = -1;
var inzeroes = false;
// i; already declared
for (i = 0; i < total; i++) {
if (inzeroes) {
if (segments[i] === '0') {
_current += 1;
} else {
inzeroes = false;
if (_current > _best) {
best = current;
_best = _current;
}
}
} else {
if (segments[i] === '0') {
inzeroes = true;
current = i;
_current = 1;
}
}
}
if (_current > _best) {
best = current;
_best = _current;
}
if (_best > 1) {
segments.splice(best, _best, '');
}
length = segments.length;
// assemble remaining segments
var result = '';
if (segments[0] === '') {
result = ':';
}
for (i = 0; i < length; i++) {
result += segments[i];
if (i === length - 1) {
break;
}
result += ':';
}
if (segments[length - 1] === '') {
result += ':';
}
return result;
}
function noConflict() {
/*jshint validthis: true */
if (root.IPv6 === this) {
root.IPv6 = _IPv6;
}
return this;
}
return {
best: bestPresentation,
noConflict: noConflict
};
}));
},{}],10:[function(require,module,exports){
/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.6
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (typeof module === 'object' && module.exports) {
// Node
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals (root is window)
root.SecondLevelDomains = factory(root);
}
}(this, function (root) {
'use strict';
// save current SecondLevelDomains variable, if any
var _SecondLevelDomains = root && root.SecondLevelDomains;
var SLD = {
// list of known Second Level Domains
// converted list of SLDs from https://github.com/gavingmiller/second-level-domains
// ----
// publicsuffix.org is more current and actually used by a couple of browsers internally.
// downside is it also contains domains like "dyndns.org" - which is fine for the security
// issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
// ----
list: {
'ac':' com gov mil net org ',
'ae':' ac co gov mil name net org pro sch ',
'af':' com edu gov net org ',
'al':' com edu gov mil net org ',
'ao':' co ed gv it og pb ',
'ar':' com edu gob gov int mil net org tur ',
'at':' ac co gv or ',
'au':' asn com csiro edu gov id net org ',
'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
'bb':' biz co com edu gov info net org store tv ',
'bh':' biz cc com edu gov info net org ',
'bn':' com edu gov net org ',
'bo':' com edu gob gov int mil net org tv ',
'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
'bs':' com edu gov net org ',
'bz':' du et om ov rg ',
'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
'ck':' biz co edu gen gov info net org ',
'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
'co':' com edu gov mil net nom org ',
'cr':' ac c co ed fi go or sa ',
'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
'do':' art com edu gob gov mil net org sld web ',
'dz':' art asso com edu gov net org pol ',
'ec':' com edu fin gov info med mil net org pro ',
'eg':' com edu eun gov mil name net org sci ',
'er':' com edu gov ind mil net org rochest w ',
'es':' com edu gob nom org ',
'et':' biz com edu gov info name net org ',
'fj':' ac biz com info mil name net org pro ',
'fk':' ac co gov net nom org ',
'fr':' asso com f gouv nom prd presse tm ',
'gg':' co net org ',
'gh':' com edu gov mil org ',
'gn':' ac com gov net org ',
'gr':' com edu gov mil net org ',
'gt':' com edu gob ind mil net org ',
'gu':' com edu gov net org ',
'hk':' com edu gov idv net org ',
'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
'id':' ac co go mil net or sch web ',
'il':' ac co gov idf k12 muni net org ',
'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
'iq':' com edu gov i mil net org ',
'ir':' ac co dnssec gov i id net org sch ',
'it':' edu gov ',
'je':' co net org ',
'jo':' com edu gov mil name net org sch ',
'jp':' ac ad co ed go gr lg ne or ',
'ke':' ac co go info me mobi ne or sc ',
'kh':' com edu gov mil net org per ',
'ki':' biz com de edu gov info mob net org tel ',
'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
'kn':' edu gov net org ',
'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
'kw':' com edu gov net org ',
'ky':' com edu gov net org ',
'kz':' com edu gov mil net org ',
'lb':' com edu gov net org ',
'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
'lr':' com edu gov net org ',
'lv':' asn com conf edu gov id mil net org ',
'ly':' com edu gov id med net org plc sch ',
'ma':' ac co gov m net org press ',
'mc':' asso tm ',
'me':' ac co edu gov its net org priv ',
'mg':' com edu gov mil nom org prd tm ',
'mk':' com edu gov inf name net org pro ',
'ml':' com edu gov net org presse ',
'mn':' edu gov org ',
'mo':' com edu gov net org ',
'mt':' com edu gov net org ',
'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
'mw':' ac co com coop edu gov int museum net org ',
'mx':' com edu gob net org ',
'my':' com edu gov mil name net org sch ',
'nf':' arts com firm info net other per rec store web ',
'ng':' biz com edu gov mil mobi name net org sch ',
'ni':' ac co com edu gob mil net nom org ',
'np':' com edu gov mil net org ',
'nr':' biz com edu gov info net org ',
'om':' ac biz co com edu gov med mil museum net org pro sch ',
'pe':' com edu gob mil net nom org sld ',
'ph':' com edu gov i mil net ngo org ',
'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
'pr':' ac biz com edu est gov info isla name net org pro prof ',
'ps':' com edu gov net org plo sec ',
'pw':' belau co ed go ne or ',
'ro':' arts com firm info nom nt org rec store tm www ',
'rs':' ac co edu gov in org ',
'sb':' com edu gov net org ',
'sc':' com edu gov net org ',
'sh':' co com edu gov net nom org ',
'sl':' com edu gov net org ',
'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
'sv':' com edu gob org red ',
'sz':' ac co org ',
'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
'tw':' club com ebiz edu game gov idv mil net org ',
'mu':' ac co com gov net or org ',
'mz':' ac co edu gov org ',
'na':' co com ',
'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
'pa':' abo ac com edu gob ing med net nom org sld ',
'pt':' com edu gov int net nome org publ ',
'py':' com edu gov mil net org ',
'qa':' com edu gov mil net org ',
're':' asso com nom ',
'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
'rw':' ac co com edu gouv gov int mil net ',
'sa':' com edu gov med net org pub sch ',
'sd':' com edu gov info med net org tv ',
'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
'sg':' com edu gov idn net org per ',
'sn':' art com edu gouv org perso univ ',
'sy':' com edu gov mil net news org ',
'th':' ac co go in mi net or ',
'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
'tz':' ac co go ne or ',
'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
'ug':' ac co go ne or org sc ',
'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
'us':' dni fed isa kids nsn ',
'uy':' com edu gub mil net org ',
've':' co com edu gob info mil net org web ',
'vi':' co com k12 net org ',
'vn':' ac biz com edu gov health info int name net org pro ',
'ye':' co com gov ltd me net org plc ',
'yu':' ac co edu gov org ',
'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
'zm':' ac co com edu gov net org sch ',
// https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
'net': 'gb jp se uk ',
'org': 'ae',
'de': 'com '
},
// gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
// in both performance and memory footprint. No initialization required.
// http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
// Following methods use lastIndexOf() rather than array.split() in order
// to avoid any memory allocations.
has: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
},
is: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset >= 0) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
},
get: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return null;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return null;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return null;
}
if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
return null;
}
return domain.slice(sldOffset+1);
},
noConflict: function(){
if (root.SecondLevelDomains === this) {
root.SecondLevelDomains = _SecondLevelDomains;
}
return this;
}
};
return SLD;
}));
},{}],11:[function(require,module,exports){
/*!
* URI.js - Mutating URLs
*
* Version: 1.19.6
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if (typeof module === 'object' && module.exports) {
// Node
module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['./punycode', './IPv6', './SecondLevelDomains'], factory);
} else {
// Browser globals (root is window)
root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);
}
}(this, function (punycode, IPv6, SLD, root) {
'use strict';
/*global location, escape, unescape */
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URI variable, if any
var _URI = root && root.URI;
function URI(url, base) {
var _urlSupplied = arguments.length >= 1;
var _baseSupplied = arguments.length >= 2;
// Allow instantiation without the 'new' keyword
if (!(this instanceof URI)) {
if (_urlSupplied) {
if (_baseSupplied) {
return new URI(url, base);
}
return new URI(url);
}
return new URI();
}
if (url === undefined) {
if (_urlSupplied) {
throw new TypeError('undefined is not a valid argument for URI');
}
if (typeof location !== 'undefined') {
url = location.href + '';
} else {
url = '';
}
}
if (url === null) {
if (_urlSupplied) {
throw new TypeError('null is not a valid argument for URI');
}
}
this.href(url);
// resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
if (base !== undefined) {
return this.absoluteTo(base);
}
return this;
}
function isInteger(value) {
return /^[0-9]+$/.test(value);
}
URI.version = '1.19.6';
var p = URI.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
function escapeRegEx(string) {
// https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function getType(value) {
// IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
if (value === undefined) {
return 'Undefined';
}
return String(Object.prototype.toString.call(value)).slice(8, -1);
}
function isArray(obj) {
return getType(obj) === 'Array';
}
function filterArrayValues(data, value) {
var lookup = {};
var i, length;
if (getType(value) === 'RegExp') {
lookup = null;
} else if (isArray(value)) {
for (i = 0, length = value.length; i < length; i++) {
lookup[value[i]] = true;
}
} else {
lookup[value] = true;
}
for (i = 0, length = data.length; i < length; i++) {
/*jshint laxbreak: true */
var _match = lookup && lookup[data[i]] !== undefined
|| !lookup && value.test(data[i]);
/*jshint laxbreak: false */
if (_match) {
data.splice(i, 1);
length--;
i--;
}
}
return data;
}
function arrayContains(list, value) {
var i, length;
// value may be string, number, array, regexp
if (isArray(value)) {
// Note: this can be optimized to O(n) (instead of current O(m * n))
for (i = 0, length = value.length; i < length; i++) {
if (!arrayContains(list, value[i])) {
return false;
}
}
return true;
}
var _type = getType(value);
for (i = 0, length = list.length; i < length; i++) {
if (_type === 'RegExp') {
if (typeof list[i] === 'string' && list[i].match(value)) {
return true;
}
} else if (list[i] === value) {
return true;
}
}
return false;
}
function arraysEqual(one, two) {
if (!isArray(one) || !isArray(two)) {
return false;
}
// arrays can't be equal if they have different amount of content
if (one.length !== two.length) {
return false;
}
one.sort();
two.sort();
for (var i = 0, l = one.length; i < l; i++) {
if (one[i] !== two[i]) {
return false;
}
}
return true;
}
function trimSlashes(text) {
var trim_expression = /^\/+|\/+$/g;
return text.replace(trim_expression, '');
}
URI._parts = function() {
return {
protocol: null,
username: null,
password: null,
hostname: null,
urn: null,
port: null,
path: null,
query: null,
fragment: null,
// state
preventInvalidHostname: URI.preventInvalidHostname,
duplicateQueryParameters: URI.duplicateQueryParameters,
escapeQuerySpace: URI.escapeQuerySpace
};
};
// state: throw on invalid hostname
// see https://github.com/medialize/URI.js/pull/345
// and https://github.com/medialize/URI.js/issues/354
URI.preventInvalidHostname = false;
// state: allow duplicate query parameters (a=1&a=1)
URI.duplicateQueryParameters = false;
// state: replaces + with %20 (space in query strings)
URI.escapeQuerySpace = true;
// static properties
URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
URI.idn_expression = /[^a-z0-9\._-]/i;
URI.punycode_expression = /(xn--)/i;
// well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
// credits to Rich Brown
// source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
// specification: http://www.ietf.org/rfc/rfc4291.txt
URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/;
// expression used is "gruber revised" (@gruber v2) determined to be the
// best solution in a regex-golf we did a couple of ages ago at
// * http://mathiasbynens.be/demo/url-regex
// * http://rodneyrehm.de/t/url-regex.html
URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
URI.findUri = {
// valid "scheme://" or "www."
start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
// everything up to the next whitespace
end: /[\s\r\n]|$/,
// trim trailing punctuation captured by end RegExp
trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
// balanced parens inclusion (), [], {}, <>
parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
};
// http://www.iana.org/assignments/uri-schemes.html
// http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
URI.defaultPorts = {
http: '80',
https: '443',
ftp: '21',
gopher: '70',
ws: '80',
wss: '443'
};
// list of protocols which always require a hostname
URI.hostProtocols = [
'http',
'https'
];
// allowed hostname characters according to RFC 3986
// ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
// I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
// map DOM Elements to their URI attribute
URI.domAttributes = {
'a': 'href',
'blockquote': 'cite',
'link': 'href',
'base': 'href',
'script': 'src',
'form': 'action',
'img': 'src',
'area': 'href',
'iframe': 'src',
'embed': 'src',
'source': 'src',
'track': 'src',
'input': 'src', // but only if type="image"
'audio': 'src',
'video': 'src'
};
URI.getDomAttribute = function(node) {
if (!node || !node.nodeName) {
return undefined;
}
var nodeName = node.nodeName.toLowerCase();
// <input> should only expose src for type="image"
if (nodeName === 'input' && node.type !== 'image') {
return undefined;
}
return URI.domAttributes[nodeName];
};
function escapeForDumbFirefox36(value) {
// https://github.com/medialize/URI.js/issues/91
return escape(value);
}
// encoding / decoding according to RFC3986
function strictEncodeURIComponent(string) {
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(string)
.replace(/[!'()*]/g, escapeForDumbFirefox36)
.replace(/\*/g, '%2A');
}
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
URI.iso8859 = function() {
URI.encode = escape;
URI.decode = unescape;
};
URI.unicode = function() {
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
};
URI.characters = {
pathname: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
map: {
// -._~!'()*
'%24': '$',
'%26': '&',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%3A': ':',
'%40': '@'
}
},
decode: {
expression: /[\/\?#]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23'
}
}
},
reserved: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
map: {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
}
}
},
urnpath: {
// The characters under `encode` are the characters called out by RFC 2141 as being acceptable
// for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
// these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
// note that the colon character is not featured in the encoding map; this is because URI.js
// gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
// should not appear unencoded in a segment itself.
// See also the note above about RFC3986 and capitalalized hex digits.
encode: {
expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
map: {
'%21': '!',
'%24': '$',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%40': '@'
}
},
// These characters are the characters called out by RFC2141 as "reserved" characters that
// should never appear in a URN, plus the colon character (see note above).
decode: {
expression: /[\/\?#:]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23',
':': '%3A'
}
}
}
};
URI.encodeQuery = function(string, escapeQuerySpace) {
var escaped = URI.encode(string + '');
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
};
URI.decodeQuery = function(string, escapeQuerySpace) {
string += '';
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
try {
return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch(e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
// generate encode/decode path functions
var _parts = {'encode':'encode', 'decode':'decode'};
var _part;
var generateAccessor = function(_group, _part) {
return function(string) {
try {
return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
return URI.characters[_group][_part].map[c];
});
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
};
for (_part in _parts) {
URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
}
var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
return function(string) {
// Why pass in names of functions, rather than the function objects themselves? The
// definitions of some functions (but in particular, URI.decode) will occasionally change due
// to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
// that the functions we use here are "fresh".
var actualCodingFunc;
if (!_innerCodingFuncName) {
actualCodingFunc = URI[_codingFuncName];
} else {
actualCodingFunc = function(string) {
return URI[_codingFuncName](URI[_innerCodingFuncName](string));
};
}
var segments = (string + '').split(_sep);
for (var i = 0, length = segments.length; i < length; i++) {
segments[i] = actualCodingFunc(segments[i]);
}
return segments.join(_sep);
};
};
// This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function(string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
} else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function(string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':');
var firstSlash = string.indexOf('/');
var nextColon = string.indexOf(':', firstColon + 1);
if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
// IPv6 host contains multiple colons - but no port
// this notation is actually not allowed by RFC 3986, but we're a liberal parser
parts.hostname = string.substring(0, pos) || null;
parts.port = null;
} else {
t = string.substring(0, pos).split(':');
parts.hostname = t[0] || null;
parts.port = t[1] || null;
}
}
if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
pos++;
string = '/' + string;
}
if (parts.preventInvalidHostname) {
URI.ensureValidHostname(parts.hostname, parts.protocol);
}
if (parts.port) {
URI.ensureValidPort(parts.port);
}
return string.substring(pos) || '/';
};
URI.parseAuthority = function(string, parts) {
string = URI.parseUserinfo(string, parts);
return URI.parseHost(string, parts);
};
URI.parseUserinfo = function(string, parts) {
// extract username:password
var _string = string
var firstBackSlash = string.indexOf('\\');
if (firstBackSlash !== -1) {
string = string.replace(/\\/g, '/')
}
var firstSlash = string.indexOf('/');
var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
var t;
// authority@ must come before /path or \path
if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
t = string.substring(0, pos).split(':');
parts.username = t[0] ? URI.decode(t[0]) : null;
t.shift();
parts.password = t[0] ? URI.decode(t.join(':')) : null;
string = _string.substring(pos + 1);
} else {
parts.username = null;
parts.password = null;
}
return string;
};
URI.parseQuery = function(string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (hasOwn.call(items, name)) {
if (typeof items[name] === 'string' || items[name] === null) {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
};
URI.build = function(parts) {
var t = '';
var requireAbsolutePath = false
if (parts.protocol) {
t += parts.protocol + ':';
}
if (!parts.urn && (t || parts.hostname)) {
t += '//';
requireAbsolutePath = true
}
t += (URI.buildAuthority(parts) || '');
if (typeof parts.path === 'string') {
if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
t += '/';
}
t += parts.path;
}
if (typeof parts.query === 'string' && parts.query) {
t += '?' + parts.query;
}
if (typeof parts.fragment === 'string' && parts.fragment) {
t += '#' + parts.fragment;
}
return t;
};
URI.buildHost = function(parts) {
var t = '';
if (!parts.hostname) {
return '';
} else if (URI.ip6_expression.test(parts.hostname)) {
t += '[' + parts.hostname + ']';
} else {
t += parts.hostname;
}
if (parts.port) {
t += ':' + parts.port;
}
return t;
};
URI.buildAuthority = function(parts) {
return URI.buildUserinfo(parts) + URI.buildHost(parts);
};
URI.buildUserinfo = function(parts) {
var t = '';
if (parts.username) {
t += URI.encode(parts.username);
}
if (parts.password) {
t += ':' + URI.encode(parts.password);
}
if (t) {
t += '@';
}
return t;
};
URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
// according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
// being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
// the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
// URI.js treats the query string as being application/x-www-form-urlencoded
// see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
var t = '';
var unique, key, i, length;
for (key in data) {
if (hasOwn.call(data, key)) {
if (isArray(data[key])) {
unique = {};
for (i = 0, length = data[key].length; i < length; i++) {
if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
if (duplicateQueryParameters !== true) {
unique[data[key][i] + ''] = true;
}
}
}
} else if (data[key] !== undefined) {
t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
}
}
}
return t.substring(1);
};
URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
// http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
// don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
};
URI.addQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.addQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (data[name] === undefined) {
data[name] = value;
return;
} else if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
if (!isArray(value)) {
value = [value];
}
data[name] = (data[name] || []).concat(value);
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
};
URI.setQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.setQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
data[name] = value === undefined ? null : value;
} else {
throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
}
};
URI.removeQuery = function(data, name, value) {
var i, length, key;
if (isArray(name)) {
for (i = 0, length = name.length; i < length; i++) {
data[name[i]] = undefined;
}
} else if (getType(name) === 'RegExp') {
for (key in data) {
if (name.test(key)) {
data[key] = undefined;
}
}
} else if (typeof name === 'object') {
for (key in name) {
if (hasOwn.call(name, key)) {
URI.removeQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (value !== undefined) {
if (getType(value) === 'RegExp') {
if (!isArray(data[name]) && value.test(data[name])) {
data[name] = undefined;
} else {
data[name] = filterArrayValues(data[name], value);
}
} else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
data[name] = undefined;
} else if (isArray(data[name])) {
data[name] = filterArrayValues(data[name], value);
}
} else {
data[name] = undefined;
}
} else {
throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
}
};
URI.hasQuery = function(data, name, value, withinArray) {
switch (getType(name)) {
case 'String':
// Nothing to do here
break;
case 'RegExp':
for (var key in data) {
if (hasOwn.call(data, key)) {
if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
return true;
}
}
}
return false;
case 'Object':
for (var _key in name) {
if (hasOwn.call(name, _key)) {
if (!URI.hasQuery(data, _key, name[_key])) {
return false;
}
}
}
return true;
default:
throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
}
switch (getType(value)) {
case 'Undefined':
// true if exists (but may be empty)
return name in data; // data[name] !== undefined;
case 'Boolean':
// true if exists and non-empty
var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
return value === _booly;
case 'Function':
// allow complex comparison
return !!value(data[name], name, data);
case 'Array':
if (!isArray(data[name])) {
return false;
}
var op = withinArray ? arrayContains : arraysEqual;
return op(data[name], value);
case 'RegExp':
if (!isArray(data[name])) {
return Boolean(data[name] && data[name].match(value));
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
case 'Number':
value = String(value);
/* falls through */
case 'String':
if (!isArray(data[name])) {
return data[name] === value;
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
default:
throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
}
};
URI.joinPaths = function() {
var input = [];
var segments = [];
var nonEmptySegments = 0;
for (var i = 0; i < arguments.length; i++) {
var url = new URI(arguments[i]);
input.push(url);
var _segments = url.segment();
for (var s = 0; s < _segments.length; s++) {
if (typeof _segments[s] === 'string') {
segments.push(_segments[s]);
}
if (_segments[s]) {
nonEmptySegments++;
}
}
}
if (!segments.length || !nonEmptySegments) {
return new URI('');
}
var uri = new URI('').segment(segments);
if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
uri.path('/' + uri.path());
}
return uri.normalize();
};
URI.commonPath = function(one, two) {
var length = Math.min(one.length, two.length);
var pos;
// find first non-matching character
for (pos = 0; pos < length; pos++) {
if (one.charAt(pos) !== two.charAt(pos)) {
pos--;
break;
}
}
if (pos < 1) {
return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
}
// revert to last /
if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
pos = one.substring(0, pos).lastIndexOf('/');
}
return one.substring(0, pos + 1);
};
URI.withinString = function(string, callback, options) {
options || (options = {});
var _start = options.start || URI.findUri.start;
var _end = options.end || URI.findUri.end;
var _trim = options.trim || URI.findUri.trim;
var _parens = options.parens || URI.findUri.parens;
var _attributeOpen = /[a-z0-9-]=["']?$/i;
_start.lastIndex = 0;
while (true) {
var match = _start.exec(string);
if (!match) {
break;
}
var start = match.index;
if (options.ignoreHtml) {
// attribut(e=["']?$)
var attributeOpen = string.slice(Math.max(start - 3, 0), start);
if (attributeOpen && _attributeOpen.test(attributeOpen)) {
continue;
}
}
var end = start + string.slice(start).search(_end);
var slice = string.slice(start, end);
// make sure we include well balanced parens
var parensEnd = -1;
while (true) {
var parensMatch = _parens.exec(slice);
if (!parensMatch) {
break;
}
var parensMatchEnd = parensMatch.index + parensMatch[0].length;
parensEnd = Math.max(parensEnd, parensMatchEnd);
}
if (parensEnd > -1) {
slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
} else {
slice = slice.replace(_trim, '');
}
if (slice.length <= match[0].length) {
// the extract only contains the starting marker of a URI,
// e.g. "www" or "http://"
continue;
}
if (options.ignore && options.ignore.test(slice)) {
continue;
}
end = start + slice.length;
var result = callback(slice, start, end, string);
if (result === undefined) {
_start.lastIndex = end;
continue;
}
result = String(result);
string = string.slice(0, start) + result + string.slice(end);
_start.lastIndex = start + result.length;
}
_start.lastIndex = 0;
return string;
};
URI.ensureValidHostname = function(v, protocol) {
// Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
// they are not part of DNS and therefore ignored by URI.js
var hasHostname = !!v; // not null and not an empty string
var hasProtocol = !!protocol;
var rejectEmptyHostname = false;
if (hasProtocol) {
rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
}
if (rejectEmptyHostname && !hasHostname) {
throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
} else if (v && v.match(URI.invalid_hostname_characters)) {
// test punycode
if (!punycode) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
}
if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
}
}
};
URI.ensureValidPort = function (v) {
if (!v) {
return;
}
var port = Number(v);
if (isInteger(port) && (port > 0) && (port < 65536)) {
return;
}
throw new TypeError('Port "' + v + '" is not a valid port');
};
// noConflict
URI.noConflict = function(removeAll) {
if (removeAll) {
var unconflicted = {
URI: this.noConflict()
};
if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
unconflicted.URITemplate = root.URITemplate.noConflict();
}
if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
unconflicted.IPv6 = root.IPv6.noConflict();
}
if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
}
return unconflicted;
} else if (root.URI === this) {
root.URI = _URI;
}
return this;
};
p.build = function(deferBuild) {
if (deferBuild === true) {
this._deferred_build = true;
} else if (deferBuild === undefined || this._deferred_build) {
this._string = URI.build(this._parts);
this._deferred_build = false;
}
return this;
};
p.clone = function() {
return new URI(this);
};
p.valueOf = p.toString = function() {
return this.build(false)._string;
};
function generateSimpleAccessor(_part){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
this._parts[_part] = v || null;
this.build(!build);
return this;
}
};
}
function generatePrefixAccessor(_part, _key){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
if (v !== null) {
v = v + '';
if (v.charAt(0) === _key) {
v = v.substring(1);
}
}
this._parts[_part] = v;
this.build(!build);
return this;
}
};
}
p.protocol = generateSimpleAccessor('protocol');
p.username = generateSimpleAccessor('username');
p.password = generateSimpleAccessor('password');
p.hostname = generateSimpleAccessor('hostname');
p.port = generateSimpleAccessor('port');
p.query = generatePrefixAccessor('query', '?');
p.fragment = generatePrefixAccessor('fragment', '#');
p.search = function(v, build) {
var t = this.query(v, build);
return typeof t === 'string' && t.length ? ('?' + t) : t;
};
p.hash = function(v, build) {
var t = this.fragment(v, build);
return typeof t === 'string' && t.length ? ('#' + t) : t;
};
p.pathname = function(v, build) {
if (v === undefined || v === true) {
var res = this._parts.path || (this._parts.hostname ? '/' : '');
return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
} else {
if (this._parts.urn) {
this._parts.path = v ? URI.recodeUrnPath(v) : '';
} else {
this._parts.path = v ? URI.recodePath(v) : '/';
}
this.build(!build);
return this;
}
};
p.path = p.pathname;
p.href = function(href, build) {
var key;
if (href === undefined) {
return this.toString();
}
this._string = '';
this._parts = URI._parts();
var _URI = href instanceof URI;
var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
if (href.nodeName) {
var attribute = URI.getDomAttribute(href);
href = href[attribute] || '';
_object = false;
}
// window.location is reported to be an object, but it's not the sort
// of object we're looking for:
// * location.protocol ends with a colon
// * location.query != object.search
// * location.hash != object.fragment
// simply serializing the unknown object should do the trick
// (for location, not for everything...)
if (!_URI && _object && href.pathname !== undefined) {
href = href.toString();
}
if (typeof href === 'string' || href instanceof String) {
this._parts = URI.parse(String(href), this._parts);
} else if (_URI || _object) {
var src = _URI ? href._parts : href;
for (key in src) {
if (key === 'query') { continue; }
if (hasOwn.call(this._parts, key)) {
this._parts[key] = src[key];
}
}
if (src.query) {
this.query(src.query, false);
}
} else {
throw new TypeError('invalid input');
}
this.build(!build);
return this;
};
// identification accessors
p.is = function(what) {
var ip = false;
var ip4 = false;
var ip6 = false;
var name = false;
var sld = false;
var idn = false;
var punycode = false;
var relative = !this._parts.urn;
if (this._parts.hostname) {
relative = false;
ip4 = URI.ip4_expression.test(this._parts.hostname);
ip6 = URI.ip6_expression.test(this._parts.hostname);
ip = ip4 || ip6;
name = !ip;
sld = name && SLD && SLD.has(this._parts.hostname);
idn = name && URI.idn_expression.test(this._parts.hostname);
punycode = name && URI.punycode_expression.test(this._parts.hostname);
}
switch (what.toLowerCase()) {
case 'relative':
return relative;
case 'absolute':
return !relative;
// hostname identification
case 'domain':
case 'name':
return name;
case 'sld':
return sld;
case 'ip':
return ip;
case 'ip4':
case 'ipv4':
case 'inet4':
return ip4;
case 'ip6':
case 'ipv6':
case 'inet6':
return ip6;
case 'idn':
return idn;
case 'url':
return !this._parts.urn;
case 'urn':
return !!this._parts.urn;
case 'punycode':
return punycode;
}
return null;
};
// component specific input validation
var _protocol = p.protocol;
var _port = p.port;
var _hostname = p.hostname;
p.protocol = function(v, build) {
if (v) {
// accept trailing ://
v = v.replace(/:(\/\/)?$/, '');
if (!v.match(URI.protocol_expression)) {
throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
}
}
return _protocol.call(this, v, build);
};
p.scheme = p.protocol;
p.port = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
if (v === 0) {
v = null;
}
if (v) {
v += '';
if (v.charAt(0) === ':') {
v = v.substring(1);
}
URI.ensureValidPort(v);
}
}
return _port.call(this, v, build);
};
p.hostname = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
var res = URI.parseHost(v, x);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
v = x.hostname;
if (this._parts.preventInvalidHostname) {
URI.ensureValidHostname(v, this._parts.protocol);
}
}
return _hostname.call(this, v, build);
};
// compound accessors
p.origin = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var protocol = this.protocol();
var authority = this.authority();
if (!authority) {
return '';
}
return (protocol ? protocol + '://' : '') + this.authority();
} else {
var origin = URI(v);
this
.protocol(origin.protocol())
.authority(origin.authority())
.build(!build);
return this;
}
};
p.host = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildHost(this._parts) : '';
} else {
var res = URI.parseHost(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.authority = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
} else {
var res = URI.parseAuthority(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.userinfo = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var t = URI.buildUserinfo(this._parts);
return t ? t.substring(0, t.length -1) : t;
} else {
if (v[v.length-1] !== '@') {
v += '@';
}
URI.parseUserinfo(v, this._parts);
this.build(!build);
return this;
}
};
p.resource = function(v, build) {
var parts;
if (v === undefined) {
return this.path() + this.search() + this.hash();
}
parts = URI.parse(v);
this._parts.path = parts.path;
this._parts.query = parts.query;
this._parts.fragment = parts.fragment;
this.build(!build);
return this;
};
// fraction accessors
p.subdomain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
// convenience, return "www" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// grab domain and add another segment
var end = this._parts.hostname.length - this.domain().length - 1;
return this._parts.hostname.substring(0, end) || '';
} else {
var e = this._parts.hostname.length - this.domain().length;
var sub = this._parts.hostname.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(sub));
if (v && v.charAt(v.length - 1) !== '.') {
v += '.';
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
if (v) {
URI.ensureValidHostname(v, this._parts.protocol);
}
this._parts.hostname = this._parts.hostname.replace(replace, v);
this.build(!build);
return this;
}
};
p.domain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// convenience, return "example.org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// if hostname consists of 1 or 2 segments, it must be the domain
var t = this._parts.hostname.match(/\./g);
if (t && t.length < 2) {
return this._parts.hostname;
}
// grab tld and add another segment
var end = this._parts.hostname.length - this.tld(build).length - 1;
end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
return this._parts.hostname.substring(end) || '';
} else {
if (!v) {
throw new TypeError('cannot set domain empty');
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
URI.ensureValidHostname(v, this._parts.protocol);
if (!this._parts.hostname || this.is('IP')) {
this._parts.hostname = v;
} else {
var replace = new RegExp(escapeRegEx(this.domain()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.tld = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// return "org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
var pos = this._parts.hostname.lastIndexOf('.');
var tld = this._parts.hostname.substring(pos + 1);
if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
return SLD.get(this._parts.hostname) || tld;
}
return tld;
} else {
var replace;
if (!v) {
throw new TypeError('cannot set TLD empty');
} else if (v.match(/[^a-zA-Z0-9-]/)) {
if (SLD && SLD.is(v)) {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
} else {
throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
}
} else if (!this._parts.hostname || this.is('IP')) {
throw new ReferenceError('cannot set TLD on non-domain host');
} else {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.directory = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path && !this._parts.hostname) {
return '';
}
if (this._parts.path === '/') {
return '/';
}
var end = this._parts.path.length - this.filename().length - 1;
var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
return v ? URI.decodePath(res) : res;
} else {
var e = this._parts.path.length - this.filename().length;
var directory = this._parts.path.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(directory));
// fully qualifier directories begin with a slash
if (!this.is('relative')) {
if (!v) {
v = '/';
}
if (v.charAt(0) !== '/') {
v = '/' + v;
}
}
// directories always end with a slash
if (v && v.charAt(v.length - 1) !== '/') {
v += '/';
}
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
this.build(!build);
return this;
}
};
p.filename = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v !== 'string') {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var pos = this._parts.path.lastIndexOf('/');
var res = this._parts.path.substring(pos+1);
return v ? URI.decodePathSegment(res) : res;
} else {
var mutatedDirectory = false;
if (v.charAt(0) === '/') {
v = v.substring(1);
}
if (v.match(/\.?\//)) {
mutatedDirectory = true;
}
var replace = new RegExp(escapeRegEx(this.filename()) + '$');
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
if (mutatedDirectory) {
this.normalizePath(build);
} else {
this.build(!build);
}
return this;
}
};
p.suffix = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var filename = this.filename();
var pos = filename.lastIndexOf('.');
var s, res;
if (pos === -1) {
return '';
}
// suffix may only contain alnum characters (yup, I made this up.)
s = filename.substring(pos+1);
res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
return v ? URI.decodePathSegment(res) : res;
} else {
if (v.charAt(0) === '.') {
v = v.substring(1);
}
var suffix = this.suffix();
var replace;
if (!suffix) {
if (!v) {
return this;
}
this._parts.path += '.' + URI.recodePath(v);
} else if (!v) {
replace = new RegExp(escapeRegEx('.' + suffix) + '$');
} else {
replace = new RegExp(escapeRegEx(suffix) + '$');
}
if (replace) {
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.segment = function(segment, v, build) {
var separator = this._parts.urn ? ':' : '/';
var path = this.path();
var absolute = path.substring(0, 1) === '/';
var segments = path.split(separator);
if (segment !== undefined && typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (segment !== undefined && typeof segment !== 'number') {
throw new Error('Bad segment "' + segment + '", must be 0-based integer');
}
if (absolute) {
segments.shift();
}
if (segment < 0) {
// allow negative indexes to address from the end
segment = Math.max(segments.length + segment, 0);
}
if (v === undefined) {
/*jshint laxbreak: true */
return segment === undefined
? segments
: segments[segment];
/*jshint laxbreak: false */
} else if (segment === null || segments[segment] === undefined) {
if (isArray(v)) {
segments = [];
// collapse empty elements within array
for (var i=0, l=v.length; i < l; i++) {
if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
continue;
}
if (segments.length && !segments[segments.length -1].length) {
segments.pop();
}
segments.push(trimSlashes(v[i]));
}
} else if (v || typeof v === 'string') {
v = trimSlashes(v);
if (segments[segments.length -1] === '') {
// empty trailing elements have to be overwritten
// to prevent results such as /foo//bar
segments[segments.length -1] = v;
} else {
segments.push(v);
}
}
} else {
if (v) {
segments[segment] = trimSlashes(v);
} else {
segments.splice(segment, 1);
}
}
if (absolute) {
segments.unshift('');
}
return this.path(segments.join(separator), build);
};
p.segmentCoded = function(segment, v, build) {
var segments, i, l;
if (typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (v === undefined) {
segments = this.segment(segment, v, build);
if (!isArray(segments)) {
segments = segments !== undefined ? URI.decode(segments) : undefined;
} else {
for (i = 0, l = segments.length; i < l; i++) {
segments[i] = URI.decode(segments[i]);
}
}
return segments;
}
if (!isArray(v)) {
v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
} else {
for (i = 0, l = v.length; i < l; i++) {
v[i] = URI.encode(v[i]);
}
}
return this.segment(segment, v, build);
};
// mutating query string
var q = p.query;
p.query = function(v, build) {
if (v === true) {
return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
} else if (typeof v === 'function') {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
var result = v.call(this, data);
this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else if (v !== undefined && typeof v !== 'string') {
this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else {
return q.call(this, v, build);
}
};
p.setQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
if (typeof name === 'string' || name instanceof String) {
data[name] = value !== undefined ? value : null;
} else if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
data[key] = name[key];
}
}
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.addQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.addQuery(data, name, value === undefined ? null : value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.removeQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.removeQuery(data, name, value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.hasQuery = function(name, value, withinArray) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
return URI.hasQuery(data, name, value, withinArray);
};
p.setSearch = p.setQuery;
p.addSearch = p.addQuery;
p.removeSearch = p.removeQuery;
p.hasSearch = p.hasQuery;
// sanitizing URLs
p.normalize = function() {
if (this._parts.urn) {
return this
.normalizeProtocol(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
}
return this
.normalizeProtocol(false)
.normalizeHostname(false)
.normalizePort(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
};
p.normalizeProtocol = function(build) {
if (typeof this._parts.protocol === 'string') {
this._parts.protocol = this._parts.protocol.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizeHostname = function(build) {
if (this._parts.hostname) {
if (this.is('IDN') && punycode) {
this._parts.hostname = punycode.toASCII(this._parts.hostname);
} else if (this.is('IPv6') && IPv6) {
this._parts.hostname = IPv6.best(this._parts.hostname);
}
this._parts.hostname = this._parts.hostname.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizePort = function(build) {
// remove port of it's the protocol's default
if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
this._parts.port = null;
this.build(!build);
}
return this;
};
p.normalizePath = function(build) {
var _path = this._parts.path;
if (!_path) {
return this;
}
if (this._parts.urn) {
this._parts.path = URI.recodeUrnPath(this._parts.path);
this.build(!build);
return this;
}
if (this._parts.path === '/') {
return this;
}
_path = URI.recodePath(_path);
var _was_relative;
var _leadingParents = '';
var _parent, _pos;
// handle relative paths
if (_path.charAt(0) !== '/') {
_was_relative = true;
_path = '/' + _path;
}
// handle relative files (as opposed to directories)
if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
_path += '/';
}
// resolve simples
_path = _path
.replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
.replace(/\/{2,}/g, '/');
// remember leading parents
if (_was_relative) {
_leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
if (_leadingParents) {
_leadingParents = _leadingParents[0];
}
}
// resolve parents
while (true) {
_parent = _path.search(/\/\.\.(\/|$)/);
if (_parent === -1) {
// no more ../ to resolve
break;
} else if (_parent === 0) {
// top level cannot be relative, skip it
_path = _path.substring(3);
continue;
}
_pos = _path.substring(0, _parent).lastIndexOf('/');
if (_pos === -1) {
_pos = _parent;
}
_path = _path.substring(0, _pos) + _path.substring(_parent + 3);
}
// revert to relative
if (_was_relative && this.is('relative')) {
_path = _leadingParents + _path.substring(1);
}
this._parts.path = _path;
this.build(!build);
return this;
};
p.normalizePathname = p.normalizePath;
p.normalizeQuery = function(build) {
if (typeof this._parts.query === 'string') {
if (!this._parts.query.length) {
this._parts.query = null;
} else {
this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
}
this.build(!build);
}
return this;
};
p.normalizeFragment = function(build) {
if (!this._parts.fragment) {
this._parts.fragment = null;
this.build(!build);
}
return this;
};
p.normalizeSearch = p.normalizeQuery;
p.normalizeHash = p.normalizeFragment;
p.iso8859 = function() {
// expect unicode input, iso8859 output
var e = URI.encode;
var d = URI.decode;
URI.encode = escape;
URI.decode = decodeURIComponent;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.unicode = function() {
// expect iso8859 input, unicode output
var e = URI.encode;
var d = URI.decode;
URI.encode = strictEncodeURIComponent;
URI.decode = unescape;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.readable = function() {
var uri = this.clone();
// removing username, password, because they shouldn't be displayed according to RFC 3986
uri.username('').password('').normalize();
var t = '';
if (uri._parts.protocol) {
t += uri._parts.protocol + '://';
}
if (uri._parts.hostname) {
if (uri.is('punycode') && punycode) {
t += punycode.toUnicode(uri._parts.hostname);
if (uri._parts.port) {
t += ':' + uri._parts.port;
}
} else {
t += uri.host();
}
}
if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
t += '/';
}
t += uri.path(true);
if (uri._parts.query) {
var q = '';
for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
var kv = (qp[i] || '').split('=');
q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
if (kv[1] !== undefined) {
q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
}
}
t += '?' + q.substring(1);
}
t += URI.decodeQuery(uri.hash(), true);
return t;
};
// resolving relative and absolute URLs
p.absoluteTo = function(base) {
var resolved = this.clone();
var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
var basedir, i, p;
if (this._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
if (!(base instanceof URI)) {
base = new URI(base);
}
if (resolved._parts.protocol) {
// Directly returns even if this._parts.hostname is empty.
return resolved;
} else {
resolved._parts.protocol = base._parts.protocol;
}
if (this._parts.hostname) {
return resolved;
}
for (i = 0; (p = properties[i]); i++) {
resolved._parts[p] = base._parts[p];
}
if (!resolved._parts.path) {
resolved._parts.path = base._parts.path;
if (!resolved._parts.query) {
resolved._parts.query = base._parts.query;
}
} else {
if (resolved._parts.path.substring(-2) === '..') {
resolved._parts.path += '/';
}
if (resolved.path().charAt(0) !== '/') {
basedir = base.directory();
basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
resolved.normalizePath();
}
}
resolved.build();
return resolved;
};
p.relativeTo = function(base) {
var relative = this.clone().normalize();
var relativeParts, baseParts, common, relativePath, basePath;
if (relative._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
base = new URI(base).normalize();
relativeParts = relative._parts;
baseParts = base._parts;
relativePath = relative.path();
basePath = base.path();
if (relativePath.charAt(0) !== '/') {
throw new Error('URI is already relative');
}
if (basePath.charAt(0) !== '/') {
throw new Error('Cannot calculate a URI relative to another relative URI');
}
if (relativeParts.protocol === baseParts.protocol) {
relativeParts.protocol = null;
}
if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
return relative.build();
}
if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
return relative.build();
}
if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
relativeParts.hostname = null;
relativeParts.port = null;
} else {
return relative.build();
}
if (relativePath === basePath) {
relativeParts.path = '';
return relative.build();
}
// determine common sub path
common = URI.commonPath(relativePath, basePath);
// If the paths have nothing in common, return a relative URL with the absolute path.
if (!common) {
return relative.build();
}
var parents = baseParts.path
.substring(common.length)
.replace(/[^\/]*$/, '')
.replace(/.*?\//g, '../');
relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
return relative.build();
};
// comparing URIs
p.equals = function(uri) {
var one = this.clone();
var two = new URI(uri);
var one_map = {};
var two_map = {};
var checked = {};
var one_query, two_query, key;
one.normalize();
two.normalize();
// exact match
if (one.toString() === two.toString()) {
return true;
}
// extract query string
one_query = one.query();
two_query = two.query();
one.query('');
two.query('');
// definitely not equal if not even non-query parts match
if (one.toString() !== two.toString()) {
return false;
}
// query parameters have the same length, even if they're permuted
if (one_query.length !== two_query.length) {
return false;
}
one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
for (key in one_map) {
if (hasOwn.call(one_map, key)) {
if (!isArray(one_map[key])) {
if (one_map[key] !== two_map[key]) {
return false;
}
} else if (!arraysEqual(one_map[key], two_map[key])) {
return false;
}
checked[key] = true;
}
}
for (key in two_map) {
if (hasOwn.call(two_map, key)) {
if (!checked[key]) {
// two contains a parameter not present in one
return false;
}
}
}
return true;
};
// state
p.preventInvalidHostname = function(v) {
this._parts.preventInvalidHostname = !!v;
return this;
};
p.duplicateQueryParameters = function(v) {
this._parts.duplicateQueryParameters = !!v;
return this;
};
p.escapeQuerySpace = function(v) {
this._parts.escapeQuerySpace = !!v;
return this;
};
return URI;
}));
},{"./IPv6":9,"./SecondLevelDomains":10,"./punycode":12}],12:[function(require,module,exports){
(function (global){(function (){
/*! https://mths.be/punycode v1.4.0 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],13:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toDate = require('./lib/toDate');
var _toDate2 = _interopRequireDefault(_toDate);
var _toFloat = require('./lib/toFloat');
var _toFloat2 = _interopRequireDefault(_toFloat);
var _toInt = require('./lib/toInt');
var _toInt2 = _interopRequireDefault(_toInt);
var _toBoolean = require('./lib/toBoolean');
var _toBoolean2 = _interopRequireDefault(_toBoolean);
var _equals = require('./lib/equals');
var _equals2 = _interopRequireDefault(_equals);
var _contains = require('./lib/contains');
var _contains2 = _interopRequireDefault(_contains);
var _matches = require('./lib/matches');
var _matches2 = _interopRequireDefault(_matches);
var _isEmail = require('./lib/isEmail');
var _isEmail2 = _interopRequireDefault(_isEmail);
var _isURL = require('./lib/isURL');
var _isURL2 = _interopRequireDefault(_isURL);
var _isMACAddress = require('./lib/isMACAddress');
var _isMACAddress2 = _interopRequireDefault(_isMACAddress);
var _isIP = require('./lib/isIP');
var _isIP2 = _interopRequireDefault(_isIP);
var _isFQDN = require('./lib/isFQDN');
var _isFQDN2 = _interopRequireDefault(_isFQDN);
var _isBoolean = require('./lib/isBoolean');
var _isBoolean2 = _interopRequireDefault(_isBoolean);
var _isAlpha = require('./lib/isAlpha');
var _isAlpha2 = _interopRequireDefault(_isAlpha);
var _isAlphanumeric = require('./lib/isAlphanumeric');
var _isAlphanumeric2 = _interopRequireDefault(_isAlphanumeric);
var _isNumeric = require('./lib/isNumeric');
var _isNumeric2 = _interopRequireDefault(_isNumeric);
var _isPort = require('./lib/isPort');
var _isPort2 = _interopRequireDefault(_isPort);
var _isLowercase = require('./lib/isLowercase');
var _isLowercase2 = _interopRequireDefault(_isLowercase);
var _isUppercase = require('./lib/isUppercase');
var _isUppercase2 = _interopRequireDefault(_isUppercase);
var _isAscii = require('./lib/isAscii');
var _isAscii2 = _interopRequireDefault(_isAscii);
var _isFullWidth = require('./lib/isFullWidth');
var _isFullWidth2 = _interopRequireDefault(_isFullWidth);
var _isHalfWidth = require('./lib/isHalfWidth');
var _isHalfWidth2 = _interopRequireDefault(_isHalfWidth);
var _isVariableWidth = require('./lib/isVariableWidth');
var _isVariableWidth2 = _interopRequireDefault(_isVariableWidth);
var _isMultibyte = require('./lib/isMultibyte');
var _isMultibyte2 = _interopRequireDefault(_isMultibyte);
var _isSurrogatePair = require('./lib/isSurrogatePair');
var _isSurrogatePair2 = _interopRequireDefault(_isSurrogatePair);
var _isInt = require('./lib/isInt');
var _isInt2 = _interopRequireDefault(_isInt);
var _isFloat = require('./lib/isFloat');
var _isFloat2 = _interopRequireDefault(_isFloat);
var _isDecimal = require('./lib/isDecimal');
var _isDecimal2 = _interopRequireDefault(_isDecimal);
var _isHexadecimal = require('./lib/isHexadecimal');
var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal);
var _isDivisibleBy = require('./lib/isDivisibleBy');
var _isDivisibleBy2 = _interopRequireDefault(_isDivisibleBy);
var _isHexColor = require('./lib/isHexColor');
var _isHexColor2 = _interopRequireDefault(_isHexColor);
var _isISRC = require('./lib/isISRC');
var _isISRC2 = _interopRequireDefault(_isISRC);
var _isMD = require('./lib/isMD5');
var _isMD2 = _interopRequireDefault(_isMD);
var _isHash = require('./lib/isHash');
var _isHash2 = _interopRequireDefault(_isHash);
var _isJSON = require('./lib/isJSON');
var _isJSON2 = _interopRequireDefault(_isJSON);
var _isEmpty = require('./lib/isEmpty');
var _isEmpty2 = _interopRequireDefault(_isEmpty);
var _isLength = require('./lib/isLength');
var _isLength2 = _interopRequireDefault(_isLength);
var _isByteLength = require('./lib/isByteLength');
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isUUID = require('./lib/isUUID');
var _isUUID2 = _interopRequireDefault(_isUUID);
var _isMongoId = require('./lib/isMongoId');
var _isMongoId2 = _interopRequireDefault(_isMongoId);
var _isAfter = require('./lib/isAfter');
var _isAfter2 = _interopRequireDefault(_isAfter);
var _isBefore = require('./lib/isBefore');
var _isBefore2 = _interopRequireDefault(_isBefore);
var _isIn = require('./lib/isIn');
var _isIn2 = _interopRequireDefault(_isIn);
var _isCreditCard = require('./lib/isCreditCard');
var _isCreditCard2 = _interopRequireDefault(_isCreditCard);
var _isISIN = require('./lib/isISIN');
var _isISIN2 = _interopRequireDefault(_isISIN);
var _isISBN = require('./lib/isISBN');
var _isISBN2 = _interopRequireDefault(_isISBN);
var _isISSN = require('./lib/isISSN');
var _isISSN2 = _interopRequireDefault(_isISSN);
var _isMobilePhone = require('./lib/isMobilePhone');
var _isMobilePhone2 = _interopRequireDefault(_isMobilePhone);
var _isCurrency = require('./lib/isCurrency');
var _isCurrency2 = _interopRequireDefault(_isCurrency);
var _isISO = require('./lib/isISO8601');
var _isISO2 = _interopRequireDefault(_isISO);
var _isISO31661Alpha = require('./lib/isISO31661Alpha2');
var _isISO31661Alpha2 = _interopRequireDefault(_isISO31661Alpha);
var _isBase = require('./lib/isBase64');
var _isBase2 = _interopRequireDefault(_isBase);
var _isDataURI = require('./lib/isDataURI');
var _isDataURI2 = _interopRequireDefault(_isDataURI);
var _isMimeType = require('./lib/isMimeType');
var _isMimeType2 = _interopRequireDefault(_isMimeType);
var _isLatLong = require('./lib/isLatLong');
var _isLatLong2 = _interopRequireDefault(_isLatLong);
var _isPostalCode = require('./lib/isPostalCode');
var _isPostalCode2 = _interopRequireDefault(_isPostalCode);
var _ltrim = require('./lib/ltrim');
var _ltrim2 = _interopRequireDefault(_ltrim);
var _rtrim = require('./lib/rtrim');
var _rtrim2 = _interopRequireDefault(_rtrim);
var _trim = require('./lib/trim');
var _trim2 = _interopRequireDefault(_trim);
var _escape = require('./lib/escape');
var _escape2 = _interopRequireDefault(_escape);
var _unescape = require('./lib/unescape');
var _unescape2 = _interopRequireDefault(_unescape);
var _stripLow = require('./lib/stripLow');
var _stripLow2 = _interopRequireDefault(_stripLow);
var _whitelist = require('./lib/whitelist');
var _whitelist2 = _interopRequireDefault(_whitelist);
var _blacklist = require('./lib/blacklist');
var _blacklist2 = _interopRequireDefault(_blacklist);
var _isWhitelisted = require('./lib/isWhitelisted');
var _isWhitelisted2 = _interopRequireDefault(_isWhitelisted);
var _normalizeEmail = require('./lib/normalizeEmail');
var _normalizeEmail2 = _interopRequireDefault(_normalizeEmail);
var _toString = require('./lib/util/toString');
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var version = '9.4.1';
var validator = {
version: version,
toDate: _toDate2.default,
toFloat: _toFloat2.default,
toInt: _toInt2.default,
toBoolean: _toBoolean2.default,
equals: _equals2.default,
contains: _contains2.default,
matches: _matches2.default,
isEmail: _isEmail2.default,
isURL: _isURL2.default,
isMACAddress: _isMACAddress2.default,
isIP: _isIP2.default,
isFQDN: _isFQDN2.default,
isBoolean: _isBoolean2.default,
isAlpha: _isAlpha2.default,
isAlphanumeric: _isAlphanumeric2.default,
isNumeric: _isNumeric2.default,
isPort: _isPort2.default,
isLowercase: _isLowercase2.default,
isUppercase: _isUppercase2.default,
isAscii: _isAscii2.default,
isFullWidth: _isFullWidth2.default,
isHalfWidth: _isHalfWidth2.default,
isVariableWidth: _isVariableWidth2.default,
isMultibyte: _isMultibyte2.default,
isSurrogatePair: _isSurrogatePair2.default,
isInt: _isInt2.default,
isFloat: _isFloat2.default,
isDecimal: _isDecimal2.default,
isHexadecimal: _isHexadecimal2.default,
isDivisibleBy: _isDivisibleBy2.default,
isHexColor: _isHexColor2.default,
isISRC: _isISRC2.default,
isMD5: _isMD2.default,
isHash: _isHash2.default,
isJSON: _isJSON2.default,
isEmpty: _isEmpty2.default,
isLength: _isLength2.default,
isByteLength: _isByteLength2.default,
isUUID: _isUUID2.default,
isMongoId: _isMongoId2.default,
isAfter: _isAfter2.default,
isBefore: _isBefore2.default,
isIn: _isIn2.default,
isCreditCard: _isCreditCard2.default,
isISIN: _isISIN2.default,
isISBN: _isISBN2.default,
isISSN: _isISSN2.default,
isMobilePhone: _isMobilePhone2.default,
isPostalCode: _isPostalCode2.default,
isCurrency: _isCurrency2.default,
isISO8601: _isISO2.default,
isISO31661Alpha2: _isISO31661Alpha2.default,
isBase64: _isBase2.default,
isDataURI: _isDataURI2.default,
isMimeType: _isMimeType2.default,
isLatLong: _isLatLong2.default,
ltrim: _ltrim2.default,
rtrim: _rtrim2.default,
trim: _trim2.default,
escape: _escape2.default,
unescape: _unescape2.default,
stripLow: _stripLow2.default,
whitelist: _whitelist2.default,
blacklist: _blacklist2.default,
isWhitelisted: _isWhitelisted2.default,
normalizeEmail: _normalizeEmail2.default,
toString: _toString2.default
};
exports.default = validator;
module.exports = exports['default'];
},{"./lib/blacklist":15,"./lib/contains":16,"./lib/equals":17,"./lib/escape":18,"./lib/isAfter":19,"./lib/isAlpha":20,"./lib/isAlphanumeric":21,"./lib/isAscii":22,"./lib/isBase64":23,"./lib/isBefore":24,"./lib/isBoolean":25,"./lib/isByteLength":26,"./lib/isCreditCard":27,"./lib/isCurrency":28,"./lib/isDataURI":29,"./lib/isDecimal":30,"./lib/isDivisibleBy":31,"./lib/isEmail":32,"./lib/isEmpty":33,"./lib/isFQDN":34,"./lib/isFloat":35,"./lib/isFullWidth":36,"./lib/isHalfWidth":37,"./lib/isHash":38,"./lib/isHexColor":39,"./lib/isHexadecimal":40,"./lib/isIP":41,"./lib/isISBN":42,"./lib/isISIN":43,"./lib/isISO31661Alpha2":44,"./lib/isISO8601":45,"./lib/isISRC":46,"./lib/isISSN":47,"./lib/isIn":48,"./lib/isInt":49,"./lib/isJSON":50,"./lib/isLatLong":51,"./lib/isLength":52,"./lib/isLowercase":53,"./lib/isMACAddress":54,"./lib/isMD5":55,"./lib/isMimeType":56,"./lib/isMobilePhone":57,"./lib/isMongoId":58,"./lib/isMultibyte":59,"./lib/isNumeric":60,"./lib/isPort":61,"./lib/isPostalCode":62,"./lib/isSurrogatePair":63,"./lib/isURL":64,"./lib/isUUID":65,"./lib/isUppercase":66,"./lib/isVariableWidth":67,"./lib/isWhitelisted":68,"./lib/ltrim":69,"./lib/matches":70,"./lib/normalizeEmail":71,"./lib/rtrim":72,"./lib/stripLow":73,"./lib/toBoolean":74,"./lib/toDate":75,"./lib/toFloat":76,"./lib/toInt":77,"./lib/trim":78,"./lib/unescape":79,"./lib/util/toString":82,"./lib/whitelist":83}],14:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var alpha = exports.alpha = {
'en-US': /^[A-Z]+$/i,
'bg-BG': /^[А-Я]+$/i,
'cs-CZ': /^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[A-ZÆØÅ]+$/i,
'de-DE': /^[A-ZÄÖÜß]+$/i,
'el-GR': /^[Α-ω]+$/i,
'es-ES': /^[A-ZÁÉÍÑÓÚÜ]+$/i,
'fr-FR': /^[A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[A-ZÀÉÈÌÎÓÒÙ]+$/i,
'nb-NO': /^[A-ZÆØÅ]+$/i,
'nl-NL': /^[A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[A-ZÆØÅ]+$/i,
'hu-HU': /^[A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'pl-PL': /^[A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,
'ru-RU': /^[А-ЯЁ]+$/i,
'sk-SK': /^[A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[A-ZÅÄÖ]+$/i,
'tr-TR': /^[A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[А-ЩЬЮЯЄIЇҐі]+$/i,
ar: /^[ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/
};
var alphanumeric = exports.alphanumeric = {
'en-US': /^[0-9A-Z]+$/i,
'bg-BG': /^[0-9А-Я]+$/i,
'cs-CZ': /^[0-9A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$/i,
'da-DK': /^[0-9A-ZÆØÅ]+$/i,
'de-DE': /^[0-9A-ZÄÖÜß]+$/i,
'el-GR': /^[0-9Α-ω]+$/i,
'es-ES': /^[0-9A-ZÁÉÍÑÓÚÜ]+$/i,
'fr-FR': /^[0-9A-ZÀÂÆÇÉÈÊËÏÎÔŒÙÛÜŸ]+$/i,
'it-IT': /^[0-9A-ZÀÉÈÌÎÓÒÙ]+$/i,
'hu-HU': /^[0-9A-ZÁÉÍÓÖŐÚÜŰ]+$/i,
'nb-NO': /^[0-9A-ZÆØÅ]+$/i,
'nl-NL': /^[0-9A-ZÁÉËÏÓÖÜÚ]+$/i,
'nn-NO': /^[0-9A-ZÆØÅ]+$/i,
'pl-PL': /^[0-9A-ZĄĆĘŚŁŃÓŻŹ]+$/i,
'pt-PT': /^[0-9A-ZÃÁÀÂÇÉÊÍÕÓÔÚÜ]+$/i,
'ru-RU': /^[0-9А-ЯЁ]+$/i,
'sk-SK': /^[0-9A-ZÁČĎÉÍŇÓŠŤÚÝŽĹŔĽÄÔ]+$/i,
'sr-RS@latin': /^[0-9A-ZČĆŽŠĐ]+$/i,
'sr-RS': /^[0-9А-ЯЂЈЉЊЋЏ]+$/i,
'sv-SE': /^[0-9A-ZÅÄÖ]+$/i,
'tr-TR': /^[0-9A-ZÇĞİıÖŞÜ]+$/i,
'uk-UA': /^[0-9А-ЩЬЮЯЄIЇҐі]+$/i,
ar: /^[٠١٢٣٤٥٦٧٨٩0-9ءآأؤإئابةتثجحخدذرزسشصضطظعغفقكلمنهوىيًٌٍَُِّْٰ]+$/
};
var decimal = exports.decimal = {
'en-US': '.',
ar: '٫'
};
var englishLocales = exports.englishLocales = ['AU', 'GB', 'HK', 'IN', 'NZ', 'ZA', 'ZM'];
for (var locale, i = 0; i < englishLocales.length; i++) {
locale = 'en-' + englishLocales[i];
alpha[locale] = alpha['en-US'];
alphanumeric[locale] = alphanumeric['en-US'];
decimal[locale] = decimal['en-US'];
}
// Source: http://www.localeplanet.com/java/
var arabicLocales = exports.arabicLocales = ['AE', 'BH', 'DZ', 'EG', 'IQ', 'JO', 'KW', 'LB', 'LY', 'MA', 'QM', 'QA', 'SA', 'SD', 'SY', 'TN', 'YE'];
for (var _locale, _i = 0; _i < arabicLocales.length; _i++) {
_locale = 'ar-' + arabicLocales[_i];
alpha[_locale] = alpha.ar;
alphanumeric[_locale] = alphanumeric.ar;
decimal[_locale] = decimal.ar;
}
// Source: https://en.wikipedia.org/wiki/Decimal_mark
var dotDecimal = exports.dotDecimal = [];
var commaDecimal = exports.commaDecimal = ['bg-BG', 'cs-CZ', 'da-DK', 'de-DE', 'el-GR', 'es-ES', 'fr-FR', 'it-IT', 'hu-HU', 'nb-NO', 'nn-NO', 'nl-NL', 'pl-Pl', 'pt-PT', 'ru-RU', 'sr-RS@latin', 'sr-RS', 'sv-SE', 'tr-TR', 'uk-UA'];
for (var _i2 = 0; _i2 < dotDecimal.length; _i2++) {
decimal[dotDecimal[_i2]] = decimal['en-US'];
}
for (var _i3 = 0; _i3 < commaDecimal.length; _i3++) {
decimal[commaDecimal[_i3]] = ',';
}
alpha['pt-BR'] = alpha['pt-PT'];
alphanumeric['pt-BR'] = alphanumeric['pt-PT'];
decimal['pt-BR'] = decimal['pt-PT'];
},{}],15:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = blacklist;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function blacklist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[' + chars + ']+', 'g'), '');
}
module.exports = exports['default'];
},{"./util/assertString":80}],16:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = contains;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toString = require('./util/toString');
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function contains(str, elem) {
(0, _assertString2.default)(str);
return str.indexOf((0, _toString2.default)(elem)) >= 0;
}
module.exports = exports['default'];
},{"./util/assertString":80,"./util/toString":82}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = equals;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function equals(str, comparison) {
(0, _assertString2.default)(str);
return str === comparison;
}
module.exports = exports['default'];
},{"./util/assertString":80}],18:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = escape;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function escape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>').replace(/\//g, '/').replace(/\\/g, '\').replace(/`/g, '`');
}
module.exports = exports['default'];
},{"./util/assertString":80}],19:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAfter;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = require('./toDate');
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAfter(str) {
var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original > comparison);
}
module.exports = exports['default'];
},{"./toDate":75,"./util/assertString":80}],20:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlpha;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlpha(str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
(0, _assertString2.default)(str);
if (locale in _alpha.alpha) {
return _alpha.alpha[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
},{"./alpha":14,"./util/assertString":80}],21:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAlphanumeric;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isAlphanumeric(str) {
var locale = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'en-US';
(0, _assertString2.default)(str);
if (locale in _alpha.alphanumeric) {
return _alpha.alphanumeric[locale].test(str);
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
},{"./alpha":14,"./util/assertString":80}],22:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isAscii;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-control-regex */
var ascii = /^[\x00-\x7F]+$/;
/* eslint-enable no-control-regex */
function isAscii(str) {
(0, _assertString2.default)(str);
return ascii.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],23:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBase64;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var notBase64 = /[^A-Z0-9+\/=]/i;
function isBase64(str) {
(0, _assertString2.default)(str);
var len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
var firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
}
module.exports = exports['default'];
},{"./util/assertString":80}],24:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBefore;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toDate = require('./toDate');
var _toDate2 = _interopRequireDefault(_toDate);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBefore(str) {
var date = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : String(new Date());
(0, _assertString2.default)(str);
var comparison = (0, _toDate2.default)(date);
var original = (0, _toDate2.default)(str);
return !!(original && comparison && original < comparison);
}
module.exports = exports['default'];
},{"./toDate":75,"./util/assertString":80}],25:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isBoolean;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isBoolean(str) {
(0, _assertString2.default)(str);
return ['true', 'false', '1', '0'].indexOf(str) >= 0;
}
module.exports = exports['default'];
},{"./util/assertString":80}],26:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = isByteLength;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable prefer-rest-params */
function isByteLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}
module.exports = exports['default'];
},{"./util/assertString":80}],27:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCreditCard;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
var creditCard = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|62[0-9]{14})$/;
/* eslint-enable max-len */
function isCreditCard(str) {
(0, _assertString2.default)(str);
var sanitized = str.replace(/[- ]+/g, '');
if (!creditCard.test(sanitized)) {
return false;
}
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = void 0;
for (var i = sanitized.length - 1; i >= 0; i--) {
digit = sanitized.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum % 10 + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return !!(sum % 10 === 0 ? sanitized : false);
}
module.exports = exports['default'];
},{"./util/assertString":80}],28:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isCurrency;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function currencyRegex(options) {
var decimal_digits = '\\d{' + options.digits_after_decimal[0] + '}';
options.digits_after_decimal.forEach(function (digit, index) {
if (index !== 0) decimal_digits = decimal_digits + '|\\d{' + digit + '}';
});
var symbol = '(\\' + options.symbol.replace(/\./g, '\\.') + ')' + (options.require_symbol ? '' : '?'),
negative = '-?',
whole_dollar_amount_without_sep = '[1-9]\\d*',
whole_dollar_amount_with_sep = '[1-9]\\d{0,2}(\\' + options.thousands_separator + '\\d{3})*',
valid_whole_dollar_amounts = ['0', whole_dollar_amount_without_sep, whole_dollar_amount_with_sep],
whole_dollar_amount = '(' + valid_whole_dollar_amounts.join('|') + ')?',
decimal_amount = '(\\' + options.decimal_separator + '(' + decimal_digits + '))' + (options.require_decimal ? '' : '?');
var pattern = whole_dollar_amount + (options.allow_decimal || options.require_decimal ? decimal_amount : '');
// default is negative sign before symbol, but there are two other options (besides parens)
if (options.allow_negatives && !options.parens_for_negatives) {
if (options.negative_sign_after_digits) {
pattern += negative;
} else if (options.negative_sign_before_digits) {
pattern = negative + pattern;
}
}
// South African Rand, for example, uses R 123 (space) and R-123 (no space)
if (options.allow_negative_sign_placeholder) {
pattern = '( (?!\\-))?' + pattern;
} else if (options.allow_space_after_symbol) {
pattern = ' ?' + pattern;
} else if (options.allow_space_after_digits) {
pattern += '( (?!$))?';
}
if (options.symbol_after_digits) {
pattern += symbol;
} else {
pattern = symbol + pattern;
}
if (options.allow_negatives) {
if (options.parens_for_negatives) {
pattern = '(\\(' + pattern + '\\)|' + pattern + ')';
} else if (!(options.negative_sign_before_digits || options.negative_sign_after_digits)) {
pattern = negative + pattern;
}
}
// ensure there's a dollar and/or decimal amount, and that
// it doesn't start with a space or a negative sign followed by a space
return new RegExp('^(?!-? )(?=.*\\d)' + pattern + '$');
}
var default_currency_options = {
symbol: '$',
require_symbol: false,
allow_space_after_symbol: false,
symbol_after_digits: false,
allow_negatives: true,
parens_for_negatives: false,
negative_sign_before_digits: false,
negative_sign_after_digits: false,
allow_negative_sign_placeholder: false,
thousands_separator: ',',
decimal_separator: '.',
allow_decimal: true,
require_decimal: false,
digits_after_decimal: [2],
allow_space_after_digits: false
};
function isCurrency(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_currency_options);
return currencyRegex(options).test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80,"./util/merge":81}],29:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDataURI;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var validMediaType = /^[a-z]+\/[a-z0-9\-\+]+$/i;
var validAttribute = /^[a-z\-]+=[a-z0-9\-]+$/i;
var validData = /^[a-z0-9!\$&'\(\)\*\+,;=\-\._~:@\/\?%\s]*$/i;
function isDataURI(str) {
(0, _assertString2.default)(str);
var data = str.split(',');
if (data.length < 2) {
return false;
}
var attributes = data.shift().trim().split(';');
var schemeAndMediaType = attributes.shift();
if (schemeAndMediaType.substr(0, 5) !== 'data:') {
return false;
}
var mediaType = schemeAndMediaType.substr(5);
if (mediaType !== '' && !validMediaType.test(mediaType)) {
return false;
}
for (var i = 0; i < attributes.length; i++) {
if (i === attributes.length - 1 && attributes[i].toLowerCase() === 'base64') {
// ok
} else if (!validAttribute.test(attributes[i])) {
return false;
}
}
for (var _i = 0; _i < data.length; _i++) {
if (!validData.test(data[_i])) {
return false;
}
}
return true;
}
module.exports = exports['default'];
},{"./util/assertString":80}],30:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDecimal;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function decimalRegExp(options) {
var regExp = new RegExp('^[-+]?([0-9]+)?(\\' + _alpha.decimal[options.locale] + '[0-9]{' + options.decimal_digits + '})' + (options.force_decimal ? '' : '?') + '$');
return regExp;
}
var default_decimal_options = {
force_decimal: false,
decimal_digits: '1,',
locale: 'en-US'
};
var blacklist = ['', '-', '+'];
function isDecimal(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_decimal_options);
if (options.locale in _alpha.decimal) {
return !blacklist.includes(str.replace(/ /g, '')) && decimalRegExp(options).test(str);
}
throw new Error('Invalid locale \'' + options.locale + '\'');
}
module.exports = exports['default'];
},{"./alpha":14,"./util/assertString":80,"./util/merge":81}],31:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isDivisibleBy;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toFloat = require('./toFloat');
var _toFloat2 = _interopRequireDefault(_toFloat);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDivisibleBy(str, num) {
(0, _assertString2.default)(str);
return (0, _toFloat2.default)(str) % parseInt(num, 10) === 0;
}
module.exports = exports['default'];
},{"./toFloat":76,"./util/assertString":80}],32:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmail;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
var _isByteLength = require('./isByteLength');
var _isByteLength2 = _interopRequireDefault(_isByteLength);
var _isFQDN = require('./isFQDN');
var _isFQDN2 = _interopRequireDefault(_isFQDN);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_email_options = {
allow_display_name: false,
require_display_name: false,
allow_utf8_local_part: true,
require_tld: true
};
/* eslint-disable max-len */
/* eslint-disable no-control-regex */
var displayName = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\,\.\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF\s]*<(.+)>$/i;
var emailUserPart = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~]+$/i;
var quotedEmailUser = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f]))*$/i;
var emailUserUtf8Part = /^[a-z\d!#\$%&'\*\+\-\/=\?\^_`{\|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+$/i;
var quotedEmailUserUtf8 = /^([\s\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|(\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*$/i;
/* eslint-enable max-len */
/* eslint-enable no-control-regex */
function isEmail(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_email_options);
if (options.require_display_name || options.allow_display_name) {
var display_email = str.match(displayName);
if (display_email) {
str = display_email[1];
} else if (options.require_display_name) {
return false;
}
}
var parts = str.split('@');
var domain = parts.pop();
var user = parts.join('@');
var lower_domain = domain.toLowerCase();
if (lower_domain === 'gmail.com' || lower_domain === 'googlemail.com') {
user = user.replace(/\./g, '').toLowerCase();
}
if (!(0, _isByteLength2.default)(user, { max: 64 }) || !(0, _isByteLength2.default)(domain, { max: 254 })) {
return false;
}
if (!(0, _isFQDN2.default)(domain, { require_tld: options.require_tld })) {
return false;
}
if (user[0] === '"') {
user = user.slice(1, user.length - 1);
return options.allow_utf8_local_part ? quotedEmailUserUtf8.test(user) : quotedEmailUser.test(user);
}
var pattern = options.allow_utf8_local_part ? emailUserUtf8Part : emailUserPart;
var user_parts = user.split('.');
for (var i = 0; i < user_parts.length; i++) {
if (!pattern.test(user_parts[i])) {
return false;
}
}
return true;
}
module.exports = exports['default'];
},{"./isByteLength":26,"./isFQDN":34,"./util/assertString":80,"./util/merge":81}],33:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isEmpty;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isEmpty(str) {
(0, _assertString2.default)(str);
return str.length === 0;
}
module.exports = exports['default'];
},{"./util/assertString":80}],34:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFQDN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_fqdn_options = {
require_tld: true,
allow_underscores: false,
allow_trailing_dot: false
};
function isFQDN(str, options) {
(0, _assertString2.default)(str);
options = (0, _merge2.default)(options, default_fqdn_options);
/* Remove the optional trailing dot before checking validity */
if (options.allow_trailing_dot && str[str.length - 1] === '.') {
str = str.substring(0, str.length - 1);
}
var parts = str.split('.');
if (options.require_tld) {
var tld = parts.pop();
if (!parts.length || !/^([a-z\u00a1-\uffff]{2,}|xn[a-z0-9-]{2,})$/i.test(tld)) {
return false;
}
// disallow spaces
if (/[\s\u2002-\u200B\u202F\u205F\u3000\uFEFF\uDB40\uDC20]/.test(tld)) {
return false;
}
}
for (var part, i = 0; i < parts.length; i++) {
part = parts[i];
if (options.allow_underscores) {
part = part.replace(/_/g, '');
}
if (!/^[a-z\u00a1-\uffff0-9-]+$/i.test(part)) {
return false;
}
// disallow full-width chars
if (/[\uff01-\uff5e]/.test(part)) {
return false;
}
if (part[0] === '-' || part[part.length - 1] === '-') {
return false;
}
}
return true;
}
module.exports = exports['default'];
},{"./util/assertString":80,"./util/merge":81}],35:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isFloat;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _alpha = require('./alpha');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isFloat(str, options) {
(0, _assertString2.default)(str);
options = options || {};
var float = new RegExp('^(?:[-+])?(?:[0-9]+)?(?:\\' + (options.locale ? _alpha.decimal[options.locale] : '.') + '[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$');
if (str === '' || str === '.' || str === '-' || str === '+') {
return false;
}
return float.test(str) && (!options.hasOwnProperty('min') || str >= options.min) && (!options.hasOwnProperty('max') || str <= options.max) && (!options.hasOwnProperty('lt') || str < options.lt) && (!options.hasOwnProperty('gt') || str > options.gt);
}
module.exports = exports['default'];
},{"./alpha":14,"./util/assertString":80}],36:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.fullWidth = undefined;
exports.default = isFullWidth;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fullWidth = exports.fullWidth = /[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isFullWidth(str) {
(0, _assertString2.default)(str);
return fullWidth.test(str);
}
},{"./util/assertString":80}],37:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.halfWidth = undefined;
exports.default = isHalfWidth;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var halfWidth = exports.halfWidth = /[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]/;
function isHalfWidth(str) {
(0, _assertString2.default)(str);
return halfWidth.test(str);
}
},{"./util/assertString":80}],38:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHash;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lengths = {
md5: 32,
md4: 32,
sha1: 40,
sha256: 64,
sha384: 96,
sha512: 128,
ripemd128: 32,
ripemd160: 40,
tiger128: 32,
tiger160: 40,
tiger192: 48,
crc32: 8,
crc32b: 8
};
function isHash(str, algorithm) {
(0, _assertString2.default)(str);
var hash = new RegExp('^[a-f0-9]{' + lengths[algorithm] + '}$');
return hash.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],39:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexColor;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexcolor = /^#?([0-9A-F]{3}|[0-9A-F]{6})$/i;
function isHexColor(str) {
(0, _assertString2.default)(str);
return hexcolor.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],40:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isHexadecimal;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var hexadecimal = /^[0-9A-F]+$/i;
function isHexadecimal(str) {
(0, _assertString2.default)(str);
return hexadecimal.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],41:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isIP;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ipv4Maybe = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
var ipv6Block = /^[0-9A-F]{1,4}$/i;
function isIP(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isIP(str, 4) || isIP(str, 6);
} else if (version === '4') {
if (!ipv4Maybe.test(str)) {
return false;
}
var parts = str.split('.').sort(function (a, b) {
return a - b;
});
return parts[3] <= 255;
} else if (version === '6') {
var blocks = str.split(':');
var foundOmissionBlock = false; // marker to indicate ::
// At least some OS accept the last 32 bits of an IPv6 address
// (i.e. 2 of the blocks) in IPv4 notation, and RFC 3493 says
// that '::ffff:a.b.c.d' is valid for IPv4-mapped IPv6 addresses,
// and '::a.b.c.d' is deprecated, but also valid.
var foundIPv4TransitionBlock = isIP(blocks[blocks.length - 1], 4);
var expectedNumberOfBlocks = foundIPv4TransitionBlock ? 7 : 8;
if (blocks.length > expectedNumberOfBlocks) {
return false;
}
// initial or final ::
if (str === '::') {
return true;
} else if (str.substr(0, 2) === '::') {
blocks.shift();
blocks.shift();
foundOmissionBlock = true;
} else if (str.substr(str.length - 2) === '::') {
blocks.pop();
blocks.pop();
foundOmissionBlock = true;
}
for (var i = 0; i < blocks.length; ++i) {
// test for a :: which can not be at the string start/end
// since those cases have been handled above
if (blocks[i] === '' && i > 0 && i < blocks.length - 1) {
if (foundOmissionBlock) {
return false; // multiple :: in address
}
foundOmissionBlock = true;
} else if (foundIPv4TransitionBlock && i === blocks.length - 1) {
// it has been checked before that the last
// block is a valid IPv4 address
} else if (!ipv6Block.test(blocks[i])) {
return false;
}
}
if (foundOmissionBlock) {
return blocks.length >= 1;
}
return blocks.length === expectedNumberOfBlocks;
}
return false;
}
module.exports = exports['default'];
},{"./util/assertString":80}],42:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISBN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isbn10Maybe = /^(?:[0-9]{9}X|[0-9]{10})$/;
var isbn13Maybe = /^(?:[0-9]{13})$/;
var factor = [1, 3];
function isISBN(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
(0, _assertString2.default)(str);
version = String(version);
if (!version) {
return isISBN(str, 10) || isISBN(str, 13);
}
var sanitized = str.replace(/[\s-]+/g, '');
var checksum = 0;
var i = void 0;
if (version === '10') {
if (!isbn10Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 9; i++) {
checksum += (i + 1) * sanitized.charAt(i);
}
if (sanitized.charAt(9) === 'X') {
checksum += 10 * 10;
} else {
checksum += 10 * sanitized.charAt(9);
}
if (checksum % 11 === 0) {
return !!sanitized;
}
} else if (version === '13') {
if (!isbn13Maybe.test(sanitized)) {
return false;
}
for (i = 0; i < 12; i++) {
checksum += factor[i % 2] * sanitized.charAt(i);
}
if (sanitized.charAt(12) - (10 - checksum % 10) % 10 === 0) {
return !!sanitized;
}
}
return false;
}
module.exports = exports['default'];
},{"./util/assertString":80}],43:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISIN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/;
function isISIN(str) {
(0, _assertString2.default)(str);
if (!isin.test(str)) {
return false;
}
var checksumStr = str.replace(/[A-Z]/g, function (character) {
return parseInt(character, 36);
});
var sum = 0;
var digit = void 0;
var tmpNum = void 0;
var shouldDouble = true;
for (var i = checksumStr.length - 2; i >= 0; i--) {
digit = checksumStr.substring(i, i + 1);
tmpNum = parseInt(digit, 10);
if (shouldDouble) {
tmpNum *= 2;
if (tmpNum >= 10) {
sum += tmpNum + 1;
} else {
sum += tmpNum;
}
} else {
sum += tmpNum;
}
shouldDouble = !shouldDouble;
}
return parseInt(str.substr(str.length - 1), 10) === (10000 - sum) % 10;
}
module.exports = exports['default'];
},{"./util/assertString":80}],44:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISO31661Alpha2;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// from https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
var validISO31661Alpha2CountriesCodes = ['AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW'];
function isISO31661Alpha2(str) {
(0, _assertString2.default)(str);
return validISO31661Alpha2CountriesCodes.includes(str.toUpperCase());
}
module.exports = exports['default'];
},{"./util/assertString":80}],45:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISO8601;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
// from http://goo.gl/0ejHHW
var iso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
/* eslint-enable max-len */
function isISO8601(str) {
(0, _assertString2.default)(str);
return iso8601.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],46:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISRC;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// see http://isrc.ifpi.org/en/isrc-standard/code-syntax
var isrc = /^[A-Z]{2}[0-9A-Z]{3}\d{2}\d{5}$/;
function isISRC(str) {
(0, _assertString2.default)(str);
return isrc.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],47:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isISSN;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var issn = '^\\d{4}-?\\d{3}[\\dX]$';
function isISSN(str) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
(0, _assertString2.default)(str);
var testIssn = issn;
testIssn = options.require_hyphen ? testIssn.replace('?', '') : testIssn;
testIssn = options.case_sensitive ? new RegExp(testIssn) : new RegExp(testIssn, 'i');
if (!testIssn.test(str)) {
return false;
}
var issnDigits = str.replace('-', '');
var position = 8;
var checksum = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = issnDigits[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var digit = _step.value;
var digitValue = digit.toUpperCase() === 'X' ? 10 : +digit;
checksum += digitValue * position;
--position;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return checksum % 11 === 0;
}
module.exports = exports['default'];
},{"./util/assertString":80}],48:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = isIn;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _toString = require('./util/toString');
var _toString2 = _interopRequireDefault(_toString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isIn(str, options) {
(0, _assertString2.default)(str);
var i = void 0;
if (Object.prototype.toString.call(options) === '[object Array]') {
var array = [];
for (i in options) {
if ({}.hasOwnProperty.call(options, i)) {
array[i] = (0, _toString2.default)(options[i]);
}
}
return array.indexOf(str) >= 0;
} else if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
return options.hasOwnProperty(str);
} else if (options && typeof options.indexOf === 'function') {
return options.indexOf(str) >= 0;
}
return false;
}
module.exports = exports['default'];
},{"./util/assertString":80,"./util/toString":82}],49:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isInt;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var int = /^(?:[-+]?(?:0|[1-9][0-9]*))$/;
var intLeadingZeroes = /^[-+]?[0-9]+$/;
function isInt(str, options) {
(0, _assertString2.default)(str);
options = options || {};
// Get the regex to use for testing, based on whether
// leading zeroes are allowed or not.
var regex = options.hasOwnProperty('allow_leading_zeroes') && !options.allow_leading_zeroes ? int : intLeadingZeroes;
// Check min/max/lt/gt
var minCheckPassed = !options.hasOwnProperty('min') || str >= options.min;
var maxCheckPassed = !options.hasOwnProperty('max') || str <= options.max;
var ltCheckPassed = !options.hasOwnProperty('lt') || str < options.lt;
var gtCheckPassed = !options.hasOwnProperty('gt') || str > options.gt;
return regex.test(str) && minCheckPassed && maxCheckPassed && ltCheckPassed && gtCheckPassed;
}
module.exports = exports['default'];
},{"./util/assertString":80}],50:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = isJSON;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isJSON(str) {
(0, _assertString2.default)(str);
try {
var obj = JSON.parse(str);
return !!obj && (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object';
} catch (e) {/* ignore */}
return false;
}
module.exports = exports['default'];
},{"./util/assertString":80}],51:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (str) {
(0, _assertString2.default)(str);
if (!str.includes(',')) return false;
var pair = str.split(',');
return lat.test(pair[0]) && long.test(pair[1]);
};
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var lat = /^\(?[+-]?(90(\.0+)?|[1-8]?\d(\.\d+)?)$/;
var long = /^\s?[+-]?(180(\.0+)?|1[0-7]\d(\.\d+)?|\d{1,2}(\.\d+)?)\)?$/;
module.exports = exports['default'];
},{"./util/assertString":80}],52:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = isLength;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable prefer-rest-params */
function isLength(str, options) {
(0, _assertString2.default)(str);
var min = void 0;
var max = void 0;
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var surrogatePairs = str.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || [];
var len = str.length - surrogatePairs.length;
return len >= min && (typeof max === 'undefined' || len <= max);
}
module.exports = exports['default'];
},{"./util/assertString":80}],53:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isLowercase;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isLowercase(str) {
(0, _assertString2.default)(str);
return str === str.toLowerCase();
}
module.exports = exports['default'];
},{"./util/assertString":80}],54:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMACAddress;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var macAddress = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/;
function isMACAddress(str) {
(0, _assertString2.default)(str);
return macAddress.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],55:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMD5;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var md5 = /^[a-f0-9]{32}$/;
function isMD5(str) {
(0, _assertString2.default)(str);
return md5.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],56:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMimeType;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
Checks if the provided string matches to a correct Media type format (MIME type)
This function only checks is the string format follows the
etablished rules by the according RFC specifications.
This function supports 'charset' in textual media types
(https://tools.ietf.org/html/rfc6657).
This function does not check against all the media types listed
by the IANA (https://www.iana.org/assignments/media-types/media-types.xhtml)
because of lightness purposes : it would require to include
all these MIME types in this librairy, which would weigh it
significantly. This kind of effort maybe is not worth for the use that
this function has in this entire librairy.
More informations in the RFC specifications :
- https://tools.ietf.org/html/rfc2045
- https://tools.ietf.org/html/rfc2046
- https://tools.ietf.org/html/rfc7231#section-3.1.1.1
- https://tools.ietf.org/html/rfc7231#section-3.1.1.5
*/
// Match simple MIME types
// NB :
// Subtype length must not exceed 100 characters.
// This rule does not comply to the RFC specs (what is the max length ?).
var mimeTypeSimple = /^(application|audio|font|image|message|model|multipart|text|video)\/[a-zA-Z0-9\.\-\+]{1,100}$/i; // eslint-disable-line max-len
// Handle "charset" in "text/*"
var mimeTypeText = /^text\/[a-zA-Z0-9\.\-\+]{1,100};\s?charset=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?$/i; // eslint-disable-line max-len
// Handle "boundary" in "multipart/*"
var mimeTypeMultipart = /^multipart\/[a-zA-Z0-9\.\-\+]{1,100}(;\s?(boundary|charset)=("[a-zA-Z0-9\.\-\+\s]{0,70}"|[a-zA-Z0-9\.\-\+]{0,70})(\s?\([a-zA-Z0-9\.\-\+\s]{1,20}\))?){0,2}$/i; // eslint-disable-line max-len
function isMimeType(str) {
(0, _assertString2.default)(str);
return mimeTypeSimple.test(str) || mimeTypeText.test(str) || mimeTypeMultipart.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],57:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMobilePhone;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable max-len */
var phones = {
'ar-AE': /^((\+?971)|0)?5[024568]\d{7}$/,
'ar-DZ': /^(\+?213|0)(5|6|7)\d{8}$/,
'ar-EG': /^((\+?20)|0)?1[012]\d{8}$/,
'ar-JO': /^(\+?962|0)?7[789]\d{7}$/,
'ar-SA': /^(!?(\+?966)|0)?5\d{8}$/,
'ar-SY': /^(!?(\+?963)|0)?9\d{8}$/,
'be-BY': /^(\+?375)?(24|25|29|33|44)\d{7}$/,
'bg-BG': /^(\+?359|0)?8[789]\d{7}$/,
'cs-CZ': /^(\+?420)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
'da-DK': /^(\+?45)?\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{2}$/,
'de-DE': /^(\+?49[ \.\-])?([\(]{1}[0-9]{1,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
'el-GR': /^(\+?30|0)?(69\d{8})$/,
'en-AU': /^(\+?61|0)4\d{8}$/,
'en-GB': /^(\+?44|0)7\d{9}$/,
'en-HK': /^(\+?852\-?)?[456789]\d{3}\-?\d{4}$/,
'en-IN': /^(\+?91|0)?[6789]\d{9}$/,
'en-KE': /^(\+?254|0)?[7]\d{8}$/,
'en-NG': /^(\+?234|0)?[789]\d{9}$/,
'en-NZ': /^(\+?64|0)2\d{7,9}$/,
'en-PK': /^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$/,
'en-RW': /^(\+?250|0)?[7]\d{8}$/,
'en-SG': /^(\+65)?[89]\d{7}$/,
'en-TZ': /^(\+?255|0)?[67]\d{8}$/,
'en-UG': /^(\+?256|0)?[7]\d{8}$/,
'en-US': /^(\+?1)?[2-9]\d{2}[2-9](?!11)\d{6}$/,
'en-ZA': /^(\+?27|0)\d{9}$/,
'en-ZM': /^(\+?26)?09[567]\d{7}$/,
'es-ES': /^(\+?34)?(6\d{1}|7[1234])\d{7}$/,
'et-EE': /^(\+?372)?\s?(5|8[1-4])\s?([0-9]\s?){6,7}$/,
'fa-IR': /^(\+?98[\-\s]?|0)9[0-39]\d[\-\s]?\d{3}[\-\s]?\d{4}$/,
'fi-FI': /^(\+?358|0)\s?(4(0|1|2|4|5|6)?|50)\s?(\d\s?){4,8}\d$/,
'fo-FO': /^(\+?298)?\s?\d{2}\s?\d{2}\s?\d{2}$/,
'fr-FR': /^(\+?33|0)[67]\d{8}$/,
'he-IL': /^(\+972|0)([23489]|5[012345689]|77)[1-9]\d{6}/,
'hu-HU': /^(\+?36)(20|30|70)\d{7}$/,
'id-ID': /^(\+?62|0[1-9])[\s|\d]+$/,
'it-IT': /^(\+?39)?\s?3\d{2} ?\d{6,7}$/,
'ja-JP': /^(\+?81|0)[789]0[ \-]?[1-9]\d{2}[ \-]?\d{5}$/,
'kk-KZ': /^(\+?7|8)?7\d{9}$/,
'kl-GL': /^(\+?299)?\s?\d{2}\s?\d{2}\s?\d{2}$/,
'ko-KR': /^((\+?82)[ \-]?)?0?1([0|1|6|7|8|9]{1})[ \-]?\d{3,4}[ \-]?\d{4}$/,
'lt-LT': /^(\+370|8)\d{8}$/,
'ms-MY': /^(\+?6?01){1}(([145]{1}(\-|\s)?\d{7,8})|([236789]{1}(\s|\-)?\d{7}))$/,
'nb-NO': /^(\+?47)?[49]\d{7}$/,
'nl-BE': /^(\+?32|0)4?\d{8}$/,
'nn-NO': /^(\+?47)?[49]\d{7}$/,
'pl-PL': /^(\+?48)? ?[5-8]\d ?\d{3} ?\d{2} ?\d{2}$/,
'pt-BR': /^(\+?55|0)\-?[1-9]{2}\-?[2-9]{1}\d{3,4}\-?\d{4}$/,
'pt-PT': /^(\+?351)?9[1236]\d{7}$/,
'ro-RO': /^(\+?4?0)\s?7\d{2}(\/|\s|\.|\-)?\d{3}(\s|\.|\-)?\d{3}$/,
'ru-RU': /^(\+?7|8)?9\d{9}$/,
'sk-SK': /^(\+?421)? ?[1-9][0-9]{2} ?[0-9]{3} ?[0-9]{3}$/,
'sr-RS': /^(\+3816|06)[- \d]{5,9}$/,
'th-TH': /^(\+66|66|0)\d{9}$/,
'tr-TR': /^(\+?90|0)?5\d{9}$/,
'uk-UA': /^(\+?38|8)?0\d{9}$/,
'vi-VN': /^(\+?84|0)?((1(2([0-9])|6([2-9])|88|99))|(9((?!5)[0-9])))([0-9]{7})$/,
'zh-CN': /^(\+?0?86\-?)?1[3456789]\d{9}$/,
'zh-TW': /^(\+?886\-?|0)?9\d{8}$/
};
/* eslint-enable max-len */
// aliases
phones['en-CA'] = phones['en-US'];
phones['fr-BE'] = phones['nl-BE'];
phones['zh-HK'] = phones['en-HK'];
function isMobilePhone(str, locale, options) {
(0, _assertString2.default)(str);
if (options && options.strictMode && !str.startsWith('+')) {
return false;
}
if (locale in phones) {
return phones[locale].test(str);
} else if (locale === 'any') {
for (var key in phones) {
if (phones.hasOwnProperty(key)) {
var phone = phones[key];
if (phone.test(str)) {
return true;
}
}
}
return false;
}
throw new Error('Invalid locale \'' + locale + '\'');
}
module.exports = exports['default'];
},{"./util/assertString":80}],58:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMongoId;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _isHexadecimal = require('./isHexadecimal');
var _isHexadecimal2 = _interopRequireDefault(_isHexadecimal);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isMongoId(str) {
(0, _assertString2.default)(str);
return (0, _isHexadecimal2.default)(str) && str.length === 24;
}
module.exports = exports['default'];
},{"./isHexadecimal":40,"./util/assertString":80}],59:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isMultibyte;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-control-regex */
var multibyte = /[^\x00-\x7F]/;
/* eslint-enable no-control-regex */
function isMultibyte(str) {
(0, _assertString2.default)(str);
return multibyte.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],60:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isNumeric;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var numeric = /^[-+]?[0-9]+$/;
function isNumeric(str) {
(0, _assertString2.default)(str);
return numeric.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],61:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isPort;
var _isInt = require('./isInt');
var _isInt2 = _interopRequireDefault(_isInt);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isPort(str) {
return (0, _isInt2.default)(str, { min: 0, max: 65535 });
}
module.exports = exports['default'];
},{"./isInt":49}],62:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.locales = undefined;
exports.default = function (str, locale) {
(0, _assertString2.default)(str);
if (locale in patterns) {
return patterns[locale].test(str);
} else if (locale === 'any') {
for (var key in patterns) {
if (patterns.hasOwnProperty(key)) {
var pattern = patterns[key];
if (pattern.test(str)) {
return true;
}
}
}
return false;
}
throw new Error('Invalid locale \'' + locale + '\'');
};
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// common patterns
var threeDigit = /^\d{3}$/;
var fourDigit = /^\d{4}$/;
var fiveDigit = /^\d{5}$/;
var sixDigit = /^\d{6}$/;
var patterns = {
AT: fourDigit,
AU: fourDigit,
BE: fourDigit,
BG: fourDigit,
CA: /^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][\s\-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i,
CH: fourDigit,
CZ: /^\d{3}\s?\d{2}$/,
DE: fiveDigit,
DK: fourDigit,
DZ: fiveDigit,
ES: fiveDigit,
FI: fiveDigit,
FR: /^\d{2}\s?\d{3}$/,
GB: /^(gir\s?0aa|[a-z]{1,2}\d[\da-z]?\s?(\d[a-z]{2})?)$/i,
GR: /^\d{3}\s?\d{2}$/,
IL: fiveDigit,
IN: sixDigit,
IS: threeDigit,
IT: fiveDigit,
JP: /^\d{3}\-\d{4}$/,
KE: fiveDigit,
LI: /^(948[5-9]|949[0-7])$/,
MX: fiveDigit,
NL: /^\d{4}\s?[a-z]{2}$/i,
NO: fourDigit,
PL: /^\d{2}\-\d{3}$/,
PT: /^\d{4}\-\d{3}?$/,
RO: sixDigit,
RU: sixDigit,
SA: fiveDigit,
SE: /^\d{3}\s?\d{2}$/,
TW: /^\d{3}(\d{2})?$/,
US: /^\d{5}(-\d{4})?$/,
ZA: fourDigit,
ZM: fiveDigit
};
var locales = exports.locales = Object.keys(patterns);
},{"./util/assertString":80}],63:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isSurrogatePair;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var surrogatePair = /[\uD800-\uDBFF][\uDC00-\uDFFF]/;
function isSurrogatePair(str) {
(0, _assertString2.default)(str);
return surrogatePair.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],64:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isURL;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _isFQDN = require('./isFQDN');
var _isFQDN2 = _interopRequireDefault(_isFQDN);
var _isIP = require('./isIP');
var _isIP2 = _interopRequireDefault(_isIP);
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_url_options = {
protocols: ['http', 'https', 'ftp'],
require_tld: true,
require_protocol: false,
require_host: true,
require_valid_protocol: true,
allow_underscores: false,
allow_trailing_dot: false,
allow_protocol_relative_urls: false
};
var wrapped_ipv6 = /^\[([^\]]+)\](?::([0-9]+))?$/;
function isRegExp(obj) {
return Object.prototype.toString.call(obj) === '[object RegExp]';
}
function checkHost(host, matches) {
for (var i = 0; i < matches.length; i++) {
var match = matches[i];
if (host === match || isRegExp(match) && match.test(host)) {
return true;
}
}
return false;
}
function isURL(url, options) {
(0, _assertString2.default)(url);
if (!url || url.length >= 2083 || /[\s<>]/.test(url)) {
return false;
}
if (url.indexOf('mailto:') === 0) {
return false;
}
options = (0, _merge2.default)(options, default_url_options);
var protocol = void 0,
auth = void 0,
host = void 0,
hostname = void 0,
port = void 0,
port_str = void 0,
split = void 0,
ipv6 = void 0;
split = url.split('#');
url = split.shift();
split = url.split('?');
url = split.shift();
split = url.split('://');
if (split.length > 1) {
protocol = split.shift();
if (options.require_valid_protocol && options.protocols.indexOf(protocol) === -1) {
return false;
}
} else if (options.require_protocol) {
return false;
} else if (options.allow_protocol_relative_urls && url.substr(0, 2) === '//') {
split[0] = url.substr(2);
}
url = split.join('://');
if (url === '') {
return false;
}
split = url.split('/');
url = split.shift();
if (url === '' && !options.require_host) {
return true;
}
split = url.split('@');
if (split.length > 1) {
auth = split.shift();
if (auth.indexOf(':') >= 0 && auth.split(':').length > 2) {
return false;
}
}
hostname = split.join('@');
port_str = null;
ipv6 = null;
var ipv6_match = hostname.match(wrapped_ipv6);
if (ipv6_match) {
host = '';
ipv6 = ipv6_match[1];
port_str = ipv6_match[2] || null;
} else {
split = hostname.split(':');
host = split.shift();
if (split.length) {
port_str = split.join(':');
}
}
if (port_str !== null) {
port = parseInt(port_str, 10);
if (!/^[0-9]+$/.test(port_str) || port <= 0 || port > 65535) {
return false;
}
}
if (!(0, _isIP2.default)(host) && !(0, _isFQDN2.default)(host, options) && (!ipv6 || !(0, _isIP2.default)(ipv6, 6))) {
return false;
}
host = host || ipv6;
if (options.host_whitelist && !checkHost(host, options.host_whitelist)) {
return false;
}
if (options.host_blacklist && checkHost(host, options.host_blacklist)) {
return false;
}
return true;
}
module.exports = exports['default'];
},{"./isFQDN":34,"./isIP":41,"./util/assertString":80,"./util/merge":81}],65:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isUUID;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var uuid = {
3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
4: /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
5: /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
all: /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i
};
function isUUID(str) {
var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'all';
(0, _assertString2.default)(str);
var pattern = uuid[version];
return pattern && pattern.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],66:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isUppercase;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isUppercase(str) {
(0, _assertString2.default)(str);
return str === str.toUpperCase();
}
module.exports = exports['default'];
},{"./util/assertString":80}],67:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isVariableWidth;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _isFullWidth = require('./isFullWidth');
var _isHalfWidth = require('./isHalfWidth');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isVariableWidth(str) {
(0, _assertString2.default)(str);
return _isFullWidth.fullWidth.test(str) && _isHalfWidth.halfWidth.test(str);
}
module.exports = exports['default'];
},{"./isFullWidth":36,"./isHalfWidth":37,"./util/assertString":80}],68:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isWhitelisted;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isWhitelisted(str, chars) {
(0, _assertString2.default)(str);
for (var i = str.length - 1; i >= 0; i--) {
if (chars.indexOf(str[i]) === -1) {
return false;
}
}
return true;
}
module.exports = exports['default'];
},{"./util/assertString":80}],69:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = ltrim;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function ltrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('^[' + chars + ']+', 'g') : /^\s+/g;
return str.replace(pattern, '');
}
module.exports = exports['default'];
},{"./util/assertString":80}],70:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = matches;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function matches(str, pattern, modifiers) {
(0, _assertString2.default)(str);
if (Object.prototype.toString.call(pattern) !== '[object RegExp]') {
pattern = new RegExp(pattern, modifiers);
}
return pattern.test(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],71:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeEmail;
var _merge = require('./util/merge');
var _merge2 = _interopRequireDefault(_merge);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var default_normalize_email_options = {
// The following options apply to all email addresses
// Lowercases the local part of the email address.
// Please note this may violate RFC 5321 as per http://stackoverflow.com/a/9808332/192024).
// The domain is always lowercased, as per RFC 1035
all_lowercase: true,
// The following conversions are specific to GMail
// Lowercases the local part of the GMail address (known to be case-insensitive)
gmail_lowercase: true,
// Removes dots from the local part of the email address, as that's ignored by GMail
gmail_remove_dots: true,
// Removes the subaddress (e.g. "+foo") from the email address
gmail_remove_subaddress: true,
// Conversts the googlemail.com domain to gmail.com
gmail_convert_googlemaildotcom: true,
// The following conversions are specific to Outlook.com / Windows Live / Hotmail
// Lowercases the local part of the Outlook.com address (known to be case-insensitive)
outlookdotcom_lowercase: true,
// Removes the subaddress (e.g. "+foo") from the email address
outlookdotcom_remove_subaddress: true,
// The following conversions are specific to Yahoo
// Lowercases the local part of the Yahoo address (known to be case-insensitive)
yahoo_lowercase: true,
// Removes the subaddress (e.g. "-foo") from the email address
yahoo_remove_subaddress: true,
// The following conversions are specific to iCloud
// Lowercases the local part of the iCloud address (known to be case-insensitive)
icloud_lowercase: true,
// Removes the subaddress (e.g. "+foo") from the email address
icloud_remove_subaddress: true
};
// List of domains used by iCloud
var icloud_domains = ['icloud.com', 'me.com'];
// List of domains used by Outlook.com and its predecessors
// This list is likely incomplete.
// Partial reference:
// https://blogs.office.com/2013/04/17/outlook-com-gets-two-step-verification-sign-in-by-alias-and-new-international-domains/
var outlookdotcom_domains = ['hotmail.at', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.co.il', 'hotmail.co.nz', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.com', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.gr', 'hotmail.com.mx', 'hotmail.com.pe', 'hotmail.com.tr', 'hotmail.com.vn', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fr', 'hotmail.hu', 'hotmail.id', 'hotmail.ie', 'hotmail.in', 'hotmail.it', 'hotmail.jp', 'hotmail.kr', 'hotmail.lv', 'hotmail.my', 'hotmail.ph', 'hotmail.pt', 'hotmail.sa', 'hotmail.sg', 'hotmail.sk', 'live.be', 'live.co.uk', 'live.com', 'live.com.ar', 'live.com.mx', 'live.de', 'live.es', 'live.eu', 'live.fr', 'live.it', 'live.nl', 'msn.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.co.il', 'outlook.co.nz', 'outlook.co.th', 'outlook.com', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.pe', 'outlook.com.tr', 'outlook.com.vn', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.id', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'passport.com'];
// List of domains used by Yahoo Mail
// This list is likely incomplete
var yahoo_domains = ['rocketmail.com', 'yahoo.ca', 'yahoo.co.uk', 'yahoo.com', 'yahoo.de', 'yahoo.fr', 'yahoo.in', 'yahoo.it', 'ymail.com'];
function normalizeEmail(email, options) {
options = (0, _merge2.default)(options, default_normalize_email_options);
var raw_parts = email.split('@');
var domain = raw_parts.pop();
var user = raw_parts.join('@');
var parts = [user, domain];
// The domain is always lowercased, as it's case-insensitive per RFC 1035
parts[1] = parts[1].toLowerCase();
if (parts[1] === 'gmail.com' || parts[1] === 'googlemail.com') {
// Address is GMail
if (options.gmail_remove_subaddress) {
parts[0] = parts[0].split('+')[0];
}
if (options.gmail_remove_dots) {
parts[0] = parts[0].replace(/\./g, '');
}
if (!parts[0].length) {
return false;
}
if (options.all_lowercase || options.gmail_lowercase) {
parts[0] = parts[0].toLowerCase();
}
parts[1] = options.gmail_convert_googlemaildotcom ? 'gmail.com' : parts[1];
} else if (~icloud_domains.indexOf(parts[1])) {
// Address is iCloud
if (options.icloud_remove_subaddress) {
parts[0] = parts[0].split('+')[0];
}
if (!parts[0].length) {
return false;
}
if (options.all_lowercase || options.icloud_lowercase) {
parts[0] = parts[0].toLowerCase();
}
} else if (~outlookdotcom_domains.indexOf(parts[1])) {
// Address is Outlook.com
if (options.outlookdotcom_remove_subaddress) {
parts[0] = parts[0].split('+')[0];
}
if (!parts[0].length) {
return false;
}
if (options.all_lowercase || options.outlookdotcom_lowercase) {
parts[0] = parts[0].toLowerCase();
}
} else if (~yahoo_domains.indexOf(parts[1])) {
// Address is Yahoo
if (options.yahoo_remove_subaddress) {
var components = parts[0].split('-');
parts[0] = components.length > 1 ? components.slice(0, -1).join('-') : components[0];
}
if (!parts[0].length) {
return false;
}
if (options.all_lowercase || options.yahoo_lowercase) {
parts[0] = parts[0].toLowerCase();
}
} else if (options.all_lowercase) {
// Any other address
parts[0] = parts[0].toLowerCase();
}
return parts.join('@');
}
module.exports = exports['default'];
},{"./util/merge":81}],72:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rtrim;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function rtrim(str, chars) {
(0, _assertString2.default)(str);
var pattern = chars ? new RegExp('[' + chars + ']') : /\s/;
var idx = str.length - 1;
while (idx >= 0 && pattern.test(str[idx])) {
idx--;
}
return idx < str.length ? str.substr(0, idx + 1) : str;
}
module.exports = exports['default'];
},{"./util/assertString":80}],73:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = stripLow;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
var _blacklist = require('./blacklist');
var _blacklist2 = _interopRequireDefault(_blacklist);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function stripLow(str, keep_new_lines) {
(0, _assertString2.default)(str);
var chars = keep_new_lines ? '\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F' : '\\x00-\\x1F\\x7F';
return (0, _blacklist2.default)(str, chars);
}
module.exports = exports['default'];
},{"./blacklist":15,"./util/assertString":80}],74:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toBoolean;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toBoolean(str, strict) {
(0, _assertString2.default)(str);
if (strict) {
return str === '1' || str === 'true';
}
return str !== '0' && str !== 'false' && str !== '';
}
module.exports = exports['default'];
},{"./util/assertString":80}],75:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toDate;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toDate(date) {
(0, _assertString2.default)(date);
date = Date.parse(date);
return !isNaN(date) ? new Date(date) : null;
}
module.exports = exports['default'];
},{"./util/assertString":80}],76:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toFloat;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toFloat(str) {
(0, _assertString2.default)(str);
return parseFloat(str);
}
module.exports = exports['default'];
},{"./util/assertString":80}],77:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = toInt;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function toInt(str, radix) {
(0, _assertString2.default)(str);
return parseInt(str, radix || 10);
}
module.exports = exports['default'];
},{"./util/assertString":80}],78:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = trim;
var _rtrim = require('./rtrim');
var _rtrim2 = _interopRequireDefault(_rtrim);
var _ltrim = require('./ltrim');
var _ltrim2 = _interopRequireDefault(_ltrim);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function trim(str, chars) {
return (0, _rtrim2.default)((0, _ltrim2.default)(str, chars), chars);
}
module.exports = exports['default'];
},{"./ltrim":69,"./rtrim":72}],79:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unescape;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function unescape(str) {
(0, _assertString2.default)(str);
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(///g, '/').replace(/\/g, '\\').replace(/`/g, '`');
}
module.exports = exports['default'];
},{"./util/assertString":80}],80:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = assertString;
function assertString(input) {
var isString = typeof input === 'string' || input instanceof String;
if (!isString) {
throw new TypeError('This library (validator.js) validates strings only');
}
}
module.exports = exports['default'];
},{}],81:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = merge;
function merge() {
var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var defaults = arguments[1];
for (var key in defaults) {
if (typeof obj[key] === 'undefined') {
obj[key] = defaults[key];
}
}
return obj;
}
module.exports = exports['default'];
},{}],82:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.default = toString;
function toString(input) {
if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input !== null) {
if (typeof input.toString === 'function') {
input = input.toString();
} else {
input = '[object Object]';
}
} else if (input === null || typeof input === 'undefined' || isNaN(input) && !input.length) {
input = '';
}
return String(input);
}
module.exports = exports['default'];
},{}],83:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = whitelist;
var _assertString = require('./util/assertString');
var _assertString2 = _interopRequireDefault(_assertString);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function whitelist(str, chars) {
(0, _assertString2.default)(str);
return str.replace(new RegExp('[^' + chars + ']+', 'g'), '');
}
module.exports = exports['default'];
},{"./util/assertString":80}],84:[function(require,module,exports){
function DOMParser(options){
this.options = options ||{locator:{}};
}
DOMParser.prototype.parseFromString = function(source,mimeType){
var options = this.options;
var sax = new XMLReader();
var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
var errorHandler = options.errorHandler;
var locator = options.locator;
var defaultNSMap = options.xmlns||{};
var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
if(locator){
domBuilder.setDocumentLocator(locator)
}
sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
sax.domBuilder = options.domBuilder || domBuilder;
if(isHTML){
defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
}
defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
if(source && typeof source === 'string'){
sax.parse(source,defaultNSMap,entityMap);
}else{
sax.errorHandler.error("invalid doc source");
}
return domBuilder.doc;
}
function buildErrorHandler(errorImpl,domBuilder,locator){
if(!errorImpl){
if(domBuilder instanceof DOMHandler){
return domBuilder;
}
errorImpl = domBuilder ;
}
var errorHandler = {}
var isCallback = errorImpl instanceof Function;
locator = locator||{}
function build(key){
var fn = errorImpl[key];
if(!fn && isCallback){
fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
}
errorHandler[key] = fn && function(msg){
fn('[xmldom '+key+']\t'+msg+_locator(locator));
}||function(){};
}
build('warning');
build('error');
build('fatalError');
return errorHandler;
}
//console.log('#\n\n\n\n\n\n\n####')
/**
* +ContentHandler+ErrorHandler
* +LexicalHandler+EntityResolver2
* -DeclHandler-DTDHandler
*
* DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
* DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
* @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
*/
function DOMHandler() {
this.cdata = false;
}
function position(locator,node){
node.lineNumber = locator.lineNumber;
node.columnNumber = locator.columnNumber;
}
/**
* @see org.xml.sax.ContentHandler#startDocument
* @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
*/
DOMHandler.prototype = {
startDocument : function() {
this.doc = new DOMImplementation().createDocument(null, null, null);
if (this.locator) {
this.doc.documentURI = this.locator.systemId;
}
},
startElement:function(namespaceURI, localName, qName, attrs) {
var doc = this.doc;
var el = doc.createElementNS(namespaceURI, qName||localName);
var len = attrs.length;
appendElement(this, el);
this.currentElement = el;
this.locator && position(this.locator,el)
for (var i = 0 ; i < len; i++) {
var namespaceURI = attrs.getURI(i);
var value = attrs.getValue(i);
var qName = attrs.getQName(i);
var attr = doc.createAttributeNS(namespaceURI, qName);
this.locator &&position(attrs.getLocator(i),attr);
attr.value = attr.nodeValue = value;
el.setAttributeNode(attr)
}
},
endElement:function(namespaceURI, localName, qName) {
var current = this.currentElement
var tagName = current.tagName;
this.currentElement = current.parentNode;
},
startPrefixMapping:function(prefix, uri) {
},
endPrefixMapping:function(prefix) {
},
processingInstruction:function(target, data) {
var ins = this.doc.createProcessingInstruction(target, data);
this.locator && position(this.locator,ins)
appendElement(this, ins);
},
ignorableWhitespace:function(ch, start, length) {
},
characters:function(chars, start, length) {
chars = _toString.apply(this,arguments)
//console.log(chars)
if(chars){
if (this.cdata) {
var charNode = this.doc.createCDATASection(chars);
} else {
var charNode = this.doc.createTextNode(chars);
}
if(this.currentElement){
this.currentElement.appendChild(charNode);
}else if(/^\s*$/.test(chars)){
this.doc.appendChild(charNode);
//process xml
}
this.locator && position(this.locator,charNode)
}
},
skippedEntity:function(name) {
},
endDocument:function() {
this.doc.normalize();
},
setDocumentLocator:function (locator) {
if(this.locator = locator){// && !('lineNumber' in locator)){
locator.lineNumber = 0;
}
},
//LexicalHandler
comment:function(chars, start, length) {
chars = _toString.apply(this,arguments)
var comm = this.doc.createComment(chars);
this.locator && position(this.locator,comm)
appendElement(this, comm);
},
startCDATA:function() {
//used in characters() methods
this.cdata = true;
},
endCDATA:function() {
this.cdata = false;
},
startDTD:function(name, publicId, systemId) {
var impl = this.doc.implementation;
if (impl && impl.createDocumentType) {
var dt = impl.createDocumentType(name, publicId, systemId);
this.locator && position(this.locator,dt)
appendElement(this, dt);
}
},
/**
* @see org.xml.sax.ErrorHandler
* @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
*/
warning:function(error) {
console.warn('[xmldom warning]\t'+error,_locator(this.locator));
},
error:function(error) {
console.error('[xmldom error]\t'+error,_locator(this.locator));
},
fatalError:function(error) {
throw new ParseError(error, this.locator);
}
}
function _locator(l){
if(l){
return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
}
}
function _toString(chars,start,length){
if(typeof chars == 'string'){
return chars.substr(start,length)
}else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
if(chars.length >= start+length || start){
return new java.lang.String(chars,start,length)+'';
}
return chars;
}
}
/*
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
* used method of org.xml.sax.ext.LexicalHandler:
* #comment(chars, start, length)
* #startCDATA()
* #endCDATA()
* #startDTD(name, publicId, systemId)
*
*
* IGNORED method of org.xml.sax.ext.LexicalHandler:
* #endDTD()
* #startEntity(name)
* #endEntity(name)
*
*
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
* IGNORED method of org.xml.sax.ext.DeclHandler
* #attributeDecl(eName, aName, type, mode, value)
* #elementDecl(name, model)
* #externalEntityDecl(name, publicId, systemId)
* #internalEntityDecl(name, value)
* @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
* IGNORED method of org.xml.sax.EntityResolver2
* #resolveEntity(String name,String publicId,String baseURI,String systemId)
* #resolveEntity(publicId, systemId)
* #getExternalSubset(name, baseURI)
* @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
* IGNORED method of org.xml.sax.DTDHandler
* #notationDecl(name, publicId, systemId) {};
* #unparsedEntityDecl(name, publicId, systemId, notationName) {};
*/
"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
DOMHandler.prototype[key] = function(){return null}
})
/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
function appendElement (hander,node) {
if (!hander.currentElement) {
hander.doc.appendChild(node);
} else {
hander.currentElement.appendChild(node);
}
}//appendChild and setAttributeNS are preformance key
//if(typeof require == 'function'){
var htmlEntity = require('./entities');
var sax = require('./sax');
var XMLReader = sax.XMLReader;
var ParseError = sax.ParseError;
var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
exports.XMLSerializer = require('./dom').XMLSerializer ;
exports.DOMParser = DOMParser;
exports.__DOMHandler = DOMHandler;
//}
},{"./dom":85,"./entities":86,"./sax":87}],85:[function(require,module,exports){
function copy(src,dest){
for(var p in src){
dest[p] = src[p];
}
}
/**
^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
*/
function _extends(Class,Super){
var pt = Class.prototype;
if(!(pt instanceof Super)){
function t(){};
t.prototype = Super.prototype;
t = new t();
copy(pt,t);
Class.prototype = pt = t;
}
if(pt.constructor != Class){
if(typeof Class != 'function'){
console.error("unknow Class:"+Class)
}
pt.constructor = Class
}
}
var htmlns = 'http://www.w3.org/1999/xhtml' ;
// Node Types
var NodeType = {}
var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
var TEXT_NODE = NodeType.TEXT_NODE = 3;
var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
// ExceptionCode
var ExceptionCode = {}
var ExceptionMessage = {};
var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
//level2
var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
/**
* DOM Level 2
* Object DOMException
* @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
* @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
*/
function DOMException(code, message) {
if(message instanceof Error){
var error = message;
}else{
error = this;
Error.call(this, ExceptionMessage[code]);
this.message = ExceptionMessage[code];
if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
}
error.code = code;
if(message) this.message = this.message + ": " + message;
return error;
};
DOMException.prototype = Error.prototype;
copy(ExceptionCode,DOMException)
/**
* @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
* The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
* The items in the NodeList are accessible via an integral index, starting from 0.
*/
function NodeList() {
};
NodeList.prototype = {
/**
* The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
* @standard level1
*/
length:0,
/**
* Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
* @standard level1
* @param index unsigned long
* Index into the collection.
* @return Node
* The node at the indexth position in the NodeList, or null if that is not a valid index.
*/
item: function(index) {
return this[index] || null;
},
toString:function(isHTML,nodeFilter){
for(var buf = [], i = 0;i<this.length;i++){
serializeToString(this[i],buf,isHTML,nodeFilter);
}
return buf.join('');
}
};
function LiveNodeList(node,refresh){
this._node = node;
this._refresh = refresh
_updateLiveList(this);
}
function _updateLiveList(list){
var inc = list._node._inc || list._node.ownerDocument._inc;
if(list._inc != inc){
var ls = list._refresh(list._node);
//console.log(ls.length)
__set__(list,'length',ls.length);
copy(ls,list);
list._inc = inc;
}
}
LiveNodeList.prototype.item = function(i){
_updateLiveList(this);
return this[i];
}
_extends(LiveNodeList,NodeList);
/**
*
* Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
* NamedNodeMap objects in the DOM are live.
* used for attributes or DocumentType entities
*/
function NamedNodeMap() {
};
function _findNodeIndex(list,node){
var i = list.length;
while(i--){
if(list[i] === node){return i}
}
}
function _addNamedNode(el,list,newAttr,oldAttr){
if(oldAttr){
list[_findNodeIndex(list,oldAttr)] = newAttr;
}else{
list[list.length++] = newAttr;
}
if(el){
newAttr.ownerElement = el;
var doc = el.ownerDocument;
if(doc){
oldAttr && _onRemoveAttribute(doc,el,oldAttr);
_onAddAttribute(doc,el,newAttr);
}
}
}
function _removeNamedNode(el,list,attr){
//console.log('remove attr:'+attr)
var i = _findNodeIndex(list,attr);
if(i>=0){
var lastIndex = list.length-1
while(i<lastIndex){
list[i] = list[++i]
}
list.length = lastIndex;
if(el){
var doc = el.ownerDocument;
if(doc){
_onRemoveAttribute(doc,el,attr);
attr.ownerElement = null;
}
}
}else{
throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
}
}
NamedNodeMap.prototype = {
length:0,
item:NodeList.prototype.item,
getNamedItem: function(key) {
// if(key.indexOf(':')>0 || key == 'xmlns'){
// return null;
// }
//console.log()
var i = this.length;
while(i--){
var attr = this[i];
//console.log(attr.nodeName,key)
if(attr.nodeName == key){
return attr;
}
}
},
setNamedItem: function(attr) {
var el = attr.ownerElement;
if(el && el!=this._ownerElement){
throw new DOMException(INUSE_ATTRIBUTE_ERR);
}
var oldAttr = this.getNamedItem(attr.nodeName);
_addNamedNode(this._ownerElement,this,attr,oldAttr);
return oldAttr;
},
/* returns Node */
setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
var el = attr.ownerElement, oldAttr;
if(el && el!=this._ownerElement){
throw new DOMException(INUSE_ATTRIBUTE_ERR);
}
oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
_addNamedNode(this._ownerElement,this,attr,oldAttr);
return oldAttr;
},
/* returns Node */
removeNamedItem: function(key) {
var attr = this.getNamedItem(key);
_removeNamedNode(this._ownerElement,this,attr);
return attr;
},// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
//for level2
removeNamedItemNS:function(namespaceURI,localName){
var attr = this.getNamedItemNS(namespaceURI,localName);
_removeNamedNode(this._ownerElement,this,attr);
return attr;
},
getNamedItemNS: function(namespaceURI, localName) {
var i = this.length;
while(i--){
var node = this[i];
if(node.localName == localName && node.namespaceURI == namespaceURI){
return node;
}
}
return null;
}
};
/**
* @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
*/
function DOMImplementation(/* Object */ features) {
this._features = {};
if (features) {
for (var feature in features) {
this._features = features[feature];
}
}
};
DOMImplementation.prototype = {
hasFeature: function(/* string */ feature, /* string */ version) {
var versions = this._features[feature.toLowerCase()];
if (versions && (!version || version in versions)) {
return true;
} else {
return false;
}
},
// Introduced in DOM Level 2:
createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
var doc = new Document();
doc.implementation = this;
doc.childNodes = new NodeList();
doc.doctype = doctype;
if(doctype){
doc.appendChild(doctype);
}
if(qualifiedName){
var root = doc.createElementNS(namespaceURI,qualifiedName);
doc.appendChild(root);
}
return doc;
},
// Introduced in DOM Level 2:
createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
var node = new DocumentType();
node.name = qualifiedName;
node.nodeName = qualifiedName;
node.publicId = publicId;
node.systemId = systemId;
// Introduced in DOM Level 2:
//readonly attribute DOMString internalSubset;
//TODO:..
// readonly attribute NamedNodeMap entities;
// readonly attribute NamedNodeMap notations;
return node;
}
};
/**
* @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
*/
function Node() {
};
Node.prototype = {
firstChild : null,
lastChild : null,
previousSibling : null,
nextSibling : null,
attributes : null,
parentNode : null,
childNodes : null,
ownerDocument : null,
nodeValue : null,
namespaceURI : null,
prefix : null,
localName : null,
// Modified in DOM Level 2:
insertBefore:function(newChild, refChild){//raises
return _insertBefore(this,newChild,refChild);
},
replaceChild:function(newChild, oldChild){//raises
this.insertBefore(newChild,oldChild);
if(oldChild){
this.removeChild(oldChild);
}
},
removeChild:function(oldChild){
return _removeChild(this,oldChild);
},
appendChild:function(newChild){
return this.insertBefore(newChild,null);
},
hasChildNodes:function(){
return this.firstChild != null;
},
cloneNode:function(deep){
return cloneNode(this.ownerDocument||this,this,deep);
},
// Modified in DOM Level 2:
normalize:function(){
var child = this.firstChild;
while(child){
var next = child.nextSibling;
if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
this.removeChild(next);
child.appendData(next.data);
}else{
child.normalize();
child = next;
}
}
},
// Introduced in DOM Level 2:
isSupported:function(feature, version){
return this.ownerDocument.implementation.hasFeature(feature,version);
},
// Introduced in DOM Level 2:
hasAttributes:function(){
return this.attributes.length>0;
},
lookupPrefix:function(namespaceURI){
var el = this;
while(el){
var map = el._nsMap;
//console.dir(map)
if(map){
for(var n in map){
if(map[n] == namespaceURI){
return n;
}
}
}
el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
}
return null;
},
// Introduced in DOM Level 3:
lookupNamespaceURI:function(prefix){
var el = this;
while(el){
var map = el._nsMap;
//console.dir(map)
if(map){
if(prefix in map){
return map[prefix] ;
}
}
el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
}
return null;
},
// Introduced in DOM Level 3:
isDefaultNamespace:function(namespaceURI){
var prefix = this.lookupPrefix(namespaceURI);
return prefix == null;
}
};
function _xmlEncoder(c){
return c == '<' && '<' ||
c == '>' && '>' ||
c == '&' && '&' ||
c == '"' && '"' ||
'&#'+c.charCodeAt()+';'
}
copy(NodeType,Node);
copy(NodeType,Node.prototype);
/**
* @param callback return true for continue,false for break
* @return boolean true: break visit;
*/
function _visitNode(node,callback){
if(callback(node)){
return true;
}
if(node = node.firstChild){
do{
if(_visitNode(node,callback)){return true}
}while(node=node.nextSibling)
}
}
function Document(){
}
function _onAddAttribute(doc,el,newAttr){
doc && doc._inc++;
var ns = newAttr.namespaceURI ;
if(ns == 'http://www.w3.org/2000/xmlns/'){
//update namespace
el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
}
}
function _onRemoveAttribute(doc,el,newAttr,remove){
doc && doc._inc++;
var ns = newAttr.namespaceURI ;
if(ns == 'http://www.w3.org/2000/xmlns/'){
//update namespace
delete el._nsMap[newAttr.prefix?newAttr.localName:'']
}
}
function _onUpdateChild(doc,el,newChild){
if(doc && doc._inc){
doc._inc++;
//update childNodes
var cs = el.childNodes;
if(newChild){
cs[cs.length++] = newChild;
}else{
//console.log(1)
var child = el.firstChild;
var i = 0;
while(child){
cs[i++] = child;
child =child.nextSibling;
}
cs.length = i;
}
}
}
/**
* attributes;
* children;
*
* writeable properties:
* nodeValue,Attr:value,CharacterData:data
* prefix
*/
function _removeChild(parentNode,child){
var previous = child.previousSibling;
var next = child.nextSibling;
if(previous){
previous.nextSibling = next;
}else{
parentNode.firstChild = next
}
if(next){
next.previousSibling = previous;
}else{
parentNode.lastChild = previous;
}
_onUpdateChild(parentNode.ownerDocument,parentNode);
return child;
}
/**
* preformance key(refChild == null)
*/
function _insertBefore(parentNode,newChild,nextChild){
var cp = newChild.parentNode;
if(cp){
cp.removeChild(newChild);//remove and update
}
if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
var newFirst = newChild.firstChild;
if (newFirst == null) {
return newChild;
}
var newLast = newChild.lastChild;
}else{
newFirst = newLast = newChild;
}
var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
newFirst.previousSibling = pre;
newLast.nextSibling = nextChild;
if(pre){
pre.nextSibling = newFirst;
}else{
parentNode.firstChild = newFirst;
}
if(nextChild == null){
parentNode.lastChild = newLast;
}else{
nextChild.previousSibling = newLast;
}
do{
newFirst.parentNode = parentNode;
}while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
_onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
//console.log(parentNode.lastChild.nextSibling == null)
if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
newChild.firstChild = newChild.lastChild = null;
}
return newChild;
}
function _appendSingleChild(parentNode,newChild){
var cp = newChild.parentNode;
if(cp){
var pre = parentNode.lastChild;
cp.removeChild(newChild);//remove and update
var pre = parentNode.lastChild;
}
var pre = parentNode.lastChild;
newChild.parentNode = parentNode;
newChild.previousSibling = pre;
newChild.nextSibling = null;
if(pre){
pre.nextSibling = newChild;
}else{
parentNode.firstChild = newChild;
}
parentNode.lastChild = newChild;
_onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
return newChild;
//console.log("__aa",parentNode.lastChild.nextSibling == null)
}
Document.prototype = {
//implementation : null,
nodeName : '#document',
nodeType : DOCUMENT_NODE,
doctype : null,
documentElement : null,
_inc : 1,
insertBefore : function(newChild, refChild){//raises
if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
var child = newChild.firstChild;
while(child){
var next = child.nextSibling;
this.insertBefore(child,refChild);
child = next;
}
return newChild;
}
if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
this.documentElement = newChild;
}
return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
},
removeChild : function(oldChild){
if(this.documentElement == oldChild){
this.documentElement = null;
}
return _removeChild(this,oldChild);
},
// Introduced in DOM Level 2:
importNode : function(importedNode,deep){
return importNode(this,importedNode,deep);
},
// Introduced in DOM Level 2:
getElementById : function(id){
var rtv = null;
_visitNode(this.documentElement,function(node){
if(node.nodeType == ELEMENT_NODE){
if(node.getAttribute('id') == id){
rtv = node;
return true;
}
}
})
return rtv;
},
getElementsByClassName: function(className) {
var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
return new LiveNodeList(this, function(base) {
var ls = [];
_visitNode(base.documentElement, function(node) {
if(node !== base && node.nodeType == ELEMENT_NODE) {
if(pattern.test(node.getAttribute('class'))) {
ls.push(node);
}
}
});
return ls;
});
},
//document factory method:
createElement : function(tagName){
var node = new Element();
node.ownerDocument = this;
node.nodeName = tagName;
node.tagName = tagName;
node.childNodes = new NodeList();
var attrs = node.attributes = new NamedNodeMap();
attrs._ownerElement = node;
return node;
},
createDocumentFragment : function(){
var node = new DocumentFragment();
node.ownerDocument = this;
node.childNodes = new NodeList();
return node;
},
createTextNode : function(data){
var node = new Text();
node.ownerDocument = this;
node.appendData(data)
return node;
},
createComment : function(data){
var node = new Comment();
node.ownerDocument = this;
node.appendData(data)
return node;
},
createCDATASection : function(data){
var node = new CDATASection();
node.ownerDocument = this;
node.appendData(data)
return node;
},
createProcessingInstruction : function(target,data){
var node = new ProcessingInstruction();
node.ownerDocument = this;
node.tagName = node.target = target;
node.nodeValue= node.data = data;
return node;
},
createAttribute : function(name){
var node = new Attr();
node.ownerDocument = this;
node.name = name;
node.nodeName = name;
node.localName = name;
node.specified = true;
return node;
},
createEntityReference : function(name){
var node = new EntityReference();
node.ownerDocument = this;
node.nodeName = name;
return node;
},
// Introduced in DOM Level 2:
createElementNS : function(namespaceURI,qualifiedName){
var node = new Element();
var pl = qualifiedName.split(':');
var attrs = node.attributes = new NamedNodeMap();
node.childNodes = new NodeList();
node.ownerDocument = this;
node.nodeName = qualifiedName;
node.tagName = qualifiedName;
node.namespaceURI = namespaceURI;
if(pl.length == 2){
node.prefix = pl[0];
node.localName = pl[1];
}else{
//el.prefix = null;
node.localName = qualifiedName;
}
attrs._ownerElement = node;
return node;
},
// Introduced in DOM Level 2:
createAttributeNS : function(namespaceURI,qualifiedName){
var node = new Attr();
var pl = qualifiedName.split(':');
node.ownerDocument = this;
node.nodeName = qualifiedName;
node.name = qualifiedName;
node.namespaceURI = namespaceURI;
node.specified = true;
if(pl.length == 2){
node.prefix = pl[0];
node.localName = pl[1];
}else{
//el.prefix = null;
node.localName = qualifiedName;
}
return node;
}
};
_extends(Document,Node);
function Element() {
this._nsMap = {};
};
Element.prototype = {
nodeType : ELEMENT_NODE,
hasAttribute : function(name){
return this.getAttributeNode(name)!=null;
},
getAttribute : function(name){
var attr = this.getAttributeNode(name);
return attr && attr.value || '';
},
getAttributeNode : function(name){
return this.attributes.getNamedItem(name);
},
setAttribute : function(name, value){
var attr = this.ownerDocument.createAttribute(name);
attr.value = attr.nodeValue = "" + value;
this.setAttributeNode(attr)
},
removeAttribute : function(name){
var attr = this.getAttributeNode(name)
attr && this.removeAttributeNode(attr);
},
//four real opeartion method
appendChild:function(newChild){
if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
return this.insertBefore(newChild,null);
}else{
return _appendSingleChild(this,newChild);
}
},
setAttributeNode : function(newAttr){
return this.attributes.setNamedItem(newAttr);
},
setAttributeNodeNS : function(newAttr){
return this.attributes.setNamedItemNS(newAttr);
},
removeAttributeNode : function(oldAttr){
//console.log(this == oldAttr.ownerElement)
return this.attributes.removeNamedItem(oldAttr.nodeName);
},
//get real attribute name,and remove it by removeAttributeNode
removeAttributeNS : function(namespaceURI, localName){
var old = this.getAttributeNodeNS(namespaceURI, localName);
old && this.removeAttributeNode(old);
},
hasAttributeNS : function(namespaceURI, localName){
return this.getAttributeNodeNS(namespaceURI, localName)!=null;
},
getAttributeNS : function(namespaceURI, localName){
var attr = this.getAttributeNodeNS(namespaceURI, localName);
return attr && attr.value || '';
},
setAttributeNS : function(namespaceURI, qualifiedName, value){
var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
attr.value = attr.nodeValue = "" + value;
this.setAttributeNode(attr)
},
getAttributeNodeNS : function(namespaceURI, localName){
return this.attributes.getNamedItemNS(namespaceURI, localName);
},
getElementsByTagName : function(tagName){
return new LiveNodeList(this,function(base){
var ls = [];
_visitNode(base,function(node){
if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
ls.push(node);
}
});
return ls;
});
},
getElementsByTagNameNS : function(namespaceURI, localName){
return new LiveNodeList(this,function(base){
var ls = [];
_visitNode(base,function(node){
if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
ls.push(node);
}
});
return ls;
});
}
};
Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
_extends(Element,Node);
function Attr() {
};
Attr.prototype.nodeType = ATTRIBUTE_NODE;
_extends(Attr,Node);
function CharacterData() {
};
CharacterData.prototype = {
data : '',
substringData : function(offset, count) {
return this.data.substring(offset, offset+count);
},
appendData: function(text) {
text = this.data+text;
this.nodeValue = this.data = text;
this.length = text.length;
},
insertData: function(offset,text) {
this.replaceData(offset,0,text);
},
appendChild:function(newChild){
throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
},
deleteData: function(offset, count) {
this.replaceData(offset,count,"");
},
replaceData: function(offset, count, text) {
var start = this.data.substring(0,offset);
var end = this.data.substring(offset+count);
text = start + text + end;
this.nodeValue = this.data = text;
this.length = text.length;
}
}
_extends(CharacterData,Node);
function Text() {
};
Text.prototype = {
nodeName : "#text",
nodeType : TEXT_NODE,
splitText : function(offset) {
var text = this.data;
var newText = text.substring(offset);
text = text.substring(0, offset);
this.data = this.nodeValue = text;
this.length = text.length;
var newNode = this.ownerDocument.createTextNode(newText);
if(this.parentNode){
this.parentNode.insertBefore(newNode, this.nextSibling);
}
return newNode;
}
}
_extends(Text,CharacterData);
function Comment() {
};
Comment.prototype = {
nodeName : "#comment",
nodeType : COMMENT_NODE
}
_extends(Comment,CharacterData);
function CDATASection() {
};
CDATASection.prototype = {
nodeName : "#cdata-section",
nodeType : CDATA_SECTION_NODE
}
_extends(CDATASection,CharacterData);
function DocumentType() {
};
DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
_extends(DocumentType,Node);
function Notation() {
};
Notation.prototype.nodeType = NOTATION_NODE;
_extends(Notation,Node);
function Entity() {
};
Entity.prototype.nodeType = ENTITY_NODE;
_extends(Entity,Node);
function EntityReference() {
};
EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
_extends(EntityReference,Node);
function DocumentFragment() {
};
DocumentFragment.prototype.nodeName = "#document-fragment";
DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
_extends(DocumentFragment,Node);
function ProcessingInstruction() {
}
ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
_extends(ProcessingInstruction,Node);
function XMLSerializer(){}
XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
return nodeSerializeToString.call(node,isHtml,nodeFilter);
}
Node.prototype.toString = nodeSerializeToString;
function nodeSerializeToString(isHtml,nodeFilter){
var buf = [];
var refNode = this.nodeType == 9 && this.documentElement || this;
var prefix = refNode.prefix;
var uri = refNode.namespaceURI;
if(uri && prefix == null){
//console.log(prefix)
var prefix = refNode.lookupPrefix(uri);
if(prefix == null){
//isHTML = true;
var visibleNamespaces=[
{namespace:uri,prefix:null}
//{namespace:uri,prefix:''}
]
}
}
serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
//console.log('###',this.nodeType,uri,prefix,buf.join(''))
return buf.join('');
}
function needNamespaceDefine(node,isHTML, visibleNamespaces) {
var prefix = node.prefix||'';
var uri = node.namespaceURI;
if (!prefix && !uri){
return false;
}
if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
|| uri == 'http://www.w3.org/2000/xmlns/'){
return false;
}
var i = visibleNamespaces.length
//console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
while (i--) {
var ns = visibleNamespaces[i];
// get namespace prefix
//console.log(node.nodeType,node.tagName,ns.prefix,prefix)
if (ns.prefix == prefix){
return ns.namespace != uri;
}
}
//console.log(isHTML,uri,prefix=='')
//if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
// return false;
//}
//node.flag = '11111'
//console.error(3,true,node.flag,node.prefix,node.namespaceURI)
return true;
}
function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
if(nodeFilter){
node = nodeFilter(node);
if(node){
if(typeof node == 'string'){
buf.push(node);
return;
}
}else{
return;
}
//buf.sort.apply(attrs, attributeSorter);
}
switch(node.nodeType){
case ELEMENT_NODE:
if (!visibleNamespaces) visibleNamespaces = [];
var startVisibleNamespaces = visibleNamespaces.length;
var attrs = node.attributes;
var len = attrs.length;
var child = node.firstChild;
var nodeName = node.tagName;
isHTML = (htmlns === node.namespaceURI) ||isHTML
buf.push('<',nodeName);
for(var i=0;i<len;i++){
// add namespaces for attributes
var attr = attrs.item(i);
if (attr.prefix == 'xmlns') {
visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
}else if(attr.nodeName == 'xmlns'){
visibleNamespaces.push({ prefix: '', namespace: attr.value });
}
}
for(var i=0;i<len;i++){
var attr = attrs.item(i);
if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
var prefix = attr.prefix||'';
var uri = attr.namespaceURI;
var ns = prefix ? ' xmlns:' + prefix : " xmlns";
buf.push(ns, '="' , uri , '"');
visibleNamespaces.push({ prefix: prefix, namespace:uri });
}
serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
}
// add namespace for current node
if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
var prefix = node.prefix||'';
var uri = node.namespaceURI;
var ns = prefix ? ' xmlns:' + prefix : " xmlns";
buf.push(ns, '="' , uri , '"');
visibleNamespaces.push({ prefix: prefix, namespace:uri });
}
if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
buf.push('>');
//if is cdata child node
if(isHTML && /^script$/i.test(nodeName)){
while(child){
if(child.data){
buf.push(child.data);
}else{
serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
}
child = child.nextSibling;
}
}else
{
while(child){
serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
child = child.nextSibling;
}
}
buf.push('</',nodeName,'>');
}else{
buf.push('/>');
}
// remove added visible namespaces
//visibleNamespaces.length = startVisibleNamespaces;
return;
case DOCUMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
var child = node.firstChild;
while(child){
serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
child = child.nextSibling;
}
return;
case ATTRIBUTE_NODE:
return buf.push(' ',node.name,'="',node.value.replace(/[&"]/g,_xmlEncoder),'"');
case TEXT_NODE:
/**
* The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
* except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
* If they are needed elsewhere, they must be escaped using either numeric character references or the strings
* `&` and `<` respectively.
* The right angle bracket (>) may be represented using the string " > ", and must, for compatibility,
* be escaped using either `>` or a character reference when it appears in the string `]]>` in content,
* when that string is not marking the end of a CDATA section.
*
* In the content of elements, character data is any string of characters
* which does not contain the start-delimiter of any markup
* and does not include the CDATA-section-close delimiter, `]]>`.
*
* @see https://www.w3.org/TR/xml/#NT-CharData
*/
return buf.push(node.data
.replace(/[<&]/g,_xmlEncoder)
.replace(/]]>/g, ']]>')
);
case CDATA_SECTION_NODE:
return buf.push( '<![CDATA[',node.data,']]>');
case COMMENT_NODE:
return buf.push( "<!--",node.data,"-->");
case DOCUMENT_TYPE_NODE:
var pubid = node.publicId;
var sysid = node.systemId;
buf.push('<!DOCTYPE ',node.name);
if(pubid){
buf.push(' PUBLIC ', pubid);
if (sysid && sysid!='.') {
buf.push(' ', sysid);
}
buf.push('>');
}else if(sysid && sysid!='.'){
buf.push(' SYSTEM ', sysid, '>');
}else{
var sub = node.internalSubset;
if(sub){
buf.push(" [",sub,"]");
}
buf.push(">");
}
return;
case PROCESSING_INSTRUCTION_NODE:
return buf.push( "<?",node.target," ",node.data,"?>");
case ENTITY_REFERENCE_NODE:
return buf.push( '&',node.nodeName,';');
//case ENTITY_NODE:
//case NOTATION_NODE:
default:
buf.push('??',node.nodeName);
}
}
function importNode(doc,node,deep){
var node2;
switch (node.nodeType) {
case ELEMENT_NODE:
node2 = node.cloneNode(false);
node2.ownerDocument = doc;
//var attrs = node2.attributes;
//var len = attrs.length;
//for(var i=0;i<len;i++){
//node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
//}
case DOCUMENT_FRAGMENT_NODE:
break;
case ATTRIBUTE_NODE:
deep = true;
break;
//case ENTITY_REFERENCE_NODE:
//case PROCESSING_INSTRUCTION_NODE:
////case TEXT_NODE:
//case CDATA_SECTION_NODE:
//case COMMENT_NODE:
// deep = false;
// break;
//case DOCUMENT_NODE:
//case DOCUMENT_TYPE_NODE:
//cannot be imported.
//case ENTITY_NODE:
//case NOTATION_NODE:
//can not hit in level3
//default:throw e;
}
if(!node2){
node2 = node.cloneNode(false);//false
}
node2.ownerDocument = doc;
node2.parentNode = null;
if(deep){
var child = node.firstChild;
while(child){
node2.appendChild(importNode(doc,child,deep));
child = child.nextSibling;
}
}
return node2;
}
//
//var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
// attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
function cloneNode(doc,node,deep){
var node2 = new node.constructor();
for(var n in node){
var v = node[n];
if(typeof v != 'object' ){
if(v != node2[n]){
node2[n] = v;
}
}
}
if(node.childNodes){
node2.childNodes = new NodeList();
}
node2.ownerDocument = doc;
switch (node2.nodeType) {
case ELEMENT_NODE:
var attrs = node.attributes;
var attrs2 = node2.attributes = new NamedNodeMap();
var len = attrs.length
attrs2._ownerElement = node2;
for(var i=0;i<len;i++){
node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
}
break;;
case ATTRIBUTE_NODE:
deep = true;
}
if(deep){
var child = node.firstChild;
while(child){
node2.appendChild(cloneNode(doc,child,deep));
child = child.nextSibling;
}
}
return node2;
}
function __set__(object,key,value){
object[key] = value
}
//do dynamic
try{
if(Object.defineProperty){
Object.defineProperty(LiveNodeList.prototype,'length',{
get:function(){
_updateLiveList(this);
return this.$$length;
}
});
Object.defineProperty(Node.prototype,'textContent',{
get:function(){
return getTextContent(this);
},
set:function(data){
switch(this.nodeType){
case ELEMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
while(this.firstChild){
this.removeChild(this.firstChild);
}
if(data || String(data)){
this.appendChild(this.ownerDocument.createTextNode(data));
}
break;
default:
//TODO:
this.data = data;
this.value = data;
this.nodeValue = data;
}
}
})
function getTextContent(node){
switch(node.nodeType){
case ELEMENT_NODE:
case DOCUMENT_FRAGMENT_NODE:
var buf = [];
node = node.firstChild;
while(node){
if(node.nodeType!==7 && node.nodeType !==8){
buf.push(getTextContent(node));
}
node = node.nextSibling;
}
return buf.join('');
default:
return node.nodeValue;
}
}
__set__ = function(object,key,value){
//console.log(value)
object['$$'+key] = value
}
}
}catch(e){//ie8
}
//if(typeof require == 'function'){
exports.Node = Node;
exports.DOMException = DOMException;
exports.DOMImplementation = DOMImplementation;
exports.XMLSerializer = XMLSerializer;
//}
},{}],86:[function(require,module,exports){
exports.entityMap = {
lt: '<',
gt: '>',
amp: '&',
quot: '"',
apos: "'",
Agrave: "À",
Aacute: "Á",
Acirc: "Â",
Atilde: "Ã",
Auml: "Ä",
Aring: "Å",
AElig: "Æ",
Ccedil: "Ç",
Egrave: "È",
Eacute: "É",
Ecirc: "Ê",
Euml: "Ë",
Igrave: "Ì",
Iacute: "Í",
Icirc: "Î",
Iuml: "Ï",
ETH: "Ð",
Ntilde: "Ñ",
Ograve: "Ò",
Oacute: "Ó",
Ocirc: "Ô",
Otilde: "Õ",
Ouml: "Ö",
Oslash: "Ø",
Ugrave: "Ù",
Uacute: "Ú",
Ucirc: "Û",
Uuml: "Ü",
Yacute: "Ý",
THORN: "Þ",
szlig: "ß",
agrave: "à",
aacute: "á",
acirc: "â",
atilde: "ã",
auml: "ä",
aring: "å",
aelig: "æ",
ccedil: "ç",
egrave: "è",
eacute: "é",
ecirc: "ê",
euml: "ë",
igrave: "ì",
iacute: "í",
icirc: "î",
iuml: "ï",
eth: "ð",
ntilde: "ñ",
ograve: "ò",
oacute: "ó",
ocirc: "ô",
otilde: "õ",
ouml: "ö",
oslash: "ø",
ugrave: "ù",
uacute: "ú",
ucirc: "û",
uuml: "ü",
yacute: "ý",
thorn: "þ",
yuml: "ÿ",
nbsp: "\u00a0",
iexcl: "¡",
cent: "¢",
pound: "£",
curren: "¤",
yen: "¥",
brvbar: "¦",
sect: "§",
uml: "¨",
copy: "©",
ordf: "ª",
laquo: "«",
not: "¬",
shy: "",
reg: "®",
macr: "¯",
deg: "°",
plusmn: "±",
sup2: "²",
sup3: "³",
acute: "´",
micro: "µ",
para: "¶",
middot: "·",
cedil: "¸",
sup1: "¹",
ordm: "º",
raquo: "»",
frac14: "¼",
frac12: "½",
frac34: "¾",
iquest: "¿",
times: "×",
divide: "÷",
forall: "∀",
part: "∂",
exist: "∃",
empty: "∅",
nabla: "∇",
isin: "∈",
notin: "∉",
ni: "∋",
prod: "∏",
sum: "∑",
minus: "−",
lowast: "∗",
radic: "√",
prop: "∝",
infin: "∞",
ang: "∠",
and: "∧",
or: "∨",
cap: "∩",
cup: "∪",
'int': "∫",
there4: "∴",
sim: "∼",
cong: "≅",
asymp: "≈",
ne: "≠",
equiv: "≡",
le: "≤",
ge: "≥",
sub: "⊂",
sup: "⊃",
nsub: "⊄",
sube: "⊆",
supe: "⊇",
oplus: "⊕",
otimes: "⊗",
perp: "⊥",
sdot: "⋅",
Alpha: "Α",
Beta: "Β",
Gamma: "Γ",
Delta: "Δ",
Epsilon: "Ε",
Zeta: "Ζ",
Eta: "Η",
Theta: "Θ",
Iota: "Ι",
Kappa: "Κ",
Lambda: "Λ",
Mu: "Μ",
Nu: "Ν",
Xi: "Ξ",
Omicron: "Ο",
Pi: "Π",
Rho: "Ρ",
Sigma: "Σ",
Tau: "Τ",
Upsilon: "Υ",
Phi: "Φ",
Chi: "Χ",
Psi: "Ψ",
Omega: "Ω",
alpha: "α",
beta: "β",
gamma: "γ",
delta: "δ",
epsilon: "ε",
zeta: "ζ",
eta: "η",
theta: "θ",
iota: "ι",
kappa: "κ",
lambda: "λ",
mu: "μ",
nu: "ν",
xi: "ξ",
omicron: "ο",
pi: "π",
rho: "ρ",
sigmaf: "ς",
sigma: "σ",
tau: "τ",
upsilon: "υ",
phi: "φ",
chi: "χ",
psi: "ψ",
omega: "ω",
thetasym: "ϑ",
upsih: "ϒ",
piv: "ϖ",
OElig: "Œ",
oelig: "œ",
Scaron: "Š",
scaron: "š",
Yuml: "Ÿ",
fnof: "ƒ",
circ: "ˆ",
tilde: "˜",
ensp: " ",
emsp: " ",
thinsp: " ",
zwnj: "",
zwj: "",
lrm: "",
rlm: "",
ndash: "–",
mdash: "—",
lsquo: "‘",
rsquo: "’",
sbquo: "‚",
ldquo: "“",
rdquo: "”",
bdquo: "„",
dagger: "†",
Dagger: "‡",
bull: "•",
hellip: "…",
permil: "‰",
prime: "′",
Prime: "″",
lsaquo: "‹",
rsaquo: "›",
oline: "‾",
euro: "€",
trade: "™",
larr: "←",
uarr: "↑",
rarr: "→",
darr: "↓",
harr: "↔",
crarr: "↵",
lceil: "⌈",
rceil: "⌉",
lfloor: "⌊",
rfloor: "⌋",
loz: "◊",
spades: "♠",
clubs: "♣",
hearts: "♥",
diams: "♦"
};
},{}],87:[function(require,module,exports){
//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
//[5] Name ::= NameStartChar (NameChar)*
var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
var S_TAG = 0;//tag name offerring
var S_ATTR = 1;//attr name offerring
var S_ATTR_SPACE=2;//attr name end and space offer
var S_EQ = 3;//=space?
var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
var S_ATTR_END = 5;//attr value end and no space(quot end)
var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
var S_TAG_CLOSE = 7;//closed el<el />
/**
* Creates an error that will not be caught by XMLReader aka the SAX parser.
*
* @param {string} message
* @param {any?} locator Optional, can provide details about the location in the source
* @constructor
*/
function ParseError(message, locator) {
this.message = message
this.locator = locator
if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
}
ParseError.prototype = new Error();
ParseError.prototype.name = ParseError.name
function XMLReader(){
}
XMLReader.prototype = {
parse:function(source,defaultNSMap,entityMap){
var domBuilder = this.domBuilder;
domBuilder.startDocument();
_copy(defaultNSMap ,defaultNSMap = {})
parse(source,defaultNSMap,entityMap,
domBuilder,this.errorHandler);
domBuilder.endDocument();
}
}
function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
function fixedFromCharCode(code) {
// String.prototype.fromCharCode does not supports
// > 2 bytes unicode chars directly
if (code > 0xffff) {
code -= 0x10000;
var surrogate1 = 0xd800 + (code >> 10)
, surrogate2 = 0xdc00 + (code & 0x3ff);
return String.fromCharCode(surrogate1, surrogate2);
} else {
return String.fromCharCode(code);
}
}
function entityReplacer(a){
var k = a.slice(1,-1);
if(k in entityMap){
return entityMap[k];
}else if(k.charAt(0) === '#'){
return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
}else{
errorHandler.error('entity not found:'+a);
return a;
}
}
function appendText(end){//has some bugs
if(end>start){
var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
locator&&position(start);
domBuilder.characters(xt,0,end-start);
start = end
}
}
function position(p,m){
while(p>=lineEnd && (m = linePattern.exec(source))){
lineStart = m.index;
lineEnd = lineStart + m[0].length;
locator.lineNumber++;
//console.log('line++:',locator,startPos,endPos)
}
locator.columnNumber = p-lineStart+1;
}
var lineStart = 0;
var lineEnd = 0;
var linePattern = /.*(?:\r\n?|\n)|.*$/g
var locator = domBuilder.locator;
var parseStack = [{currentNSMap:defaultNSMapCopy}]
var closeMap = {};
var start = 0;
while(true){
try{
var tagStart = source.indexOf('<',start);
if(tagStart<0){
if(!source.substr(start).match(/^\s*$/)){
var doc = domBuilder.doc;
var text = doc.createTextNode(source.substr(start));
doc.appendChild(text);
domBuilder.currentElement = text;
}
return;
}
if(tagStart>start){
appendText(tagStart);
}
switch(source.charAt(tagStart+1)){
case '/':
var end = source.indexOf('>',tagStart+3);
var tagName = source.substring(tagStart+2,end);
var config = parseStack.pop();
if(end<0){
tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
//console.error('#@@@@@@'+tagName)
errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
end = tagStart+1+tagName.length;
}else if(tagName.match(/\s</)){
tagName = tagName.replace(/[\s<].*/,'');
errorHandler.error("end tag name: "+tagName+' maybe not complete');
end = tagStart+1+tagName.length;
}
//console.error(parseStack.length,parseStack)
//console.error(config);
var localNSMap = config.localNSMap;
var endMatch = config.tagName == tagName;
var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
if(endIgnoreCaseMach){
domBuilder.endElement(config.uri,config.localName,tagName);
if(localNSMap){
for(var prefix in localNSMap){
domBuilder.endPrefixMapping(prefix) ;
}
}
if(!endMatch){
errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
}
}else{
parseStack.push(config)
}
end++;
break;
// end elment
case '?':// <?...?>
locator&&position(tagStart);
end = parseInstruction(source,tagStart,domBuilder);
break;
case '!':// <!doctype,<![CDATA,<!--
locator&&position(tagStart);
end = parseDCC(source,tagStart,domBuilder,errorHandler);
break;
default:
locator&&position(tagStart);
var el = new ElementAttributes();
var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
//elStartEnd
var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
var len = el.length;
if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
el.closed = true;
if(!entityMap.nbsp){
errorHandler.warning('unclosed xml attribute');
}
}
if(locator && len){
var locator2 = copyLocator(locator,{});
//try{//attribute position fixed
for(var i = 0;i<len;i++){
var a = el[i];
position(a.offset);
a.locator = copyLocator(locator,{});
}
//}catch(e){console.error('@@@@@'+e)}
domBuilder.locator = locator2
if(appendElement(el,domBuilder,currentNSMap)){
parseStack.push(el)
}
domBuilder.locator = locator;
}else{
if(appendElement(el,domBuilder,currentNSMap)){
parseStack.push(el)
}
}
if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
}else{
end++;
}
}
}catch(e){
if (e instanceof ParseError) {
throw e;
}
errorHandler.error('element parse error: '+e)
end = -1;
}
if(end>start){
start = end;
}else{
//TODO: 这里有可能sax回退,有位置错误风险
appendText(Math.max(tagStart,start)+1);
}
}
}
function copyLocator(f,t){
t.lineNumber = f.lineNumber;
t.columnNumber = f.columnNumber;
return t;
}
/**
* @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
* @return end of the elementStartPart(end of elementEndPart for selfClosed el)
*/
function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
/**
* @param {string} qname
* @param {string} value
* @param {number} startIndex
*/
function addAttribute(qname, value, startIndex) {
if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
el.addValue(qname, value, startIndex)
}
var attrName;
var value;
var p = ++start;
var s = S_TAG;//status
while(true){
var c = source.charAt(p);
switch(c){
case '=':
if(s === S_ATTR){//attrName
attrName = source.slice(start,p);
s = S_EQ;
}else if(s === S_ATTR_SPACE){
s = S_EQ;
}else{
//fatalError: equal must after attrName or space after attrName
throw new Error('attribute equal must after attrName'); // No known test case
}
break;
case '\'':
case '"':
if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
){//equal
if(s === S_ATTR){
errorHandler.warning('attribute value must after "="')
attrName = source.slice(start,p)
}
start = p+1;
p = source.indexOf(c,start)
if(p>0){
value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
addAttribute(attrName, value, start-1);
s = S_ATTR_END;
}else{
//fatalError: no end quot match
throw new Error('attribute value no end \''+c+'\' match');
}
}else if(s == S_ATTR_NOQUOT_VALUE){
value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
//console.log(attrName,value,start,p)
addAttribute(attrName, value, start);
//console.dir(el)
errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
start = p+1;
s = S_ATTR_END
}else{
//fatalError: no equal before
throw new Error('attribute value must after "="'); // No known test case
}
break;
case '/':
switch(s){
case S_TAG:
el.setTagName(source.slice(start,p));
case S_ATTR_END:
case S_TAG_SPACE:
case S_TAG_CLOSE:
s =S_TAG_CLOSE;
el.closed = true;
case S_ATTR_NOQUOT_VALUE:
case S_ATTR:
case S_ATTR_SPACE:
break;
//case S_EQ:
default:
throw new Error("attribute invalid close char('/')") // No known test case
}
break;
case ''://end document
errorHandler.error('unexpected end of input');
if(s == S_TAG){
el.setTagName(source.slice(start,p));
}
return p;
case '>':
switch(s){
case S_TAG:
el.setTagName(source.slice(start,p));
case S_ATTR_END:
case S_TAG_SPACE:
case S_TAG_CLOSE:
break;//normal
case S_ATTR_NOQUOT_VALUE://Compatible state
case S_ATTR:
value = source.slice(start,p);
if(value.slice(-1) === '/'){
el.closed = true;
value = value.slice(0,-1)
}
case S_ATTR_SPACE:
if(s === S_ATTR_SPACE){
value = attrName;
}
if(s == S_ATTR_NOQUOT_VALUE){
errorHandler.warning('attribute "'+value+'" missed quot(")!');
addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start)
}else{
if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
}
addAttribute(value, value, start)
}
break;
case S_EQ:
throw new Error('attribute value missed!!');
}
// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
return p;
/*xml space '\x20' | #x9 | #xD | #xA; */
case '\u0080':
c = ' ';
default:
if(c<= ' '){//space
switch(s){
case S_TAG:
el.setTagName(source.slice(start,p));//tagName
s = S_TAG_SPACE;
break;
case S_ATTR:
attrName = source.slice(start,p)
s = S_ATTR_SPACE;
break;
case S_ATTR_NOQUOT_VALUE:
var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
errorHandler.warning('attribute "'+value+'" missed quot(")!!');
addAttribute(attrName, value, start)
case S_ATTR_END:
s = S_TAG_SPACE;
break;
//case S_TAG_SPACE:
//case S_EQ:
//case S_ATTR_SPACE:
// void();break;
//case S_TAG_CLOSE:
//ignore warning
}
}else{//not space
//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
switch(s){
//case S_TAG:void();break;
//case S_ATTR:void();break;
//case S_ATTR_NOQUOT_VALUE:void();break;
case S_ATTR_SPACE:
var tagName = el.tagName;
if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
}
addAttribute(attrName, attrName, start);
start = p;
s = S_ATTR;
break;
case S_ATTR_END:
errorHandler.warning('attribute space is required"'+attrName+'"!!')
case S_TAG_SPACE:
s = S_ATTR;
start = p;
break;
case S_EQ:
s = S_ATTR_NOQUOT_VALUE;
start = p;
break;
case S_TAG_CLOSE:
throw new Error("elements closed character '/' and '>' must be connected to");
}
}
}//end outer switch
//console.log('p++',p)
p++;
}
}
/**
* @return true if has new namespace define
*/
function appendElement(el,domBuilder,currentNSMap){
var tagName = el.tagName;
var localNSMap = null;
//var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
var i = el.length;
while(i--){
var a = el[i];
var qName = a.qName;
var value = a.value;
var nsp = qName.indexOf(':');
if(nsp>0){
var prefix = a.prefix = qName.slice(0,nsp);
var localName = qName.slice(nsp+1);
var nsPrefix = prefix === 'xmlns' && localName
}else{
localName = qName;
prefix = null
nsPrefix = qName === 'xmlns' && ''
}
//can not set prefix,because prefix !== ''
a.localName = localName ;
//prefix == null for no ns prefix attribute
if(nsPrefix !== false){//hack!!
if(localNSMap == null){
localNSMap = {}
//console.log(currentNSMap,0)
_copy(currentNSMap,currentNSMap={})
//console.log(currentNSMap,1)
}
currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
a.uri = 'http://www.w3.org/2000/xmlns/'
domBuilder.startPrefixMapping(nsPrefix, value)
}
}
var i = el.length;
while(i--){
a = el[i];
var prefix = a.prefix;
if(prefix){//no prefix attribute has no namespace
if(prefix === 'xml'){
a.uri = 'http://www.w3.org/XML/1998/namespace';
}if(prefix !== 'xmlns'){
a.uri = currentNSMap[prefix || '']
//{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
}
}
}
var nsp = tagName.indexOf(':');
if(nsp>0){
prefix = el.prefix = tagName.slice(0,nsp);
localName = el.localName = tagName.slice(nsp+1);
}else{
prefix = null;//important!!
localName = el.localName = tagName;
}
//no prefix element has default namespace
var ns = el.uri = currentNSMap[prefix || ''];
domBuilder.startElement(ns,localName,tagName,el);
//endPrefixMapping and startPrefixMapping have not any help for dom builder
//localNSMap = null
if(el.closed){
domBuilder.endElement(ns,localName,tagName);
if(localNSMap){
for(prefix in localNSMap){
domBuilder.endPrefixMapping(prefix)
}
}
}else{
el.currentNSMap = currentNSMap;
el.localNSMap = localNSMap;
//parseStack.push(el);
return true;
}
}
function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
if(/^(?:script|textarea)$/i.test(tagName)){
var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
var text = source.substring(elStartEnd+1,elEndStart);
if(/[&<]/.test(text)){
if(/^script$/i.test(tagName)){
//if(!/\]\]>/.test(text)){
//lexHandler.startCDATA();
domBuilder.characters(text,0,text.length);
//lexHandler.endCDATA();
return elEndStart;
//}
}//}else{//text area
text = text.replace(/&#?\w+;/g,entityReplacer);
domBuilder.characters(text,0,text.length);
return elEndStart;
//}
}
}
return elStartEnd+1;
}
function fixSelfClosed(source,elStartEnd,tagName,closeMap){
//if(tagName in closeMap){
var pos = closeMap[tagName];
if(pos == null){
//console.log(tagName)
pos = source.lastIndexOf('</'+tagName+'>')
if(pos<elStartEnd){//忘记闭合
pos = source.lastIndexOf('</'+tagName)
}
closeMap[tagName] =pos
}
return pos<elStartEnd;
//}
}
function _copy(source,target){
for(var n in source){target[n] = source[n]}
}
function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
var next= source.charAt(start+2)
switch(next){
case '-':
if(source.charAt(start + 3) === '-'){
var end = source.indexOf('-->',start+4);
//append comment source.substring(4,end)//<!--
if(end>start){
domBuilder.comment(source,start+4,end-start-4);
return end+3;
}else{
errorHandler.error("Unclosed comment");
return -1;
}
}else{
//error
return -1;
}
default:
if(source.substr(start+3,6) == 'CDATA['){
var end = source.indexOf(']]>',start+9);
domBuilder.startCDATA();
domBuilder.characters(source,start+9,end-start-9);
domBuilder.endCDATA()
return end+3;
}
//<!DOCTYPE
//startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
var matchs = split(source,start);
var len = matchs.length;
if(len>1 && /!doctype/i.test(matchs[0][0])){
var name = matchs[1][0];
var pubid = false;
var sysid = false;
if(len>3){
if(/^public$/i.test(matchs[2][0])){
pubid = matchs[3][0];
sysid = len>4 && matchs[4][0];
}else if(/^system$/i.test(matchs[2][0])){
sysid = matchs[3][0];
}
}
var lastMatch = matchs[len-1]
domBuilder.startDTD(name, pubid, sysid);
domBuilder.endDTD();
return lastMatch.index+lastMatch[0].length
}
}
return -1;
}
function parseInstruction(source,start,domBuilder){
var end = source.indexOf('?>',start);
if(end){
var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
if(match){
var len = match[0].length;
domBuilder.processingInstruction(match[1], match[2]) ;
return end+2;
}else{//error
return -1;
}
}
return -1;
}
function ElementAttributes(){
this.attributeNames = {}
}
ElementAttributes.prototype = {
setTagName:function(tagName){
if(!tagNamePattern.test(tagName)){
throw new Error('invalid tagName:'+tagName)
}
this.tagName = tagName
},
addValue:function(qName, value, offset) {
if(!tagNamePattern.test(qName)){
throw new Error('invalid attribute:'+qName)
}
this.attributeNames[qName] = this.length;
this[this.length++] = {qName:qName,value:value,offset:offset}
},
length:0,
getLocalName:function(i){return this[i].localName},
getLocator:function(i){return this[i].locator},
getQName:function(i){return this[i].qName},
getURI:function(i){return this[i].uri},
getValue:function(i){return this[i].value}
// ,getIndex:function(uri, localName)){
// if(localName){
//
// }else{
// var qName = uri
// }
// },
// getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
// getType:function(uri,localName){}
// getType:function(i){},
}
function split(source,start){
var match;
var buf = [];
var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
reg.lastIndex = start;
reg.exec(source);//skip <
while(match = reg.exec(source)){
buf.push(match);
if(match[1])return buf;
}
}
exports.XMLReader = XMLReader;
exports.ParseError = ParseError;
},{}],88:[function(require,module,exports){
/*
* xpath.js
*
* An XPath 1.0 library for JavaScript.
*
* Cameron McCormack <cam (at) mcc.id.au>
*
* This work is licensed under the Creative Commons Attribution-ShareAlike
* License. To view a copy of this license, visit
*
* http://creativecommons.org/licenses/by-sa/2.0/
*
* or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
* California 94305, USA.
*
* Revision 20: April 26, 2011
* Fixed a typo resulting in FIRST_ORDERED_NODE_TYPE results being wrong,
* thanks to <shi_a009 (at) hotmail.com>.
*
* Revision 19: November 29, 2005
* Nodesets now store their nodes in a height balanced tree, increasing
* performance for the common case of selecting nodes in document order,
* thanks to S閎astien Cramatte <contact (at) zeninteractif.com>.
* AVL tree code adapted from Raimund Neumann <rnova (at) gmx.net>.
*
* Revision 18: October 27, 2005
* DOM 3 XPath support. Caveats:
* - namespace prefixes aren't resolved in XPathEvaluator.createExpression,
* but in XPathExpression.evaluate.
* - XPathResult.invalidIteratorState is not implemented.
*
* Revision 17: October 25, 2005
* Some core XPath function fixes and a patch to avoid crashing certain
* versions of MSXML in PathExpr.prototype.getOwnerElement, thanks to
* S閎astien Cramatte <contact (at) zeninteractif.com>.
*
* Revision 16: September 22, 2005
* Workarounds for some IE 5.5 deficiencies.
* Fixed problem with prefix node tests on attribute nodes.
*
* Revision 15: May 21, 2005
* Fixed problem with QName node tests on elements with an xmlns="...".
*
* Revision 14: May 19, 2005
* Fixed QName node tests on attribute node regression.
*
* Revision 13: May 3, 2005
* Node tests are case insensitive now if working in an HTML DOM.
*
* Revision 12: April 26, 2005
* Updated licence. Slight code changes to enable use of Dean
* Edwards' script compression, http://dean.edwards.name/packer/ .
*
* Revision 11: April 23, 2005
* Fixed bug with 'and' and 'or' operators, fix thanks to
* Sandy McArthur <sandy (at) mcarthur.org>.
*
* Revision 10: April 15, 2005
* Added support for a virtual root node, supposedly helpful for
* implementing XForms. Fixed problem with QName node tests and
* the parent axis.
*
* Revision 9: March 17, 2005
* Namespace resolver tweaked so using the document node as the context
* for namespace lookups is equivalent to using the document element.
*
* Revision 8: February 13, 2005
* Handle implicit declaration of 'xmlns' namespace prefix.
* Fixed bug when comparing nodesets.
* Instance data can now be associated with a FunctionResolver, and
* workaround for MSXML not supporting 'localName' and 'getElementById',
* thanks to Grant Gongaware.
* Fix a few problems when the context node is the root node.
*
* Revision 7: February 11, 2005
* Default namespace resolver fix from Grant Gongaware
* <grant (at) gongaware.com>.
*
* Revision 6: February 10, 2005
* Fixed bug in 'number' function.
*
* Revision 5: February 9, 2005
* Fixed bug where text nodes not getting converted to string values.
*
* Revision 4: January 21, 2005
* Bug in 'name' function, fix thanks to Bill Edney.
* Fixed incorrect processing of namespace nodes.
* Fixed NamespaceResolver to resolve 'xml' namespace.
* Implemented union '|' operator.
*
* Revision 3: January 14, 2005
* Fixed bug with nodeset comparisons, bug lexing < and >.
*
* Revision 2: October 26, 2004
* QName node test namespace handling fixed. Few other bug fixes.
*
* Revision 1: August 13, 2004
* Bug fixes from William J. Edney <bedney (at) technicalpursuit.com>.
* Added minimal licence.
*
* Initial version: June 14, 2004
*/
// non-node wrapper
var xpath = (typeof exports === 'undefined') ? {} : exports;
(function(exports) {
"use strict";
// XPathParser ///////////////////////////////////////////////////////////////
XPathParser.prototype = new Object();
XPathParser.prototype.constructor = XPathParser;
XPathParser.superclass = Object.prototype;
function XPathParser() {
this.init();
}
XPathParser.prototype.init = function() {
this.reduceActions = [];
this.reduceActions[3] = function(rhs) {
return new OrOperation(rhs[0], rhs[2]);
};
this.reduceActions[5] = function(rhs) {
return new AndOperation(rhs[0], rhs[2]);
};
this.reduceActions[7] = function(rhs) {
return new EqualsOperation(rhs[0], rhs[2]);
};
this.reduceActions[8] = function(rhs) {
return new NotEqualOperation(rhs[0], rhs[2]);
};
this.reduceActions[10] = function(rhs) {
return new LessThanOperation(rhs[0], rhs[2]);
};
this.reduceActions[11] = function(rhs) {
return new GreaterThanOperation(rhs[0], rhs[2]);
};
this.reduceActions[12] = function(rhs) {
return new LessThanOrEqualOperation(rhs[0], rhs[2]);
};
this.reduceActions[13] = function(rhs) {
return new GreaterThanOrEqualOperation(rhs[0], rhs[2]);
};
this.reduceActions[15] = function(rhs) {
return new PlusOperation(rhs[0], rhs[2]);
};
this.reduceActions[16] = function(rhs) {
return new MinusOperation(rhs[0], rhs[2]);
};
this.reduceActions[18] = function(rhs) {
return new MultiplyOperation(rhs[0], rhs[2]);
};
this.reduceActions[19] = function(rhs) {
return new DivOperation(rhs[0], rhs[2]);
};
this.reduceActions[20] = function(rhs) {
return new ModOperation(rhs[0], rhs[2]);
};
this.reduceActions[22] = function(rhs) {
return new UnaryMinusOperation(rhs[1]);
};
this.reduceActions[24] = function(rhs) {
return new BarOperation(rhs[0], rhs[2]);
};
this.reduceActions[25] = function(rhs) {
return new PathExpr(undefined, undefined, rhs[0]);
};
this.reduceActions[27] = function(rhs) {
rhs[0].locationPath = rhs[2];
return rhs[0];
};
this.reduceActions[28] = function(rhs) {
rhs[0].locationPath = rhs[2];
rhs[0].locationPath.steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
return rhs[0];
};
this.reduceActions[29] = function(rhs) {
return new PathExpr(rhs[0], [], undefined);
};
this.reduceActions[30] = function(rhs) {
if (Utilities.instance_of(rhs[0], PathExpr)) {
if (rhs[0].filterPredicates == undefined) {
rhs[0].filterPredicates = [];
}
rhs[0].filterPredicates.push(rhs[1]);
return rhs[0];
} else {
return new PathExpr(rhs[0], [rhs[1]], undefined);
}
};
this.reduceActions[32] = function(rhs) {
return rhs[1];
};
this.reduceActions[33] = function(rhs) {
return new XString(rhs[0]);
};
this.reduceActions[34] = function(rhs) {
return new XNumber(rhs[0]);
};
this.reduceActions[36] = function(rhs) {
return new FunctionCall(rhs[0], []);
};
this.reduceActions[37] = function(rhs) {
return new FunctionCall(rhs[0], rhs[2]);
};
this.reduceActions[38] = function(rhs) {
return [ rhs[0] ];
};
this.reduceActions[39] = function(rhs) {
rhs[2].unshift(rhs[0]);
return rhs[2];
};
this.reduceActions[43] = function(rhs) {
return new LocationPath(true, []);
};
this.reduceActions[44] = function(rhs) {
rhs[1].absolute = true;
return rhs[1];
};
this.reduceActions[46] = function(rhs) {
return new LocationPath(false, [ rhs[0] ]);
};
this.reduceActions[47] = function(rhs) {
rhs[0].steps.push(rhs[2]);
return rhs[0];
};
this.reduceActions[49] = function(rhs) {
return new Step(rhs[0], rhs[1], []);
};
this.reduceActions[50] = function(rhs) {
return new Step(Step.CHILD, rhs[0], []);
};
this.reduceActions[51] = function(rhs) {
return new Step(rhs[0], rhs[1], rhs[2]);
};
this.reduceActions[52] = function(rhs) {
return new Step(Step.CHILD, rhs[0], rhs[1]);
};
this.reduceActions[54] = function(rhs) {
return [ rhs[0] ];
};
this.reduceActions[55] = function(rhs) {
rhs[1].unshift(rhs[0]);
return rhs[1];
};
this.reduceActions[56] = function(rhs) {
if (rhs[0] == "ancestor") {
return Step.ANCESTOR;
} else if (rhs[0] == "ancestor-or-self") {
return Step.ANCESTORORSELF;
} else if (rhs[0] == "attribute") {
return Step.ATTRIBUTE;
} else if (rhs[0] == "child") {
return Step.CHILD;
} else if (rhs[0] == "descendant") {
return Step.DESCENDANT;
} else if (rhs[0] == "descendant-or-self") {
return Step.DESCENDANTORSELF;
} else if (rhs[0] == "following") {
return Step.FOLLOWING;
} else if (rhs[0] == "following-sibling") {
return Step.FOLLOWINGSIBLING;
} else if (rhs[0] == "namespace") {
return Step.NAMESPACE;
} else if (rhs[0] == "parent") {
return Step.PARENT;
} else if (rhs[0] == "preceding") {
return Step.PRECEDING;
} else if (rhs[0] == "preceding-sibling") {
return Step.PRECEDINGSIBLING;
} else if (rhs[0] == "self") {
return Step.SELF;
}
return -1;
};
this.reduceActions[57] = function(rhs) {
return Step.ATTRIBUTE;
};
this.reduceActions[59] = function(rhs) {
if (rhs[0] == "comment") {
return new NodeTest(NodeTest.COMMENT, undefined);
} else if (rhs[0] == "text") {
return new NodeTest(NodeTest.TEXT, undefined);
} else if (rhs[0] == "processing-instruction") {
return new NodeTest(NodeTest.PI, undefined);
} else if (rhs[0] == "node") {
return new NodeTest(NodeTest.NODE, undefined);
}
return new NodeTest(-1, undefined);
};
this.reduceActions[60] = function(rhs) {
return new NodeTest(NodeTest.PI, rhs[2]);
};
this.reduceActions[61] = function(rhs) {
return rhs[1];
};
this.reduceActions[63] = function(rhs) {
rhs[1].absolute = true;
rhs[1].steps.unshift(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
return rhs[1];
};
this.reduceActions[64] = function(rhs) {
rhs[0].steps.push(new Step(Step.DESCENDANTORSELF, new NodeTest(NodeTest.NODE, undefined), []));
rhs[0].steps.push(rhs[2]);
return rhs[0];
};
this.reduceActions[65] = function(rhs) {
return new Step(Step.SELF, new NodeTest(NodeTest.NODE, undefined), []);
};
this.reduceActions[66] = function(rhs) {
return new Step(Step.PARENT, new NodeTest(NodeTest.NODE, undefined), []);
};
this.reduceActions[67] = function(rhs) {
return new VariableReference(rhs[1]);
};
this.reduceActions[68] = function(rhs) {
return new NodeTest(NodeTest.NAMETESTANY, undefined);
};
this.reduceActions[69] = function(rhs) {
var prefix = rhs[0].substring(0, rhs[0].indexOf(":"));
return new NodeTest(NodeTest.NAMETESTPREFIXANY, prefix);
};
this.reduceActions[70] = function(rhs) {
return new NodeTest(NodeTest.NAMETESTQNAME, rhs[0]);
};
};
XPathParser.actionTable = [
" s s sssssssss s ss s ss",
" s ",
"r rrrrrrrrr rrrrrrr rr r ",
" rrrrr ",
" s s sssssssss s ss s ss",
"rs rrrrrrrr s sssssrrrrrr rrs rs ",
" s s sssssssss s ss s ss",
" s ",
" s ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
" s ",
" s ",
" s s sssss s s ",
"r rrrrrrrrr rrrrrrr rr r ",
"a ",
"r s rr r ",
"r sr rr r ",
"r s rr s rr r ",
"r rssrr rss rr r ",
"r rrrrr rrrss rr r ",
"r rrrrrsss rrrrr rr r ",
"r rrrrrrrr rrrrr rr r ",
"r rrrrrrrr rrrrrs rr r ",
"r rrrrrrrr rrrrrr rr r ",
"r rrrrrrrr rrrrrr rr r ",
"r srrrrrrrr rrrrrrs rr sr ",
"r srrrrrrrr rrrrrrs rr r ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrr rrrrrr rr r ",
"r rrrrrrrr rrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
" sssss ",
"r rrrrrrrrr rrrrrrr rr sr ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
" s ",
"r srrrrrrrr rrrrrrs rr r ",
"r rrrrrrrr rrrrr rr r ",
" s ",
" s ",
" rrrrr ",
" s s sssssssss s sss s ss",
"r srrrrrrrr rrrrrrs rr r ",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss s ss s ss",
" s s sssssssss ss s ss",
" s s sssssssss s ss s ss",
" s s sssss s s ",
" s s sssss s s ",
"r rrrrrrrrr rrrrrrr rr rr ",
" s s sssss s s ",
" s s sssss s s ",
"r rrrrrrrrr rrrrrrr rr sr ",
"r rrrrrrrrr rrrrrrr rr sr ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr rr ",
" s ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
" rr ",
" s ",
" rs ",
"r sr rr r ",
"r s rr s rr r ",
"r rssrr rss rr r ",
"r rssrr rss rr r ",
"r rrrrr rrrss rr r ",
"r rrrrr rrrss rr r ",
"r rrrrr rrrss rr r ",
"r rrrrr rrrss rr r ",
"r rrrrrsss rrrrr rr r ",
"r rrrrrsss rrrrr rr r ",
"r rrrrrrrr rrrrr rr r ",
"r rrrrrrrr rrrrr rr r ",
"r rrrrrrrr rrrrr rr r ",
"r rrrrrrrr rrrrrr rr r ",
" r ",
" s ",
"r srrrrrrrr rrrrrrs rr r ",
"r srrrrrrrr rrrrrrs rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr r ",
"r rrrrrrrrr rrrrrrr rr rr ",
"r rrrrrrrrr rrrrrrr rr rr ",
" s s sssssssss s ss s ss",
"r rrrrrrrrr rrrrrrr rr rr ",
" r "
];
XPathParser.actionTableNumber = [
" 1 0 /.-,+*)(' & %$ # \"!",
" J ",
"a aaaaaaaaa aaaaaaa aa a ",
" YYYYY ",
" 1 0 /.-,+*)(' & %$ # \"!",
"K1 KKKKKKKK . +*)('KKKKKK KK# K\" ",
" 1 0 /.-,+*)(' & %$ # \"!",
" N ",
" O ",
"e eeeeeeeee eeeeeee ee ee ",
"f fffffffff fffffff ff ff ",
"d ddddddddd ddddddd dd dd ",
"B BBBBBBBBB BBBBBBB BB BB ",
"A AAAAAAAAA AAAAAAA AA AA ",
" P ",
" Q ",
" 1 . +*)(' # \" ",
"b bbbbbbbbb bbbbbbb bb b ",
" ",
"! S !! ! ",
"\" T\" \"\" \" ",
"$ V $$ U $$ $ ",
"& &ZY&& &XW && & ",
") ))))) )))\\[ )) ) ",
". ....._^] ..... .. . ",
"1 11111111 11111 11 1 ",
"5 55555555 55555` 55 5 ",
"7 77777777 777777 77 7 ",
"9 99999999 999999 99 9 ",
": c:::::::: ::::::b :: a: ",
"I fIIIIIIII IIIIIIe II I ",
"= ========= ======= == == ",
"? ????????? ??????? ?? ?? ",
"C CCCCCCCCC CCCCCCC CC CC ",
"J JJJJJJJJ JJJJJJ JJ J ",
"M MMMMMMMM MMMMMM MM M ",
"N NNNNNNNNN NNNNNNN NN N ",
"P PPPPPPPPP PPPPPPP PP P ",
" +*)(' ",
"R RRRRRRRRR RRRRRRR RR aR ",
"U UUUUUUUUU UUUUUUU UU U ",
"Z ZZZZZZZZZ ZZZZZZZ ZZ ZZ ",
"c ccccccccc ccccccc cc cc ",
" j ",
"L fLLLLLLLL LLLLLLe LL L ",
"6 66666666 66666 66 6 ",
" k ",
" l ",
" XXXXX ",
" 1 0 /.-,+*)(' & %$m # \"!",
"_ f________ ______e __ _ ",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 0 /.-,+*)(' %$ # \"!",
" 1 0 /.-,+*)(' & %$ # \"!",
" 1 . +*)(' # \" ",
" 1 . +*)(' # \" ",
"> >>>>>>>>> >>>>>>> >> >> ",
" 1 . +*)(' # \" ",
" 1 . +*)(' # \" ",
"Q QQQQQQQQQ QQQQQQQ QQ aQ ",
"V VVVVVVVVV VVVVVVV VV aV ",
"T TTTTTTTTT TTTTTTT TT T ",
"@ @@@@@@@@@ @@@@@@@ @@ @@ ",
" \x87 ",
"[ [[[[[[[[[ [[[[[[[ [[ [[ ",
"D DDDDDDDDD DDDDDDD DD DD ",
" HH ",
" \x88 ",
" F\x89 ",
"# T# ## # ",
"% V %% U %% % ",
"' 'ZY'' 'XW '' ' ",
"( (ZY(( (XW (( ( ",
"+ +++++ +++\\[ ++ + ",
"* ***** ***\\[ ** * ",
"- ----- ---\\[ -- - ",
", ,,,,, ,,,\\[ ,, , ",
"0 00000_^] 00000 00 0 ",
"/ /////_^] ///// // / ",
"2 22222222 22222 22 2 ",
"3 33333333 33333 33 3 ",
"4 44444444 44444 44 4 ",
"8 88888888 888888 88 8 ",
" ^ ",
" \x8a ",
"; f;;;;;;;; ;;;;;;e ;; ; ",
"< f<<<<<<<< <<<<<<e << < ",
"O OOOOOOOOO OOOOOOO OO O ",
"` ````````` ``````` `` ` ",
"S SSSSSSSSS SSSSSSS SS S ",
"W WWWWWWWWW WWWWWWW WW W ",
"\\ \\\\\\\\\\\\\\\\\\ \\\\\\\\\\\\\\ \\\\ \\\\ ",
"E EEEEEEEEE EEEEEEE EE EE ",
" 1 0 /.-,+*)(' & %$ # \"!",
"] ]]]]]]]]] ]]]]]]] ]] ]] ",
" G "
];
XPathParser.gotoTable = [
"3456789:;<=>?@ AB CDEFGH IJ ",
" ",
" ",
" ",
"L456789:;<=>?@ AB CDEFGH IJ ",
" M EFGH IJ ",
" N;<=>?@ AB CDEFGH IJ ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" S EFGH IJ ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" e ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" h J ",
" i j ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"o456789:;<=>?@ ABpqCDEFGH IJ ",
" ",
" r6789:;<=>?@ AB CDEFGH IJ ",
" s789:;<=>?@ AB CDEFGH IJ ",
" t89:;<=>?@ AB CDEFGH IJ ",
" u89:;<=>?@ AB CDEFGH IJ ",
" v9:;<=>?@ AB CDEFGH IJ ",
" w9:;<=>?@ AB CDEFGH IJ ",
" x9:;<=>?@ AB CDEFGH IJ ",
" y9:;<=>?@ AB CDEFGH IJ ",
" z:;<=>?@ AB CDEFGH IJ ",
" {:;<=>?@ AB CDEFGH IJ ",
" |;<=>?@ AB CDEFGH IJ ",
" };<=>?@ AB CDEFGH IJ ",
" ~;<=>?@ AB CDEFGH IJ ",
" \x7f=>?@ AB CDEFGH IJ ",
"\x80456789:;<=>?@ AB CDEFGH IJ\x81",
" \x82 EFGH IJ ",
" \x83 EFGH IJ ",
" ",
" \x84 GH IJ ",
" \x85 GH IJ ",
" i \x86 ",
" i \x87 ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
"o456789:;<=>?@ AB\x8cqCDEFGH IJ ",
" ",
" "
];
XPathParser.productions = [
[1, 1, 2],
[2, 1, 3],
[3, 1, 4],
[3, 3, 3, -9, 4],
[4, 1, 5],
[4, 3, 4, -8, 5],
[5, 1, 6],
[5, 3, 5, -22, 6],
[5, 3, 5, -5, 6],
[6, 1, 7],
[6, 3, 6, -23, 7],
[6, 3, 6, -24, 7],
[6, 3, 6, -6, 7],
[6, 3, 6, -7, 7],
[7, 1, 8],
[7, 3, 7, -25, 8],
[7, 3, 7, -26, 8],
[8, 1, 9],
[8, 3, 8, -12, 9],
[8, 3, 8, -11, 9],
[8, 3, 8, -10, 9],
[9, 1, 10],
[9, 2, -26, 9],
[10, 1, 11],
[10, 3, 10, -27, 11],
[11, 1, 12],
[11, 1, 13],
[11, 3, 13, -28, 14],
[11, 3, 13, -4, 14],
[13, 1, 15],
[13, 2, 13, 16],
[15, 1, 17],
[15, 3, -29, 2, -30],
[15, 1, -15],
[15, 1, -16],
[15, 1, 18],
[18, 3, -13, -29, -30],
[18, 4, -13, -29, 19, -30],
[19, 1, 20],
[19, 3, 20, -31, 19],
[20, 1, 2],
[12, 1, 14],
[12, 1, 21],
[21, 1, -28],
[21, 2, -28, 14],
[21, 1, 22],
[14, 1, 23],
[14, 3, 14, -28, 23],
[14, 1, 24],
[23, 2, 25, 26],
[23, 1, 26],
[23, 3, 25, 26, 27],
[23, 2, 26, 27],
[23, 1, 28],
[27, 1, 16],
[27, 2, 16, 27],
[25, 2, -14, -3],
[25, 1, -32],
[26, 1, 29],
[26, 3, -20, -29, -30],
[26, 4, -21, -29, -15, -30],
[16, 3, -33, 30, -34],
[30, 1, 2],
[22, 2, -4, 14],
[24, 3, 14, -4, 23],
[28, 1, -35],
[28, 1, -2],
[17, 2, -36, -18],
[29, 1, -17],
[29, 1, -19],
[29, 1, -18]
];
XPathParser.DOUBLEDOT = 2;
XPathParser.DOUBLECOLON = 3;
XPathParser.DOUBLESLASH = 4;
XPathParser.NOTEQUAL = 5;
XPathParser.LESSTHANOREQUAL = 6;
XPathParser.GREATERTHANOREQUAL = 7;
XPathParser.AND = 8;
XPathParser.OR = 9;
XPathParser.MOD = 10;
XPathParser.DIV = 11;
XPathParser.MULTIPLYOPERATOR = 12;
XPathParser.FUNCTIONNAME = 13;
XPathParser.AXISNAME = 14;
XPathParser.LITERAL = 15;
XPathParser.NUMBER = 16;
XPathParser.ASTERISKNAMETEST = 17;
XPathParser.QNAME = 18;
XPathParser.NCNAMECOLONASTERISK = 19;
XPathParser.NODETYPE = 20;
XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL = 21;
XPathParser.EQUALS = 22;
XPathParser.LESSTHAN = 23;
XPathParser.GREATERTHAN = 24;
XPathParser.PLUS = 25;
XPathParser.MINUS = 26;
XPathParser.BAR = 27;
XPathParser.SLASH = 28;
XPathParser.LEFTPARENTHESIS = 29;
XPathParser.RIGHTPARENTHESIS = 30;
XPathParser.COMMA = 31;
XPathParser.AT = 32;
XPathParser.LEFTBRACKET = 33;
XPathParser.RIGHTBRACKET = 34;
XPathParser.DOT = 35;
XPathParser.DOLLAR = 36;
XPathParser.prototype.tokenize = function(s1) {
var types = [];
var values = [];
var s = s1 + '\0';
var pos = 0;
var c = s.charAt(pos++);
while (1) {
while (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
c = s.charAt(pos++);
}
if (c == '\0' || pos >= s.length) {
break;
}
if (c == '(') {
types.push(XPathParser.LEFTPARENTHESIS);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == ')') {
types.push(XPathParser.RIGHTPARENTHESIS);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '[') {
types.push(XPathParser.LEFTBRACKET);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == ']') {
types.push(XPathParser.RIGHTBRACKET);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '@') {
types.push(XPathParser.AT);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == ',') {
types.push(XPathParser.COMMA);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '|') {
types.push(XPathParser.BAR);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '+') {
types.push(XPathParser.PLUS);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '-') {
types.push(XPathParser.MINUS);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '=') {
types.push(XPathParser.EQUALS);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '$') {
types.push(XPathParser.DOLLAR);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == '.') {
c = s.charAt(pos++);
if (c == '.') {
types.push(XPathParser.DOUBLEDOT);
values.push("..");
c = s.charAt(pos++);
continue;
}
if (c >= '0' && c <= '9') {
var number = "." + c;
c = s.charAt(pos++);
while (c >= '0' && c <= '9') {
number += c;
c = s.charAt(pos++);
}
types.push(XPathParser.NUMBER);
values.push(number);
continue;
}
types.push(XPathParser.DOT);
values.push('.');
continue;
}
if (c == '\'' || c == '"') {
var delimiter = c;
var literal = "";
while (pos < s.length && (c = s.charAt(pos)) !== delimiter) {
literal += c;
pos += 1;
}
if (c !== delimiter) {
throw XPathException.fromMessage("Unterminated string literal: " + delimiter + literal);
}
pos += 1;
types.push(XPathParser.LITERAL);
values.push(literal);
c = s.charAt(pos++);
continue;
}
if (c >= '0' && c <= '9') {
var number = c;
c = s.charAt(pos++);
while (c >= '0' && c <= '9') {
number += c;
c = s.charAt(pos++);
}
if (c == '.') {
if (s.charAt(pos) >= '0' && s.charAt(pos) <= '9') {
number += c;
number += s.charAt(pos++);
c = s.charAt(pos++);
while (c >= '0' && c <= '9') {
number += c;
c = s.charAt(pos++);
}
}
}
types.push(XPathParser.NUMBER);
values.push(number);
continue;
}
if (c == '*') {
if (types.length > 0) {
var last = types[types.length - 1];
if (last != XPathParser.AT
&& last != XPathParser.DOUBLECOLON
&& last != XPathParser.LEFTPARENTHESIS
&& last != XPathParser.LEFTBRACKET
&& last != XPathParser.AND
&& last != XPathParser.OR
&& last != XPathParser.MOD
&& last != XPathParser.DIV
&& last != XPathParser.MULTIPLYOPERATOR
&& last != XPathParser.SLASH
&& last != XPathParser.DOUBLESLASH
&& last != XPathParser.BAR
&& last != XPathParser.PLUS
&& last != XPathParser.MINUS
&& last != XPathParser.EQUALS
&& last != XPathParser.NOTEQUAL
&& last != XPathParser.LESSTHAN
&& last != XPathParser.LESSTHANOREQUAL
&& last != XPathParser.GREATERTHAN
&& last != XPathParser.GREATERTHANOREQUAL) {
types.push(XPathParser.MULTIPLYOPERATOR);
values.push(c);
c = s.charAt(pos++);
continue;
}
}
types.push(XPathParser.ASTERISKNAMETEST);
values.push(c);
c = s.charAt(pos++);
continue;
}
if (c == ':') {
if (s.charAt(pos) == ':') {
types.push(XPathParser.DOUBLECOLON);
values.push("::");
pos++;
c = s.charAt(pos++);
continue;
}
}
if (c == '/') {
c = s.charAt(pos++);
if (c == '/') {
types.push(XPathParser.DOUBLESLASH);
values.push("//");
c = s.charAt(pos++);
continue;
}
types.push(XPathParser.SLASH);
values.push('/');
continue;
}
if (c == '!') {
if (s.charAt(pos) == '=') {
types.push(XPathParser.NOTEQUAL);
values.push("!=");
pos++;
c = s.charAt(pos++);
continue;
}
}
if (c == '<') {
if (s.charAt(pos) == '=') {
types.push(XPathParser.LESSTHANOREQUAL);
values.push("<=");
pos++;
c = s.charAt(pos++);
continue;
}
types.push(XPathParser.LESSTHAN);
values.push('<');
c = s.charAt(pos++);
continue;
}
if (c == '>') {
if (s.charAt(pos) == '=') {
types.push(XPathParser.GREATERTHANOREQUAL);
values.push(">=");
pos++;
c = s.charAt(pos++);
continue;
}
types.push(XPathParser.GREATERTHAN);
values.push('>');
c = s.charAt(pos++);
continue;
}
if (c == '_' || Utilities.isLetter(c.charCodeAt(0))) {
var name = c;
c = s.charAt(pos++);
while (Utilities.isNCNameChar(c.charCodeAt(0))) {
name += c;
c = s.charAt(pos++);
}
if (types.length > 0) {
var last = types[types.length - 1];
if (last != XPathParser.AT
&& last != XPathParser.DOUBLECOLON
&& last != XPathParser.LEFTPARENTHESIS
&& last != XPathParser.LEFTBRACKET
&& last != XPathParser.AND
&& last != XPathParser.OR
&& last != XPathParser.MOD
&& last != XPathParser.DIV
&& last != XPathParser.MULTIPLYOPERATOR
&& last != XPathParser.SLASH
&& last != XPathParser.DOUBLESLASH
&& last != XPathParser.BAR
&& last != XPathParser.PLUS
&& last != XPathParser.MINUS
&& last != XPathParser.EQUALS
&& last != XPathParser.NOTEQUAL
&& last != XPathParser.LESSTHAN
&& last != XPathParser.LESSTHANOREQUAL
&& last != XPathParser.GREATERTHAN
&& last != XPathParser.GREATERTHANOREQUAL) {
if (name == "and") {
types.push(XPathParser.AND);
values.push(name);
continue;
}
if (name == "or") {
types.push(XPathParser.OR);
values.push(name);
continue;
}
if (name == "mod") {
types.push(XPathParser.MOD);
values.push(name);
continue;
}
if (name == "div") {
types.push(XPathParser.DIV);
values.push(name);
continue;
}
}
}
if (c == ':') {
if (s.charAt(pos) == '*') {
types.push(XPathParser.NCNAMECOLONASTERISK);
values.push(name + ":*");
pos++;
c = s.charAt(pos++);
continue;
}
if (s.charAt(pos) == '_' || Utilities.isLetter(s.charCodeAt(pos))) {
name += ':';
c = s.charAt(pos++);
while (Utilities.isNCNameChar(c.charCodeAt(0))) {
name += c;
c = s.charAt(pos++);
}
if (c == '(') {
types.push(XPathParser.FUNCTIONNAME);
values.push(name);
continue;
}
types.push(XPathParser.QNAME);
values.push(name);
continue;
}
if (s.charAt(pos) == ':') {
types.push(XPathParser.AXISNAME);
values.push(name);
continue;
}
}
if (c == '(') {
if (name == "comment" || name == "text" || name == "node") {
types.push(XPathParser.NODETYPE);
values.push(name);
continue;
}
if (name == "processing-instruction") {
if (s.charAt(pos) == ')') {
types.push(XPathParser.NODETYPE);
} else {
types.push(XPathParser.PROCESSINGINSTRUCTIONWITHLITERAL);
}
values.push(name);
continue;
}
types.push(XPathParser.FUNCTIONNAME);
values.push(name);
continue;
}
types.push(XPathParser.QNAME);
values.push(name);
continue;
}
throw new Error("Unexpected character " + c);
}
types.push(1);
values.push("[EOF]");
return [types, values];
};
XPathParser.SHIFT = 's';
XPathParser.REDUCE = 'r';
XPathParser.ACCEPT = 'a';
XPathParser.prototype.parse = function(s) {
var types;
var values;
var res = this.tokenize(s);
if (res == undefined) {
return undefined;
}
types = res[0];
values = res[1];
var tokenPos = 0;
var state = [];
var tokenType = [];
var tokenValue = [];
var s;
var a;
var t;
state.push(0);
tokenType.push(1);
tokenValue.push("_S");
a = types[tokenPos];
t = values[tokenPos++];
while (1) {
s = state[state.length - 1];
switch (XPathParser.actionTable[s].charAt(a - 1)) {
case XPathParser.SHIFT:
tokenType.push(-a);
tokenValue.push(t);
state.push(XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32);
a = types[tokenPos];
t = values[tokenPos++];
break;
case XPathParser.REDUCE:
var num = XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][1];
var rhs = [];
for (var i = 0; i < num; i++) {
tokenType.pop();
rhs.unshift(tokenValue.pop());
state.pop();
}
var s_ = state[state.length - 1];
tokenType.push(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0]);
if (this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32] == undefined) {
tokenValue.push(rhs[0]);
} else {
tokenValue.push(this.reduceActions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32](rhs));
}
state.push(XPathParser.gotoTable[s_].charCodeAt(XPathParser.productions[XPathParser.actionTableNumber[s].charCodeAt(a - 1) - 32][0] - 2) - 33);
break;
case XPathParser.ACCEPT:
return new XPath(tokenValue.pop());
default:
throw new Error("XPath parse error");
}
}
};
// XPath /////////////////////////////////////////////////////////////////////
XPath.prototype = new Object();
XPath.prototype.constructor = XPath;
XPath.superclass = Object.prototype;
function XPath(e) {
this.expression = e;
}
XPath.prototype.toString = function() {
return this.expression.toString();
};
XPath.prototype.evaluate = function(c) {
c.contextNode = c.expressionContextNode;
c.contextSize = 1;
c.contextPosition = 1;
c.caseInsensitive = false;
if (c.contextNode != null) {
var doc = c.contextNode;
if (doc.nodeType != 9 /*Node.DOCUMENT_NODE*/) {
doc = doc.ownerDocument;
}
try {
c.caseInsensitive = doc.implementation.hasFeature("HTML", "2.0");
} catch (e) {
c.caseInsensitive = true;
}
}
return this.expression.evaluate(c);
};
XPath.XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace";
XPath.XMLNS_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";
// Expression ////////////////////////////////////////////////////////////////
Expression.prototype = new Object();
Expression.prototype.constructor = Expression;
Expression.superclass = Object.prototype;
function Expression() {
}
Expression.prototype.init = function() {
};
Expression.prototype.toString = function() {
return "<Expression>";
};
Expression.prototype.evaluate = function(c) {
throw new Error("Could not evaluate expression.");
};
// UnaryOperation ////////////////////////////////////////////////////////////
UnaryOperation.prototype = new Expression();
UnaryOperation.prototype.constructor = UnaryOperation;
UnaryOperation.superclass = Expression.prototype;
function UnaryOperation(rhs) {
if (arguments.length > 0) {
this.init(rhs);
}
}
UnaryOperation.prototype.init = function(rhs) {
this.rhs = rhs;
};
// UnaryMinusOperation ///////////////////////////////////////////////////////
UnaryMinusOperation.prototype = new UnaryOperation();
UnaryMinusOperation.prototype.constructor = UnaryMinusOperation;
UnaryMinusOperation.superclass = UnaryOperation.prototype;
function UnaryMinusOperation(rhs) {
if (arguments.length > 0) {
this.init(rhs);
}
}
UnaryMinusOperation.prototype.init = function(rhs) {
UnaryMinusOperation.superclass.init.call(this, rhs);
};
UnaryMinusOperation.prototype.evaluate = function(c) {
return this.rhs.evaluate(c).number().negate();
};
UnaryMinusOperation.prototype.toString = function() {
return "-" + this.rhs.toString();
};
// BinaryOperation ///////////////////////////////////////////////////////////
BinaryOperation.prototype = new Expression();
BinaryOperation.prototype.constructor = BinaryOperation;
BinaryOperation.superclass = Expression.prototype;
function BinaryOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
BinaryOperation.prototype.init = function(lhs, rhs) {
this.lhs = lhs;
this.rhs = rhs;
};
// OrOperation ///////////////////////////////////////////////////////////////
OrOperation.prototype = new BinaryOperation();
OrOperation.prototype.constructor = OrOperation;
OrOperation.superclass = BinaryOperation.prototype;
function OrOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
OrOperation.prototype.init = function(lhs, rhs) {
OrOperation.superclass.init.call(this, lhs, rhs);
};
OrOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " or " + this.rhs.toString() + ")";
};
OrOperation.prototype.evaluate = function(c) {
var b = this.lhs.evaluate(c).bool();
if (b.booleanValue()) {
return b;
}
return this.rhs.evaluate(c).bool();
};
// AndOperation //////////////////////////////////////////////////////////////
AndOperation.prototype = new BinaryOperation();
AndOperation.prototype.constructor = AndOperation;
AndOperation.superclass = BinaryOperation.prototype;
function AndOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
AndOperation.prototype.init = function(lhs, rhs) {
AndOperation.superclass.init.call(this, lhs, rhs);
};
AndOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " and " + this.rhs.toString() + ")";
};
AndOperation.prototype.evaluate = function(c) {
var b = this.lhs.evaluate(c).bool();
if (!b.booleanValue()) {
return b;
}
return this.rhs.evaluate(c).bool();
};
// EqualsOperation ///////////////////////////////////////////////////////////
EqualsOperation.prototype = new BinaryOperation();
EqualsOperation.prototype.constructor = EqualsOperation;
EqualsOperation.superclass = BinaryOperation.prototype;
function EqualsOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
EqualsOperation.prototype.init = function(lhs, rhs) {
EqualsOperation.superclass.init.call(this, lhs, rhs);
};
EqualsOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " = " + this.rhs.toString() + ")";
};
EqualsOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).equals(this.rhs.evaluate(c));
};
// NotEqualOperation /////////////////////////////////////////////////////////
NotEqualOperation.prototype = new BinaryOperation();
NotEqualOperation.prototype.constructor = NotEqualOperation;
NotEqualOperation.superclass = BinaryOperation.prototype;
function NotEqualOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
NotEqualOperation.prototype.init = function(lhs, rhs) {
NotEqualOperation.superclass.init.call(this, lhs, rhs);
};
NotEqualOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " != " + this.rhs.toString() + ")";
};
NotEqualOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).notequal(this.rhs.evaluate(c));
};
// LessThanOperation /////////////////////////////////////////////////////////
LessThanOperation.prototype = new BinaryOperation();
LessThanOperation.prototype.constructor = LessThanOperation;
LessThanOperation.superclass = BinaryOperation.prototype;
function LessThanOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
LessThanOperation.prototype.init = function(lhs, rhs) {
LessThanOperation.superclass.init.call(this, lhs, rhs);
};
LessThanOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).lessthan(this.rhs.evaluate(c));
};
LessThanOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " < " + this.rhs.toString() + ")";
};
// GreaterThanOperation //////////////////////////////////////////////////////
GreaterThanOperation.prototype = new BinaryOperation();
GreaterThanOperation.prototype.constructor = GreaterThanOperation;
GreaterThanOperation.superclass = BinaryOperation.prototype;
function GreaterThanOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
GreaterThanOperation.prototype.init = function(lhs, rhs) {
GreaterThanOperation.superclass.init.call(this, lhs, rhs);
};
GreaterThanOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).greaterthan(this.rhs.evaluate(c));
};
GreaterThanOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " > " + this.rhs.toString() + ")";
};
// LessThanOrEqualOperation //////////////////////////////////////////////////
LessThanOrEqualOperation.prototype = new BinaryOperation();
LessThanOrEqualOperation.prototype.constructor = LessThanOrEqualOperation;
LessThanOrEqualOperation.superclass = BinaryOperation.prototype;
function LessThanOrEqualOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
LessThanOrEqualOperation.prototype.init = function(lhs, rhs) {
LessThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
};
LessThanOrEqualOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).lessthanorequal(this.rhs.evaluate(c));
};
LessThanOrEqualOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " <= " + this.rhs.toString() + ")";
};
// GreaterThanOrEqualOperation ///////////////////////////////////////////////
GreaterThanOrEqualOperation.prototype = new BinaryOperation();
GreaterThanOrEqualOperation.prototype.constructor = GreaterThanOrEqualOperation;
GreaterThanOrEqualOperation.superclass = BinaryOperation.prototype;
function GreaterThanOrEqualOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
GreaterThanOrEqualOperation.prototype.init = function(lhs, rhs) {
GreaterThanOrEqualOperation.superclass.init.call(this, lhs, rhs);
};
GreaterThanOrEqualOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).greaterthanorequal(this.rhs.evaluate(c));
};
GreaterThanOrEqualOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " >= " + this.rhs.toString() + ")";
};
// PlusOperation /////////////////////////////////////////////////////////////
PlusOperation.prototype = new BinaryOperation();
PlusOperation.prototype.constructor = PlusOperation;
PlusOperation.superclass = BinaryOperation.prototype;
function PlusOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
PlusOperation.prototype.init = function(lhs, rhs) {
PlusOperation.superclass.init.call(this, lhs, rhs);
};
PlusOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).number().plus(this.rhs.evaluate(c).number());
};
PlusOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " + " + this.rhs.toString() + ")";
};
// MinusOperation ////////////////////////////////////////////////////////////
MinusOperation.prototype = new BinaryOperation();
MinusOperation.prototype.constructor = MinusOperation;
MinusOperation.superclass = BinaryOperation.prototype;
function MinusOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
MinusOperation.prototype.init = function(lhs, rhs) {
MinusOperation.superclass.init.call(this, lhs, rhs);
};
MinusOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).number().minus(this.rhs.evaluate(c).number());
};
MinusOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " - " + this.rhs.toString() + ")";
};
// MultiplyOperation /////////////////////////////////////////////////////////
MultiplyOperation.prototype = new BinaryOperation();
MultiplyOperation.prototype.constructor = MultiplyOperation;
MultiplyOperation.superclass = BinaryOperation.prototype;
function MultiplyOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
MultiplyOperation.prototype.init = function(lhs, rhs) {
MultiplyOperation.superclass.init.call(this, lhs, rhs);
};
MultiplyOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).number().multiply(this.rhs.evaluate(c).number());
};
MultiplyOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " * " + this.rhs.toString() + ")";
};
// DivOperation //////////////////////////////////////////////////////////////
DivOperation.prototype = new BinaryOperation();
DivOperation.prototype.constructor = DivOperation;
DivOperation.superclass = BinaryOperation.prototype;
function DivOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
DivOperation.prototype.init = function(lhs, rhs) {
DivOperation.superclass.init.call(this, lhs, rhs);
};
DivOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).number().div(this.rhs.evaluate(c).number());
};
DivOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " div " + this.rhs.toString() + ")";
};
// ModOperation //////////////////////////////////////////////////////////////
ModOperation.prototype = new BinaryOperation();
ModOperation.prototype.constructor = ModOperation;
ModOperation.superclass = BinaryOperation.prototype;
function ModOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
ModOperation.prototype.init = function(lhs, rhs) {
ModOperation.superclass.init.call(this, lhs, rhs);
};
ModOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).number().mod(this.rhs.evaluate(c).number());
};
ModOperation.prototype.toString = function() {
return "(" + this.lhs.toString() + " mod " + this.rhs.toString() + ")";
};
// BarOperation //////////////////////////////////////////////////////////////
BarOperation.prototype = new BinaryOperation();
BarOperation.prototype.constructor = BarOperation;
BarOperation.superclass = BinaryOperation.prototype;
function BarOperation(lhs, rhs) {
if (arguments.length > 0) {
this.init(lhs, rhs);
}
}
BarOperation.prototype.init = function(lhs, rhs) {
BarOperation.superclass.init.call(this, lhs, rhs);
};
BarOperation.prototype.evaluate = function(c) {
return this.lhs.evaluate(c).nodeset().union(this.rhs.evaluate(c).nodeset());
};
BarOperation.prototype.toString = function() {
return this.lhs.toString() + " | " + this.rhs.toString();
};
// PathExpr //////////////////////////////////////////////////////////////////
PathExpr.prototype = new Expression();
PathExpr.prototype.constructor = PathExpr;
PathExpr.superclass = Expression.prototype;
function PathExpr(filter, filterPreds, locpath) {
if (arguments.length > 0) {
this.init(filter, filterPreds, locpath);
}
}
PathExpr.prototype.init = function(filter, filterPreds, locpath) {
PathExpr.superclass.init.call(this);
this.filter = filter;
this.filterPredicates = filterPreds;
this.locationPath = locpath;
};
/**
* Returns the topmost node of the tree containing node
*/
function findRoot(node) {
while (node && node.parentNode) {
node = node.parentNode;
}
return node;
}
PathExpr.prototype.evaluate = function(c) {
var nodes;
var xpc = new XPathContext();
xpc.variableResolver = c.variableResolver;
xpc.functionResolver = c.functionResolver;
xpc.namespaceResolver = c.namespaceResolver;
xpc.expressionContextNode = c.expressionContextNode;
xpc.virtualRoot = c.virtualRoot;
xpc.caseInsensitive = c.caseInsensitive;
if (this.filter == null) {
nodes = [ c.contextNode ];
} else {
var ns = this.filter.evaluate(c);
if (!Utilities.instance_of(ns, XNodeSet)) {
if (this.filterPredicates != null && this.filterPredicates.length > 0 || this.locationPath != null) {
throw new Error("Path expression filter must evaluate to a nodset if predicates or location path are used");
}
return ns;
}
nodes = ns.toUnsortedArray();
if (this.filterPredicates != null) {
// apply each of the predicates in turn
for (var j = 0; j < this.filterPredicates.length; j++) {
var pred = this.filterPredicates[j];
var newNodes = [];
xpc.contextSize = nodes.length;
for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) {
xpc.contextNode = nodes[xpc.contextPosition - 1];
if (this.predicateMatches(pred, xpc)) {
newNodes.push(xpc.contextNode);
}
}
nodes = newNodes;
}
}
}
if (this.locationPath != null) {
if (this.locationPath.absolute) {
if (nodes[0].nodeType != 9 /*Node.DOCUMENT_NODE*/) {
if (xpc.virtualRoot != null) {
nodes = [ xpc.virtualRoot ];
} else {
if (nodes[0].ownerDocument == null) {
// IE 5.5 doesn't have ownerDocument?
var n = nodes[0];
while (n.parentNode != null) {
n = n.parentNode;
}
nodes = [ n ];
} else {
nodes = [ nodes[0].ownerDocument ];
}
}
} else {
nodes = [ nodes[0] ];
}
}
for (var i = 0; i < this.locationPath.steps.length; i++) {
var step = this.locationPath.steps[i];
var newNodes = [];
for (var j = 0; j < nodes.length; j++) {
xpc.contextNode = nodes[j];
switch (step.axis) {
case Step.ANCESTOR:
// look at all the ancestor nodes
if (xpc.contextNode === xpc.virtualRoot) {
break;
}
var m;
if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
m = this.getOwnerElement(xpc.contextNode);
} else {
m = xpc.contextNode.parentNode;
}
while (m != null) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
if (m === xpc.virtualRoot) {
break;
}
m = m.parentNode;
}
break;
case Step.ANCESTORORSELF:
// look at all the ancestor nodes and the current node
for (var m = xpc.contextNode; m != null; m = m.nodeType == 2 /*Node.ATTRIBUTE_NODE*/ ? this.getOwnerElement(m) : m.parentNode) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
if (m === xpc.virtualRoot) {
break;
}
}
break;
case Step.ATTRIBUTE:
// look at the attributes
var nnm = xpc.contextNode.attributes;
if (nnm != null) {
for (var k = 0; k < nnm.length; k++) {
var m = nnm.item(k);
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
}
}
break;
case Step.CHILD:
// look at all child elements
for (var m = xpc.contextNode.firstChild; m != null; m = m.nextSibling) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
}
break;
case Step.DESCENDANT:
// look at all descendant nodes
var st = [ xpc.contextNode.firstChild ];
while (st.length > 0) {
for (var m = st.pop(); m != null; ) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
if (m.firstChild != null) {
st.push(m.nextSibling);
m = m.firstChild;
} else {
m = m.nextSibling;
}
}
}
break;
case Step.DESCENDANTORSELF:
// look at self
if (step.nodeTest.matches(xpc.contextNode, xpc)) {
newNodes.push(xpc.contextNode);
}
// look at all descendant nodes
var st = [ xpc.contextNode.firstChild ];
while (st.length > 0) {
for (var m = st.pop(); m != null; ) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
if (m.firstChild != null) {
st.push(m.nextSibling);
m = m.firstChild;
} else {
m = m.nextSibling;
}
}
}
break;
case Step.FOLLOWING:
if (xpc.contextNode === xpc.virtualRoot) {
break;
}
var st = [];
if (xpc.contextNode.firstChild != null) {
st.unshift(xpc.contextNode.firstChild);
} else {
st.unshift(xpc.contextNode.nextSibling);
}
for (var m = xpc.contextNode.parentNode; m != null && m.nodeType != 9 /*Node.DOCUMENT_NODE*/ && m !== xpc.virtualRoot; m = m.parentNode) {
st.unshift(m.nextSibling);
}
do {
for (var m = st.pop(); m != null; ) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
if (m.firstChild != null) {
st.push(m.nextSibling);
m = m.firstChild;
} else {
m = m.nextSibling;
}
}
} while (st.length > 0);
break;
case Step.FOLLOWINGSIBLING:
if (xpc.contextNode === xpc.virtualRoot) {
break;
}
for (var m = xpc.contextNode.nextSibling; m != null; m = m.nextSibling) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
}
break;
case Step.NAMESPACE:
var n = {};
if (xpc.contextNode.nodeType == 1 /*Node.ELEMENT_NODE*/) {
n["xml"] = XPath.XML_NAMESPACE_URI;
n["xmlns"] = XPath.XMLNS_NAMESPACE_URI;
for (var m = xpc.contextNode; m != null && m.nodeType == 1 /*Node.ELEMENT_NODE*/; m = m.parentNode) {
for (var k = 0; k < m.attributes.length; k++) {
var attr = m.attributes.item(k);
var nm = String(attr.name);
if (nm == "xmlns") {
if (n[""] == undefined) {
n[""] = attr.value;
}
} else if (nm.length > 6 && nm.substring(0, 6) == "xmlns:") {
var pre = nm.substring(6, nm.length);
if (n[pre] == undefined) {
n[pre] = attr.value;
}
}
}
}
for (var pre in n) {
var nsn = new XPathNamespace(pre, n[pre], xpc.contextNode);
if (step.nodeTest.matches(nsn, xpc)) {
newNodes.push(nsn);
}
}
}
break;
case Step.PARENT:
m = null;
if (xpc.contextNode !== xpc.virtualRoot) {
if (xpc.contextNode.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
m = this.getOwnerElement(xpc.contextNode);
} else {
m = xpc.contextNode.parentNode;
}
}
if (m != null && step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
break;
case Step.PRECEDING:
var st;
if (xpc.virtualRoot != null) {
st = [ xpc.virtualRoot ];
} else {
// cannot rely on .ownerDocument because the node may be in a document fragment
st = [findRoot(xpc.contextNode)];
}
outer: while (st.length > 0) {
for (var m = st.pop(); m != null; ) {
if (m == xpc.contextNode) {
break outer;
}
if (step.nodeTest.matches(m, xpc)) {
newNodes.unshift(m);
}
if (m.firstChild != null) {
st.push(m.nextSibling);
m = m.firstChild;
} else {
m = m.nextSibling;
}
}
}
break;
case Step.PRECEDINGSIBLING:
if (xpc.contextNode === xpc.virtualRoot) {
break;
}
for (var m = xpc.contextNode.previousSibling; m != null; m = m.previousSibling) {
if (step.nodeTest.matches(m, xpc)) {
newNodes.push(m);
}
}
break;
case Step.SELF:
if (step.nodeTest.matches(xpc.contextNode, xpc)) {
newNodes.push(xpc.contextNode);
}
break;
default:
}
}
nodes = newNodes;
// apply each of the predicates in turn
for (var j = 0; j < step.predicates.length; j++) {
var pred = step.predicates[j];
var newNodes = [];
xpc.contextSize = nodes.length;
for (xpc.contextPosition = 1; xpc.contextPosition <= xpc.contextSize; xpc.contextPosition++) {
xpc.contextNode = nodes[xpc.contextPosition - 1];
if (this.predicateMatches(pred, xpc)) {
newNodes.push(xpc.contextNode);
} else {
}
}
nodes = newNodes;
}
}
}
var ns = new XNodeSet();
ns.addArray(nodes);
return ns;
};
PathExpr.prototype.predicateMatches = function(pred, c) {
var res = pred.evaluate(c);
if (Utilities.instance_of(res, XNumber)) {
return c.contextPosition == res.numberValue();
}
return res.booleanValue();
};
PathExpr.prototype.toString = function() {
if (this.filter != undefined) {
var s = this.filter.toString();
if (Utilities.instance_of(this.filter, XString)) {
s = "'" + s + "'";
}
if (this.filterPredicates != undefined) {
for (var i = 0; i < this.filterPredicates.length; i++) {
s = s + "[" + this.filterPredicates[i].toString() + "]";
}
}
if (this.locationPath != undefined) {
if (!this.locationPath.absolute) {
s += "/";
}
s += this.locationPath.toString();
}
return s;
}
return this.locationPath.toString();
};
PathExpr.prototype.getOwnerElement = function(n) {
// DOM 2 has ownerElement
if (n.ownerElement) {
return n.ownerElement;
}
// DOM 1 Internet Explorer can use selectSingleNode (ironically)
try {
if (n.selectSingleNode) {
return n.selectSingleNode("..");
}
} catch (e) {
}
// Other DOM 1 implementations must use this egregious search
var doc = n.nodeType == 9 /*Node.DOCUMENT_NODE*/
? n
: n.ownerDocument;
var elts = doc.getElementsByTagName("*");
for (var i = 0; i < elts.length; i++) {
var elt = elts.item(i);
var nnm = elt.attributes;
for (var j = 0; j < nnm.length; j++) {
var an = nnm.item(j);
if (an === n) {
return elt;
}
}
}
return null;
};
// LocationPath //////////////////////////////////////////////////////////////
LocationPath.prototype = new Object();
LocationPath.prototype.constructor = LocationPath;
LocationPath.superclass = Object.prototype;
function LocationPath(abs, steps) {
if (arguments.length > 0) {
this.init(abs, steps);
}
}
LocationPath.prototype.init = function(abs, steps) {
this.absolute = abs;
this.steps = steps;
};
LocationPath.prototype.toString = function() {
var s;
if (this.absolute) {
s = "/";
} else {
s = "";
}
for (var i = 0; i < this.steps.length; i++) {
if (i != 0) {
s += "/";
}
s += this.steps[i].toString();
}
return s;
};
// Step //////////////////////////////////////////////////////////////////////
Step.prototype = new Object();
Step.prototype.constructor = Step;
Step.superclass = Object.prototype;
function Step(axis, nodetest, preds) {
if (arguments.length > 0) {
this.init(axis, nodetest, preds);
}
}
Step.prototype.init = function(axis, nodetest, preds) {
this.axis = axis;
this.nodeTest = nodetest;
this.predicates = preds;
};
Step.prototype.toString = function() {
var s;
switch (this.axis) {
case Step.ANCESTOR:
s = "ancestor";
break;
case Step.ANCESTORORSELF:
s = "ancestor-or-self";
break;
case Step.ATTRIBUTE:
s = "attribute";
break;
case Step.CHILD:
s = "child";
break;
case Step.DESCENDANT:
s = "descendant";
break;
case Step.DESCENDANTORSELF:
s = "descendant-or-self";
break;
case Step.FOLLOWING:
s = "following";
break;
case Step.FOLLOWINGSIBLING:
s = "following-sibling";
break;
case Step.NAMESPACE:
s = "namespace";
break;
case Step.PARENT:
s = "parent";
break;
case Step.PRECEDING:
s = "preceding";
break;
case Step.PRECEDINGSIBLING:
s = "preceding-sibling";
break;
case Step.SELF:
s = "self";
break;
}
s += "::";
s += this.nodeTest.toString();
for (var i = 0; i < this.predicates.length; i++) {
s += "[" + this.predicates[i].toString() + "]";
}
return s;
};
Step.ANCESTOR = 0;
Step.ANCESTORORSELF = 1;
Step.ATTRIBUTE = 2;
Step.CHILD = 3;
Step.DESCENDANT = 4;
Step.DESCENDANTORSELF = 5;
Step.FOLLOWING = 6;
Step.FOLLOWINGSIBLING = 7;
Step.NAMESPACE = 8;
Step.PARENT = 9;
Step.PRECEDING = 10;
Step.PRECEDINGSIBLING = 11;
Step.SELF = 12;
// NodeTest //////////////////////////////////////////////////////////////////
NodeTest.prototype = new Object();
NodeTest.prototype.constructor = NodeTest;
NodeTest.superclass = Object.prototype;
function NodeTest(type, value) {
if (arguments.length > 0) {
this.init(type, value);
}
}
NodeTest.prototype.init = function(type, value) {
this.type = type;
this.value = value;
};
NodeTest.prototype.toString = function() {
switch (this.type) {
case NodeTest.NAMETESTANY:
return "*";
case NodeTest.NAMETESTPREFIXANY:
return this.value + ":*";
case NodeTest.NAMETESTRESOLVEDANY:
return "{" + this.value + "}*";
case NodeTest.NAMETESTQNAME:
return this.value;
case NodeTest.NAMETESTRESOLVEDNAME:
return "{" + this.namespaceURI + "}" + this.value;
case NodeTest.COMMENT:
return "comment()";
case NodeTest.TEXT:
return "text()";
case NodeTest.PI:
if (this.value != undefined) {
return "processing-instruction(\"" + this.value + "\")";
}
return "processing-instruction()";
case NodeTest.NODE:
return "node()";
}
return "<unknown nodetest type>";
};
NodeTest.prototype.matches = function (n, xpc) {
var nType = n.nodeType;
switch (this.type) {
case NodeTest.NAMETESTANY:
if (nType === 2 /*Node.ATTRIBUTE_NODE*/
|| nType === 1 /*Node.ELEMENT_NODE*/
|| nType === XPathNamespace.XPATH_NAMESPACE_NODE) {
return true;
}
return false;
case NodeTest.NAMETESTPREFIXANY:
if (nType === 2 /*Node.ATTRIBUTE_NODE*/ || nType === 1 /*Node.ELEMENT_NODE*/) {
var ns = xpc.namespaceResolver.getNamespace(this.value, xpc.expressionContextNode);
if (ns == null) {
throw new Error("Cannot resolve QName " + this.value);
}
return ns === (n.namespaceURI || '');
}
return false;
case NodeTest.NAMETESTQNAME:
if (nType === 2 /*Node.ATTRIBUTE_NODE*/
|| nType === 1 /*Node.ELEMENT_NODE*/
|| nType === XPathNamespace.XPATH_NAMESPACE_NODE) {
var test = Utilities.resolveQName(this.value, xpc.namespaceResolver, xpc.expressionContextNode, false);
if (test[0] == null) {
throw new Error("Cannot resolve QName " + this.value);
}
test[0] = String(test[0]) || null;
test[1] = String(test[1]);
var node = [
String(n.namespaceURI || '') || null,
// localName will be null if the node was created with DOM1 createElement()
String(n.localName || n.nodeName)
];
if (xpc.caseInsensitive) {
return test[0] === node[0] && test[1].toLowerCase() === node[1].toLowerCase();
}
return test[0] === node[0] && test[1] === node[1];
}
return false;
case NodeTest.COMMENT:
return nType === 8 /*Node.COMMENT_NODE*/;
case NodeTest.TEXT:
return nType === 3 /*Node.TEXT_NODE*/ || nType == 4 /*Node.CDATA_SECTION_NODE*/;
case NodeTest.PI:
return nType === 7 /*Node.PROCESSING_INSTRUCTION_NODE*/
&& (this.value == null || n.nodeName == this.value);
case NodeTest.NODE:
return nType === 9 /*Node.DOCUMENT_NODE*/
|| nType === 1 /*Node.ELEMENT_NODE*/
|| nType === 2 /*Node.ATTRIBUTE_NODE*/
|| nType === 3 /*Node.TEXT_NODE*/
|| nType === 4 /*Node.CDATA_SECTION_NODE*/
|| nType === 8 /*Node.COMMENT_NODE*/
|| nType === 7 /*Node.PROCESSING_INSTRUCTION_NODE*/;
}
return false;
};
NodeTest.NAMETESTANY = 0;
NodeTest.NAMETESTPREFIXANY = 1;
NodeTest.NAMETESTQNAME = 2;
NodeTest.COMMENT = 3;
NodeTest.TEXT = 4;
NodeTest.PI = 5;
NodeTest.NODE = 6;
// VariableReference /////////////////////////////////////////////////////////
VariableReference.prototype = new Expression();
VariableReference.prototype.constructor = VariableReference;
VariableReference.superclass = Expression.prototype;
function VariableReference(v) {
if (arguments.length > 0) {
this.init(v);
}
}
VariableReference.prototype.init = function(v) {
this.variable = v;
};
VariableReference.prototype.toString = function() {
return "$" + this.variable;
};
VariableReference.prototype.evaluate = function(c) {
var parts = Utilities.resolveQName(this.variable, c.namespaceResolver, c.contextNode, false);
if (parts[0] == null) {
throw new Error("Cannot resolve QName " + fn);
}
var result = c.variableResolver.getVariable(parts[1], parts[0]);
if (!result) {
throw XPathException.fromMessage("Undeclared variable: " + this.toString());
}
return result;
};
// FunctionCall //////////////////////////////////////////////////////////////
FunctionCall.prototype = new Expression();
FunctionCall.prototype.constructor = FunctionCall;
FunctionCall.superclass = Expression.prototype;
function FunctionCall(fn, args) {
if (arguments.length > 0) {
this.init(fn, args);
}
}
FunctionCall.prototype.init = function(fn, args) {
this.functionName = fn;
this.arguments = args;
};
FunctionCall.prototype.toString = function() {
var s = this.functionName + "(";
for (var i = 0; i < this.arguments.length; i++) {
if (i > 0) {
s += ", ";
}
s += this.arguments[i].toString();
}
return s + ")";
};
FunctionCall.prototype.evaluate = function(c) {
var f = FunctionResolver.getFunctionFromContext(this.functionName, c);
if (!f) {
throw new Error("Unknown function " + this.functionName);
}
var a = [c].concat(this.arguments);
return f.apply(c.functionResolver.thisArg, a);
};
// XString ///////////////////////////////////////////////////////////////////
XString.prototype = new Expression();
XString.prototype.constructor = XString;
XString.superclass = Expression.prototype;
function XString(s) {
if (arguments.length > 0) {
this.init(s);
}
}
XString.prototype.init = function(s) {
this.str = String(s);
};
XString.prototype.toString = function() {
return this.str;
};
XString.prototype.evaluate = function(c) {
return this;
};
XString.prototype.string = function() {
return this;
};
XString.prototype.number = function() {
return new XNumber(this.str);
};
XString.prototype.bool = function() {
return new XBoolean(this.str);
};
XString.prototype.nodeset = function() {
throw new Error("Cannot convert string to nodeset");
};
XString.prototype.stringValue = function() {
return this.str;
};
XString.prototype.numberValue = function() {
return this.number().numberValue();
};
XString.prototype.booleanValue = function() {
return this.bool().booleanValue();
};
XString.prototype.equals = function(r) {
if (Utilities.instance_of(r, XBoolean)) {
return this.bool().equals(r);
}
if (Utilities.instance_of(r, XNumber)) {
return this.number().equals(r);
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithString(this, Operators.equals);
}
return new XBoolean(this.str == r.str);
};
XString.prototype.notequal = function(r) {
if (Utilities.instance_of(r, XBoolean)) {
return this.bool().notequal(r);
}
if (Utilities.instance_of(r, XNumber)) {
return this.number().notequal(r);
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithString(this, Operators.notequal);
}
return new XBoolean(this.str != r.str);
};
XString.prototype.lessthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.greaterthanorequal);
}
return this.number().lessthan(r.number());
};
XString.prototype.greaterthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.lessthanorequal);
}
return this.number().greaterthan(r.number());
};
XString.prototype.lessthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.greaterthan);
}
return this.number().lessthanorequal(r.number());
};
XString.prototype.greaterthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.lessthan);
}
return this.number().greaterthanorequal(r.number());
};
// XNumber ///////////////////////////////////////////////////////////////////
XNumber.prototype = new Expression();
XNumber.prototype.constructor = XNumber;
XNumber.superclass = Expression.prototype;
function XNumber(n) {
if (arguments.length > 0) {
this.init(n);
}
}
XNumber.prototype.init = function(n) {
this.num = typeof n === "string" ? this.parse(n) : Number(n);
};
XNumber.prototype.numberFormat = /^\s*-?[0-9]*\.?[0-9]+\s*$/;
XNumber.prototype.parse = function(s) {
// XPath representation of numbers is more restrictive than what Number() or parseFloat() allow
return this.numberFormat.test(s) ? parseFloat(s) : Number.NaN;
};
function padSmallNumber(numberStr) {
var parts = numberStr.split('e-');
var base = parts[0].replace('.', '');
var exponent = Number(parts[1]);
for (var i = 0; i < exponent - 1; i += 1) {
base = '0' + base;
}
return '0.' + base;
}
function padLargeNumber(numberStr) {
var parts = numberStr.split('e');
var base = parts[0].replace('.', '');
var exponent = Number(parts[1]);
var zerosToAppend = exponent + 1 - base.length;
for (var i = 0; i < zerosToAppend; i += 1){
base += '0';
}
return base;
}
XNumber.prototype.toString = function() {
var strValue = this.num.toString();
if (strValue.indexOf('e-') !== -1) {
return padSmallNumber(strValue);
}
if (strValue.indexOf('e') !== -1) {
return padLargeNumber(strValue);
}
return strValue;
};
XNumber.prototype.evaluate = function(c) {
return this;
};
XNumber.prototype.string = function() {
return new XString(this.toString());
};
XNumber.prototype.number = function() {
return this;
};
XNumber.prototype.bool = function() {
return new XBoolean(this.num);
};
XNumber.prototype.nodeset = function() {
throw new Error("Cannot convert number to nodeset");
};
XNumber.prototype.stringValue = function() {
return this.string().stringValue();
};
XNumber.prototype.numberValue = function() {
return this.num;
};
XNumber.prototype.booleanValue = function() {
return this.bool().booleanValue();
};
XNumber.prototype.negate = function() {
return new XNumber(-this.num);
};
XNumber.prototype.equals = function(r) {
if (Utilities.instance_of(r, XBoolean)) {
return this.bool().equals(r);
}
if (Utilities.instance_of(r, XString)) {
return this.equals(r.number());
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.equals);
}
return new XBoolean(this.num == r.num);
};
XNumber.prototype.notequal = function(r) {
if (Utilities.instance_of(r, XBoolean)) {
return this.bool().notequal(r);
}
if (Utilities.instance_of(r, XString)) {
return this.notequal(r.number());
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.notequal);
}
return new XBoolean(this.num != r.num);
};
XNumber.prototype.lessthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.greaterthanorequal);
}
if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
return this.lessthan(r.number());
}
return new XBoolean(this.num < r.num);
};
XNumber.prototype.greaterthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.lessthanorequal);
}
if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
return this.greaterthan(r.number());
}
return new XBoolean(this.num > r.num);
};
XNumber.prototype.lessthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.greaterthan);
}
if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
return this.lessthanorequal(r.number());
}
return new XBoolean(this.num <= r.num);
};
XNumber.prototype.greaterthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this, Operators.lessthan);
}
if (Utilities.instance_of(r, XBoolean) || Utilities.instance_of(r, XString)) {
return this.greaterthanorequal(r.number());
}
return new XBoolean(this.num >= r.num);
};
XNumber.prototype.plus = function(r) {
return new XNumber(this.num + r.num);
};
XNumber.prototype.minus = function(r) {
return new XNumber(this.num - r.num);
};
XNumber.prototype.multiply = function(r) {
return new XNumber(this.num * r.num);
};
XNumber.prototype.div = function(r) {
return new XNumber(this.num / r.num);
};
XNumber.prototype.mod = function(r) {
return new XNumber(this.num % r.num);
};
// XBoolean //////////////////////////////////////////////////////////////////
XBoolean.prototype = new Expression();
XBoolean.prototype.constructor = XBoolean;
XBoolean.superclass = Expression.prototype;
function XBoolean(b) {
if (arguments.length > 0) {
this.init(b);
}
}
XBoolean.prototype.init = function(b) {
this.b = Boolean(b);
};
XBoolean.prototype.toString = function() {
return this.b.toString();
};
XBoolean.prototype.evaluate = function(c) {
return this;
};
XBoolean.prototype.string = function() {
return new XString(this.b);
};
XBoolean.prototype.number = function() {
return new XNumber(this.b);
};
XBoolean.prototype.bool = function() {
return this;
};
XBoolean.prototype.nodeset = function() {
throw new Error("Cannot convert boolean to nodeset");
};
XBoolean.prototype.stringValue = function() {
return this.string().stringValue();
};
XBoolean.prototype.numberValue = function() {
return this.num().numberValue();
};
XBoolean.prototype.booleanValue = function() {
return this.b;
};
XBoolean.prototype.not = function() {
return new XBoolean(!this.b);
};
XBoolean.prototype.equals = function(r) {
if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
return this.equals(r.bool());
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithBoolean(this, Operators.equals);
}
return new XBoolean(this.b == r.b);
};
XBoolean.prototype.notequal = function(r) {
if (Utilities.instance_of(r, XString) || Utilities.instance_of(r, XNumber)) {
return this.notequal(r.bool());
}
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithBoolean(this, Operators.notequal);
}
return new XBoolean(this.b != r.b);
};
XBoolean.prototype.lessthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.greaterthanorequal);
}
return this.number().lessthan(r.number());
};
XBoolean.prototype.greaterthan = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.lessthanorequal);
}
return this.number().greaterthan(r.number());
};
XBoolean.prototype.lessthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.greaterthan);
}
return this.number().lessthanorequal(r.number());
};
XBoolean.prototype.greaterthanorequal = function(r) {
if (Utilities.instance_of(r, XNodeSet)) {
return r.compareWithNumber(this.number(), Operators.lessthan);
}
return this.number().greaterthanorequal(r.number());
};
// AVLTree ///////////////////////////////////////////////////////////////////
AVLTree.prototype = new Object();
AVLTree.prototype.constructor = AVLTree;
AVLTree.superclass = Object.prototype;
function AVLTree(n) {
this.init(n);
}
AVLTree.prototype.init = function(n) {
this.left = null;
this.right = null;
this.node = n;
this.depth = 1;
};
AVLTree.prototype.balance = function() {
var ldepth = this.left == null ? 0 : this.left.depth;
var rdepth = this.right == null ? 0 : this.right.depth;
if (ldepth > rdepth + 1) {
// LR or LL rotation
var lldepth = this.left.left == null ? 0 : this.left.left.depth;
var lrdepth = this.left.right == null ? 0 : this.left.right.depth;
if (lldepth < lrdepth) {
// LR rotation consists of a RR rotation of the left child
this.left.rotateRR();
// plus a LL rotation of this node, which happens anyway
}
this.rotateLL();
} else if (ldepth + 1 < rdepth) {
// RR or RL rorarion
var rrdepth = this.right.right == null ? 0 : this.right.right.depth;
var rldepth = this.right.left == null ? 0 : this.right.left.depth;
if (rldepth > rrdepth) {
// RR rotation consists of a LL rotation of the right child
this.right.rotateLL();
// plus a RR rotation of this node, which happens anyway
}
this.rotateRR();
}
};
AVLTree.prototype.rotateLL = function() {
// the left side is too long => rotate from the left (_not_ leftwards)
var nodeBefore = this.node;
var rightBefore = this.right;
this.node = this.left.node;
this.right = this.left;
this.left = this.left.left;
this.right.left = this.right.right;
this.right.right = rightBefore;
this.right.node = nodeBefore;
this.right.updateInNewLocation();
this.updateInNewLocation();
};
AVLTree.prototype.rotateRR = function() {
// the right side is too long => rotate from the right (_not_ rightwards)
var nodeBefore = this.node;
var leftBefore = this.left;
this.node = this.right.node;
this.left = this.right;
this.right = this.right.right;
this.left.right = this.left.left;
this.left.left = leftBefore;
this.left.node = nodeBefore;
this.left.updateInNewLocation();
this.updateInNewLocation();
};
AVLTree.prototype.updateInNewLocation = function() {
this.getDepthFromChildren();
};
AVLTree.prototype.getDepthFromChildren = function() {
this.depth = this.node == null ? 0 : 1;
if (this.left != null) {
this.depth = this.left.depth + 1;
}
if (this.right != null && this.depth <= this.right.depth) {
this.depth = this.right.depth + 1;
}
};
function nodeOrder(n1, n2) {
if (n1 === n2) {
return 0;
}
if (n1.compareDocumentPosition) {
var cpos = n1.compareDocumentPosition(n2);
if (cpos & 0x01) {
// not in the same document; return an arbitrary result (is there a better way to do this)
return 1;
}
if (cpos & 0x0A) {
// n2 precedes or contains n1
return 1;
}
if (cpos & 0x14) {
// n2 follows or is contained by n1
return -1;
}
return 0;
}
var d1 = 0,
d2 = 0;
for (var m1 = n1; m1 != null; m1 = m1.parentNode || m1.ownerElement) {
d1++;
}
for (var m2 = n2; m2 != null; m2 = m2.parentNode || m2.ownerElement) {
d2++;
}
// step up to same depth
if (d1 > d2) {
while (d1 > d2) {
n1 = n1.parentNode || n1.ownerElement;
d1--;
}
if (n1 === n2) {
return 1;
}
} else if (d2 > d1) {
while (d2 > d1) {
n2 = n2.parentNode || n2.ownerElement;
d2--;
}
if (n1 === n2) {
return -1;
}
}
var n1Par = n1.parentNode || n1.ownerElement,
n2Par = n2.parentNode || n2.ownerElement;
// find common parent
while (n1Par !== n2Par) {
n1 = n1Par;
n2 = n2Par;
n1Par = n1.parentNode || n1.ownerElement;
n2Par = n2.parentNode || n2.ownerElement;
}
var n1isAttr = Utilities.isAttribute(n1);
var n2isAttr = Utilities.isAttribute(n2);
if (n1isAttr && !n2isAttr) {
return -1;
}
if (!n1isAttr && n2isAttr) {
return 1;
}
if(n1Par) {
var cn = n1isAttr ? n1Par.attributes : n1Par.childNodes,
len = cn.length;
for (var i = 0; i < len; i += 1) {
var n = cn[i];
if (n === n1) {
return -1;
}
if (n === n2) {
return 1;
}
}
}
throw new Error('Unexpected: could not determine node order');
}
AVLTree.prototype.add = function(n) {
if (n === this.node) {
return false;
}
var o = nodeOrder(n, this.node);
var ret = false;
if (o == -1) {
if (this.left == null) {
this.left = new AVLTree(n);
ret = true;
} else {
ret = this.left.add(n);
if (ret) {
this.balance();
}
}
} else if (o == 1) {
if (this.right == null) {
this.right = new AVLTree(n);
ret = true;
} else {
ret = this.right.add(n);
if (ret) {
this.balance();
}
}
}
if (ret) {
this.getDepthFromChildren();
}
return ret;
};
// XNodeSet //////////////////////////////////////////////////////////////////
XNodeSet.prototype = new Expression();
XNodeSet.prototype.constructor = XNodeSet;
XNodeSet.superclass = Expression.prototype;
function XNodeSet() {
this.init();
}
XNodeSet.prototype.init = function() {
this.tree = null;
this.nodes = [];
this.size = 0;
};
XNodeSet.prototype.toString = function() {
var p = this.first();
if (p == null) {
return "";
}
return this.stringForNode(p);
};
XNodeSet.prototype.evaluate = function(c) {
return this;
};
XNodeSet.prototype.string = function() {
return new XString(this.toString());
};
XNodeSet.prototype.stringValue = function() {
return this.toString();
};
XNodeSet.prototype.number = function() {
return new XNumber(this.string());
};
XNodeSet.prototype.numberValue = function() {
return Number(this.string());
};
XNodeSet.prototype.bool = function() {
return new XBoolean(this.booleanValue());
};
XNodeSet.prototype.booleanValue = function() {
return !!this.size;
};
XNodeSet.prototype.nodeset = function() {
return this;
};
XNodeSet.prototype.stringForNode = function(n) {
if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/ ||
n.nodeType == 1 /*Node.ELEMENT_NODE */ ||
n.nodeType === 11 /*Node.DOCUMENT_FRAGMENT*/) {
return this.stringForContainerNode(n);
}
if (n.nodeType === 2 /* Node.ATTRIBUTE_NODE */) {
return n.value || n.nodeValue;
}
if (n.isNamespaceNode) {
return n.namespace;
}
return n.nodeValue;
};
XNodeSet.prototype.stringForContainerNode = function(n) {
var s = "";
for (var n2 = n.firstChild; n2 != null; n2 = n2.nextSibling) {
var nt = n2.nodeType;
// Element, Text, CDATA, Document, Document Fragment
if (nt === 1 || nt === 3 || nt === 4 || nt === 9 || nt === 11) {
s += this.stringForNode(n2);
}
}
return s;
};
XNodeSet.prototype.buildTree = function () {
if (!this.tree && this.nodes.length) {
this.tree = new AVLTree(this.nodes[0]);
for (var i = 1; i < this.nodes.length; i += 1) {
this.tree.add(this.nodes[i]);
}
}
return this.tree;
};
XNodeSet.prototype.first = function() {
var p = this.buildTree();
if (p == null) {
return null;
}
while (p.left != null) {
p = p.left;
}
return p.node;
};
XNodeSet.prototype.add = function(n) {
for (var i = 0; i < this.nodes.length; i += 1) {
if (n === this.nodes[i]) {
return;
}
}
this.tree = null;
this.nodes.push(n);
this.size += 1;
};
XNodeSet.prototype.addArray = function(ns) {
for (var i = 0; i < ns.length; i += 1) {
this.add(ns[i]);
}
};
/**
* Returns an array of the node set's contents in document order
*/
XNodeSet.prototype.toArray = function() {
var a = [];
this.toArrayRec(this.buildTree(), a);
return a;
};
XNodeSet.prototype.toArrayRec = function(t, a) {
if (t != null) {
this.toArrayRec(t.left, a);
a.push(t.node);
this.toArrayRec(t.right, a);
}
};
/**
* Returns an array of the node set's contents in arbitrary order
*/
XNodeSet.prototype.toUnsortedArray = function () {
return this.nodes.slice();
};
XNodeSet.prototype.compareWithString = function(r, o) {
var a = this.toUnsortedArray();
for (var i = 0; i < a.length; i++) {
var n = a[i];
var l = new XString(this.stringForNode(n));
var res = o(l, r);
if (res.booleanValue()) {
return res;
}
}
return new XBoolean(false);
};
XNodeSet.prototype.compareWithNumber = function(r, o) {
var a = this.toUnsortedArray();
for (var i = 0; i < a.length; i++) {
var n = a[i];
var l = new XNumber(this.stringForNode(n));
var res = o(l, r);
if (res.booleanValue()) {
return res;
}
}
return new XBoolean(false);
};
XNodeSet.prototype.compareWithBoolean = function(r, o) {
return o(this.bool(), r);
};
XNodeSet.prototype.compareWithNodeSet = function(r, o) {
var arr = this.toUnsortedArray();
var oInvert = function (lop, rop) { return o(rop, lop); };
for (var i = 0; i < arr.length; i++) {
var l = new XString(this.stringForNode(arr[i]));
var res = r.compareWithString(l, oInvert);
if (res.booleanValue()) {
return res;
}
}
return new XBoolean(false);
};
XNodeSet.prototype.equals = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithString(r, Operators.equals);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.equals);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.equals);
}
return this.compareWithNodeSet(r, Operators.equals);
};
XNodeSet.prototype.notequal = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithString(r, Operators.notequal);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.notequal);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.notequal);
}
return this.compareWithNodeSet(r, Operators.notequal);
};
XNodeSet.prototype.lessthan = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithNumber(r.number(), Operators.lessthan);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.lessthan);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.lessthan);
}
return this.compareWithNodeSet(r, Operators.lessthan);
};
XNodeSet.prototype.greaterthan = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithNumber(r.number(), Operators.greaterthan);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.greaterthan);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.greaterthan);
}
return this.compareWithNodeSet(r, Operators.greaterthan);
};
XNodeSet.prototype.lessthanorequal = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithNumber(r.number(), Operators.lessthanorequal);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.lessthanorequal);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.lessthanorequal);
}
return this.compareWithNodeSet(r, Operators.lessthanorequal);
};
XNodeSet.prototype.greaterthanorequal = function(r) {
if (Utilities.instance_of(r, XString)) {
return this.compareWithNumber(r.number(), Operators.greaterthanorequal);
}
if (Utilities.instance_of(r, XNumber)) {
return this.compareWithNumber(r, Operators.greaterthanorequal);
}
if (Utilities.instance_of(r, XBoolean)) {
return this.compareWithBoolean(r, Operators.greaterthanorequal);
}
return this.compareWithNodeSet(r, Operators.greaterthanorequal);
};
XNodeSet.prototype.union = function(r) {
var ns = new XNodeSet();
ns.addArray(this.toUnsortedArray());
ns.addArray(r.toUnsortedArray());
return ns;
};
// XPathNamespace ////////////////////////////////////////////////////////////
XPathNamespace.prototype = new Object();
XPathNamespace.prototype.constructor = XPathNamespace;
XPathNamespace.superclass = Object.prototype;
function XPathNamespace(pre, ns, p) {
this.isXPathNamespace = true;
this.ownerDocument = p.ownerDocument;
this.nodeName = "#namespace";
this.prefix = pre;
this.localName = pre;
this.namespaceURI = ns;
this.nodeValue = ns;
this.ownerElement = p;
this.nodeType = XPathNamespace.XPATH_NAMESPACE_NODE;
}
XPathNamespace.prototype.toString = function() {
return "{ \"" + this.prefix + "\", \"" + this.namespaceURI + "\" }";
};
// Operators /////////////////////////////////////////////////////////////////
var Operators = new Object();
Operators.equals = function(l, r) {
return l.equals(r);
};
Operators.notequal = function(l, r) {
return l.notequal(r);
};
Operators.lessthan = function(l, r) {
return l.lessthan(r);
};
Operators.greaterthan = function(l, r) {
return l.greaterthan(r);
};
Operators.lessthanorequal = function(l, r) {
return l.lessthanorequal(r);
};
Operators.greaterthanorequal = function(l, r) {
return l.greaterthanorequal(r);
};
// XPathContext //////////////////////////////////////////////////////////////
XPathContext.prototype = new Object();
XPathContext.prototype.constructor = XPathContext;
XPathContext.superclass = Object.prototype;
function XPathContext(vr, nr, fr) {
this.variableResolver = vr != null ? vr : new VariableResolver();
this.namespaceResolver = nr != null ? nr : new NamespaceResolver();
this.functionResolver = fr != null ? fr : new FunctionResolver();
}
// VariableResolver //////////////////////////////////////////////////////////
VariableResolver.prototype = new Object();
VariableResolver.prototype.constructor = VariableResolver;
VariableResolver.superclass = Object.prototype;
function VariableResolver() {
}
VariableResolver.prototype.getVariable = function(ln, ns) {
return null;
};
// FunctionResolver //////////////////////////////////////////////////////////
FunctionResolver.prototype = new Object();
FunctionResolver.prototype.constructor = FunctionResolver;
FunctionResolver.superclass = Object.prototype;
function FunctionResolver(thisArg) {
this.thisArg = thisArg != null ? thisArg : Functions;
this.functions = new Object();
this.addStandardFunctions();
}
FunctionResolver.prototype.addStandardFunctions = function() {
this.functions["{}last"] = Functions.last;
this.functions["{}position"] = Functions.position;
this.functions["{}count"] = Functions.count;
this.functions["{}id"] = Functions.id;
this.functions["{}local-name"] = Functions.localName;
this.functions["{}namespace-uri"] = Functions.namespaceURI;
this.functions["{}name"] = Functions.name;
this.functions["{}string"] = Functions.string;
this.functions["{}concat"] = Functions.concat;
this.functions["{}starts-with"] = Functions.startsWith;
this.functions["{}contains"] = Functions.contains;
this.functions["{}substring-before"] = Functions.substringBefore;
this.functions["{}substring-after"] = Functions.substringAfter;
this.functions["{}substring"] = Functions.substring;
this.functions["{}string-length"] = Functions.stringLength;
this.functions["{}normalize-space"] = Functions.normalizeSpace;
this.functions["{}translate"] = Functions.translate;
this.functions["{}boolean"] = Functions.boolean_;
this.functions["{}not"] = Functions.not;
this.functions["{}true"] = Functions.true_;
this.functions["{}false"] = Functions.false_;
this.functions["{}lang"] = Functions.lang;
this.functions["{}number"] = Functions.number;
this.functions["{}sum"] = Functions.sum;
this.functions["{}floor"] = Functions.floor;
this.functions["{}ceiling"] = Functions.ceiling;
this.functions["{}round"] = Functions.round;
};
FunctionResolver.prototype.addFunction = function(ns, ln, f) {
this.functions["{" + ns + "}" + ln] = f;
};
FunctionResolver.getFunctionFromContext = function(qName, context) {
var parts = Utilities.resolveQName(qName, context.namespaceResolver, context.contextNode, false);
if (parts[0] === null) {
throw new Error("Cannot resolve QName " + name);
}
return context.functionResolver.getFunction(parts[1], parts[0]);
};
FunctionResolver.prototype.getFunction = function(localName, namespace) {
return this.functions["{" + namespace + "}" + localName];
};
// NamespaceResolver /////////////////////////////////////////////////////////
NamespaceResolver.prototype = new Object();
NamespaceResolver.prototype.constructor = NamespaceResolver;
NamespaceResolver.superclass = Object.prototype;
function NamespaceResolver() {
}
NamespaceResolver.prototype.getNamespace = function(prefix, n) {
if (prefix == "xml") {
return XPath.XML_NAMESPACE_URI;
} else if (prefix == "xmlns") {
return XPath.XMLNS_NAMESPACE_URI;
}
if (n.nodeType == 9 /*Node.DOCUMENT_NODE*/) {
n = n.documentElement;
} else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
n = PathExpr.prototype.getOwnerElement(n);
} else if (n.nodeType != 1 /*Node.ELEMENT_NODE*/) {
n = n.parentNode;
}
while (n != null && n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
var nnm = n.attributes;
for (var i = 0; i < nnm.length; i++) {
var a = nnm.item(i);
var aname = a.name || a.nodeName;
if ((aname === "xmlns" && prefix === "")
|| aname === "xmlns:" + prefix) {
return String(a.value || a.nodeValue);
}
}
n = n.parentNode;
}
return null;
};
// Functions /////////////////////////////////////////////////////////////////
var Functions = new Object();
Functions.last = function() {
var c = arguments[0];
if (arguments.length != 1) {
throw new Error("Function last expects ()");
}
return new XNumber(c.contextSize);
};
Functions.position = function() {
var c = arguments[0];
if (arguments.length != 1) {
throw new Error("Function position expects ()");
}
return new XNumber(c.contextPosition);
};
Functions.count = function() {
var c = arguments[0];
var ns;
if (arguments.length != 2 || !Utilities.instance_of(ns = arguments[1].evaluate(c), XNodeSet)) {
throw new Error("Function count expects (node-set)");
}
return new XNumber(ns.size);
};
Functions.id = function() {
var c = arguments[0];
var id;
if (arguments.length != 2) {
throw new Error("Function id expects (object)");
}
id = arguments[1].evaluate(c);
if (Utilities.instance_of(id, XNodeSet)) {
id = id.toArray().join(" ");
} else {
id = id.stringValue();
}
var ids = id.split(/[\x0d\x0a\x09\x20]+/);
var count = 0;
var ns = new XNodeSet();
var doc = c.contextNode.nodeType == 9 /*Node.DOCUMENT_NODE*/
? c.contextNode
: c.contextNode.ownerDocument;
for (var i = 0; i < ids.length; i++) {
var n;
if (doc.getElementById) {
n = doc.getElementById(ids[i]);
} else {
n = Utilities.getElementById(doc, ids[i]);
}
if (n != null) {
ns.add(n);
count++;
}
}
return ns;
};
Functions.localName = function() {
var c = arguments[0];
var n;
if (arguments.length == 1) {
n = c.contextNode;
} else if (arguments.length == 2) {
n = arguments[1].evaluate(c).first();
} else {
throw new Error("Function local-name expects (node-set?)");
}
if (n == null) {
return new XString("");
}
return new XString(n.localName || // standard elements and attributes
n.baseName || // IE
n.target || // processing instructions
n.nodeName || // DOM1 elements
""); // fallback
};
Functions.namespaceURI = function() {
var c = arguments[0];
var n;
if (arguments.length == 1) {
n = c.contextNode;
} else if (arguments.length == 2) {
n = arguments[1].evaluate(c).first();
} else {
throw new Error("Function namespace-uri expects (node-set?)");
}
if (n == null) {
return new XString("");
}
return new XString(n.namespaceURI);
};
Functions.name = function() {
var c = arguments[0];
var n;
if (arguments.length == 1) {
n = c.contextNode;
} else if (arguments.length == 2) {
n = arguments[1].evaluate(c).first();
} else {
throw new Error("Function name expects (node-set?)");
}
if (n == null) {
return new XString("");
}
if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
return new XString(n.nodeName);
} else if (n.nodeType == 2 /*Node.ATTRIBUTE_NODE*/) {
return new XString(n.name || n.nodeName);
} else if (n.nodeType === 7 /*Node.PROCESSING_INSTRUCTION_NODE*/) {
return new XString(n.target || n.nodeName);
} else if (n.localName == null) {
return new XString("");
} else {
return new XString(n.localName);
}
};
Functions.string = function() {
var c = arguments[0];
if (arguments.length == 1) {
return new XString(XNodeSet.prototype.stringForNode(c.contextNode));
} else if (arguments.length == 2) {
return arguments[1].evaluate(c).string();
}
throw new Error("Function string expects (object?)");
};
Functions.concat = function() {
var c = arguments[0];
if (arguments.length < 3) {
throw new Error("Function concat expects (string, string, string*)");
}
var s = "";
for (var i = 1; i < arguments.length; i++) {
s += arguments[i].evaluate(c).stringValue();
}
return new XString(s);
};
Functions.startsWith = function() {
var c = arguments[0];
if (arguments.length != 3) {
throw new Error("Function startsWith expects (string, string)");
}
var s1 = arguments[1].evaluate(c).stringValue();
var s2 = arguments[2].evaluate(c).stringValue();
return new XBoolean(s1.substring(0, s2.length) == s2);
};
Functions.contains = function() {
var c = arguments[0];
if (arguments.length != 3) {
throw new Error("Function contains expects (string, string)");
}
var s1 = arguments[1].evaluate(c).stringValue();
var s2 = arguments[2].evaluate(c).stringValue();
return new XBoolean(s1.indexOf(s2) !== -1);
};
Functions.substringBefore = function() {
var c = arguments[0];
if (arguments.length != 3) {
throw new Error("Function substring-before expects (string, string)");
}
var s1 = arguments[1].evaluate(c).stringValue();
var s2 = arguments[2].evaluate(c).stringValue();
return new XString(s1.substring(0, s1.indexOf(s2)));
};
Functions.substringAfter = function() {
var c = arguments[0];
if (arguments.length != 3) {
throw new Error("Function substring-after expects (string, string)");
}
var s1 = arguments[1].evaluate(c).stringValue();
var s2 = arguments[2].evaluate(c).stringValue();
if (s2.length == 0) {
return new XString(s1);
}
var i = s1.indexOf(s2);
if (i == -1) {
return new XString("");
}
return new XString(s1.substring(i + s2.length));
};
Functions.substring = function() {
var c = arguments[0];
if (!(arguments.length == 3 || arguments.length == 4)) {
throw new Error("Function substring expects (string, number, number?)");
}
var s = arguments[1].evaluate(c).stringValue();
var n1 = Math.round(arguments[2].evaluate(c).numberValue()) - 1;
var n2 = arguments.length == 4 ? n1 + Math.round(arguments[3].evaluate(c).numberValue()) : undefined;
return new XString(s.substring(n1, n2));
};
Functions.stringLength = function() {
var c = arguments[0];
var s;
if (arguments.length == 1) {
s = XNodeSet.prototype.stringForNode(c.contextNode);
} else if (arguments.length == 2) {
s = arguments[1].evaluate(c).stringValue();
} else {
throw new Error("Function string-length expects (string?)");
}
return new XNumber(s.length);
};
Functions.normalizeSpace = function() {
var c = arguments[0];
var s;
if (arguments.length == 1) {
s = XNodeSet.prototype.stringForNode(c.contextNode);
} else if (arguments.length == 2) {
s = arguments[1].evaluate(c).stringValue();
} else {
throw new Error("Function normalize-space expects (string?)");
}
var i = 0;
var j = s.length - 1;
while (Utilities.isSpace(s.charCodeAt(j))) {
j--;
}
var t = "";
while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
i++;
}
while (i <= j) {
if (Utilities.isSpace(s.charCodeAt(i))) {
t += " ";
while (i <= j && Utilities.isSpace(s.charCodeAt(i))) {
i++;
}
} else {
t += s.charAt(i);
i++;
}
}
return new XString(t);
};
Functions.translate = function() {
var c = arguments[0];
if (arguments.length != 4) {
throw new Error("Function translate expects (string, string, string)");
}
var s1 = arguments[1].evaluate(c).stringValue();
var s2 = arguments[2].evaluate(c).stringValue();
var s3 = arguments[3].evaluate(c).stringValue();
var map = [];
for (var i = 0; i < s2.length; i++) {
var j = s2.charCodeAt(i);
if (map[j] == undefined) {
var k = i > s3.length ? "" : s3.charAt(i);
map[j] = k;
}
}
var t = "";
for (var i = 0; i < s1.length; i++) {
var c = s1.charCodeAt(i);
var r = map[c];
if (r == undefined) {
t += s1.charAt(i);
} else {
t += r;
}
}
return new XString(t);
};
Functions.boolean_ = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function boolean expects (object)");
}
return arguments[1].evaluate(c).bool();
};
Functions.not = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function not expects (object)");
}
return arguments[1].evaluate(c).bool().not();
};
Functions.true_ = function() {
if (arguments.length != 1) {
throw new Error("Function true expects ()");
}
return new XBoolean(true);
};
Functions.false_ = function() {
if (arguments.length != 1) {
throw new Error("Function false expects ()");
}
return new XBoolean(false);
};
Functions.lang = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function lang expects (string)");
}
var lang;
for (var n = c.contextNode; n != null && n.nodeType != 9 /*Node.DOCUMENT_NODE*/; n = n.parentNode) {
var a = n.getAttributeNS(XPath.XML_NAMESPACE_URI, "lang");
if (a != null) {
lang = String(a);
break;
}
}
if (lang == null) {
return new XBoolean(false);
}
var s = arguments[1].evaluate(c).stringValue();
return new XBoolean(lang.substring(0, s.length) == s
&& (lang.length == s.length || lang.charAt(s.length) == '-'));
};
Functions.number = function() {
var c = arguments[0];
if (!(arguments.length == 1 || arguments.length == 2)) {
throw new Error("Function number expects (object?)");
}
if (arguments.length == 1) {
return new XNumber(XNodeSet.prototype.stringForNode(c.contextNode));
}
return arguments[1].evaluate(c).number();
};
Functions.sum = function() {
var c = arguments[0];
var ns;
if (arguments.length != 2 || !Utilities.instance_of((ns = arguments[1].evaluate(c)), XNodeSet)) {
throw new Error("Function sum expects (node-set)");
}
ns = ns.toUnsortedArray();
var n = 0;
for (var i = 0; i < ns.length; i++) {
n += new XNumber(XNodeSet.prototype.stringForNode(ns[i])).numberValue();
}
return new XNumber(n);
};
Functions.floor = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function floor expects (number)");
}
return new XNumber(Math.floor(arguments[1].evaluate(c).numberValue()));
};
Functions.ceiling = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function ceiling expects (number)");
}
return new XNumber(Math.ceil(arguments[1].evaluate(c).numberValue()));
};
Functions.round = function() {
var c = arguments[0];
if (arguments.length != 2) {
throw new Error("Function round expects (number)");
}
return new XNumber(Math.round(arguments[1].evaluate(c).numberValue()));
};
// Utilities /////////////////////////////////////////////////////////////////
var Utilities = new Object();
Utilities.isAttribute = function (val) {
return val && (val.nodeType === 2 || val.ownerElement);
}
Utilities.splitQName = function(qn) {
var i = qn.indexOf(":");
if (i == -1) {
return [ null, qn ];
}
return [ qn.substring(0, i), qn.substring(i + 1) ];
};
Utilities.resolveQName = function(qn, nr, n, useDefault) {
var parts = Utilities.splitQName(qn);
if (parts[0] != null) {
parts[0] = nr.getNamespace(parts[0], n);
} else {
if (useDefault) {
parts[0] = nr.getNamespace("", n);
if (parts[0] == null) {
parts[0] = "";
}
} else {
parts[0] = "";
}
}
return parts;
};
Utilities.isSpace = function(c) {
return c == 0x9 || c == 0xd || c == 0xa || c == 0x20;
};
Utilities.isLetter = function(c) {
return c >= 0x0041 && c <= 0x005A ||
c >= 0x0061 && c <= 0x007A ||
c >= 0x00C0 && c <= 0x00D6 ||
c >= 0x00D8 && c <= 0x00F6 ||
c >= 0x00F8 && c <= 0x00FF ||
c >= 0x0100 && c <= 0x0131 ||
c >= 0x0134 && c <= 0x013E ||
c >= 0x0141 && c <= 0x0148 ||
c >= 0x014A && c <= 0x017E ||
c >= 0x0180 && c <= 0x01C3 ||
c >= 0x01CD && c <= 0x01F0 ||
c >= 0x01F4 && c <= 0x01F5 ||
c >= 0x01FA && c <= 0x0217 ||
c >= 0x0250 && c <= 0x02A8 ||
c >= 0x02BB && c <= 0x02C1 ||
c == 0x0386 ||
c >= 0x0388 && c <= 0x038A ||
c == 0x038C ||
c >= 0x038E && c <= 0x03A1 ||
c >= 0x03A3 && c <= 0x03CE ||
c >= 0x03D0 && c <= 0x03D6 ||
c == 0x03DA ||
c == 0x03DC ||
c == 0x03DE ||
c == 0x03E0 ||
c >= 0x03E2 && c <= 0x03F3 ||
c >= 0x0401 && c <= 0x040C ||
c >= 0x040E && c <= 0x044F ||
c >= 0x0451 && c <= 0x045C ||
c >= 0x045E && c <= 0x0481 ||
c >= 0x0490 && c <= 0x04C4 ||
c >= 0x04C7 && c <= 0x04C8 ||
c >= 0x04CB && c <= 0x04CC ||
c >= 0x04D0 && c <= 0x04EB ||
c >= 0x04EE && c <= 0x04F5 ||
c >= 0x04F8 && c <= 0x04F9 ||
c >= 0x0531 && c <= 0x0556 ||
c == 0x0559 ||
c >= 0x0561 && c <= 0x0586 ||
c >= 0x05D0 && c <= 0x05EA ||
c >= 0x05F0 && c <= 0x05F2 ||
c >= 0x0621 && c <= 0x063A ||
c >= 0x0641 && c <= 0x064A ||
c >= 0x0671 && c <= 0x06B7 ||
c >= 0x06BA && c <= 0x06BE ||
c >= 0x06C0 && c <= 0x06CE ||
c >= 0x06D0 && c <= 0x06D3 ||
c == 0x06D5 ||
c >= 0x06E5 && c <= 0x06E6 ||
c >= 0x0905 && c <= 0x0939 ||
c == 0x093D ||
c >= 0x0958 && c <= 0x0961 ||
c >= 0x0985 && c <= 0x098C ||
c >= 0x098F && c <= 0x0990 ||
c >= 0x0993 && c <= 0x09A8 ||
c >= 0x09AA && c <= 0x09B0 ||
c == 0x09B2 ||
c >= 0x09B6 && c <= 0x09B9 ||
c >= 0x09DC && c <= 0x09DD ||
c >= 0x09DF && c <= 0x09E1 ||
c >= 0x09F0 && c <= 0x09F1 ||
c >= 0x0A05 && c <= 0x0A0A ||
c >= 0x0A0F && c <= 0x0A10 ||
c >= 0x0A13 && c <= 0x0A28 ||
c >= 0x0A2A && c <= 0x0A30 ||
c >= 0x0A32 && c <= 0x0A33 ||
c >= 0x0A35 && c <= 0x0A36 ||
c >= 0x0A38 && c <= 0x0A39 ||
c >= 0x0A59 && c <= 0x0A5C ||
c == 0x0A5E ||
c >= 0x0A72 && c <= 0x0A74 ||
c >= 0x0A85 && c <= 0x0A8B ||
c == 0x0A8D ||
c >= 0x0A8F && c <= 0x0A91 ||
c >= 0x0A93 && c <= 0x0AA8 ||
c >= 0x0AAA && c <= 0x0AB0 ||
c >= 0x0AB2 && c <= 0x0AB3 ||
c >= 0x0AB5 && c <= 0x0AB9 ||
c == 0x0ABD ||
c == 0x0AE0 ||
c >= 0x0B05 && c <= 0x0B0C ||
c >= 0x0B0F && c <= 0x0B10 ||
c >= 0x0B13 && c <= 0x0B28 ||
c >= 0x0B2A && c <= 0x0B30 ||
c >= 0x0B32 && c <= 0x0B33 ||
c >= 0x0B36 && c <= 0x0B39 ||
c == 0x0B3D ||
c >= 0x0B5C && c <= 0x0B5D ||
c >= 0x0B5F && c <= 0x0B61 ||
c >= 0x0B85 && c <= 0x0B8A ||
c >= 0x0B8E && c <= 0x0B90 ||
c >= 0x0B92 && c <= 0x0B95 ||
c >= 0x0B99 && c <= 0x0B9A ||
c == 0x0B9C ||
c >= 0x0B9E && c <= 0x0B9F ||
c >= 0x0BA3 && c <= 0x0BA4 ||
c >= 0x0BA8 && c <= 0x0BAA ||
c >= 0x0BAE && c <= 0x0BB5 ||
c >= 0x0BB7 && c <= 0x0BB9 ||
c >= 0x0C05 && c <= 0x0C0C ||
c >= 0x0C0E && c <= 0x0C10 ||
c >= 0x0C12 && c <= 0x0C28 ||
c >= 0x0C2A && c <= 0x0C33 ||
c >= 0x0C35 && c <= 0x0C39 ||
c >= 0x0C60 && c <= 0x0C61 ||
c >= 0x0C85 && c <= 0x0C8C ||
c >= 0x0C8E && c <= 0x0C90 ||
c >= 0x0C92 && c <= 0x0CA8 ||
c >= 0x0CAA && c <= 0x0CB3 ||
c >= 0x0CB5 && c <= 0x0CB9 ||
c == 0x0CDE ||
c >= 0x0CE0 && c <= 0x0CE1 ||
c >= 0x0D05 && c <= 0x0D0C ||
c >= 0x0D0E && c <= 0x0D10 ||
c >= 0x0D12 && c <= 0x0D28 ||
c >= 0x0D2A && c <= 0x0D39 ||
c >= 0x0D60 && c <= 0x0D61 ||
c >= 0x0E01 && c <= 0x0E2E ||
c == 0x0E30 ||
c >= 0x0E32 && c <= 0x0E33 ||
c >= 0x0E40 && c <= 0x0E45 ||
c >= 0x0E81 && c <= 0x0E82 ||
c == 0x0E84 ||
c >= 0x0E87 && c <= 0x0E88 ||
c == 0x0E8A ||
c == 0x0E8D ||
c >= 0x0E94 && c <= 0x0E97 ||
c >= 0x0E99 && c <= 0x0E9F ||
c >= 0x0EA1 && c <= 0x0EA3 ||
c == 0x0EA5 ||
c == 0x0EA7 ||
c >= 0x0EAA && c <= 0x0EAB ||
c >= 0x0EAD && c <= 0x0EAE ||
c == 0x0EB0 ||
c >= 0x0EB2 && c <= 0x0EB3 ||
c == 0x0EBD ||
c >= 0x0EC0 && c <= 0x0EC4 ||
c >= 0x0F40 && c <= 0x0F47 ||
c >= 0x0F49 && c <= 0x0F69 ||
c >= 0x10A0 && c <= 0x10C5 ||
c >= 0x10D0 && c <= 0x10F6 ||
c == 0x1100 ||
c >= 0x1102 && c <= 0x1103 ||
c >= 0x1105 && c <= 0x1107 ||
c == 0x1109 ||
c >= 0x110B && c <= 0x110C ||
c >= 0x110E && c <= 0x1112 ||
c == 0x113C ||
c == 0x113E ||
c == 0x1140 ||
c == 0x114C ||
c == 0x114E ||
c == 0x1150 ||
c >= 0x1154 && c <= 0x1155 ||
c == 0x1159 ||
c >= 0x115F && c <= 0x1161 ||
c == 0x1163 ||
c == 0x1165 ||
c == 0x1167 ||
c == 0x1169 ||
c >= 0x116D && c <= 0x116E ||
c >= 0x1172 && c <= 0x1173 ||
c == 0x1175 ||
c == 0x119E ||
c == 0x11A8 ||
c == 0x11AB ||
c >= 0x11AE && c <= 0x11AF ||
c >= 0x11B7 && c <= 0x11B8 ||
c == 0x11BA ||
c >= 0x11BC && c <= 0x11C2 ||
c == 0x11EB ||
c == 0x11F0 ||
c == 0x11F9 ||
c >= 0x1E00 && c <= 0x1E9B ||
c >= 0x1EA0 && c <= 0x1EF9 ||
c >= 0x1F00 && c <= 0x1F15 ||
c >= 0x1F18 && c <= 0x1F1D ||
c >= 0x1F20 && c <= 0x1F45 ||
c >= 0x1F48 && c <= 0x1F4D ||
c >= 0x1F50 && c <= 0x1F57 ||
c == 0x1F59 ||
c == 0x1F5B ||
c == 0x1F5D ||
c >= 0x1F5F && c <= 0x1F7D ||
c >= 0x1F80 && c <= 0x1FB4 ||
c >= 0x1FB6 && c <= 0x1FBC ||
c == 0x1FBE ||
c >= 0x1FC2 && c <= 0x1FC4 ||
c >= 0x1FC6 && c <= 0x1FCC ||
c >= 0x1FD0 && c <= 0x1FD3 ||
c >= 0x1FD6 && c <= 0x1FDB ||
c >= 0x1FE0 && c <= 0x1FEC ||
c >= 0x1FF2 && c <= 0x1FF4 ||
c >= 0x1FF6 && c <= 0x1FFC ||
c == 0x2126 ||
c >= 0x212A && c <= 0x212B ||
c == 0x212E ||
c >= 0x2180 && c <= 0x2182 ||
c >= 0x3041 && c <= 0x3094 ||
c >= 0x30A1 && c <= 0x30FA ||
c >= 0x3105 && c <= 0x312C ||
c >= 0xAC00 && c <= 0xD7A3 ||
c >= 0x4E00 && c <= 0x9FA5 ||
c == 0x3007 ||
c >= 0x3021 && c <= 0x3029;
};
Utilities.isNCNameChar = function(c) {
return c >= 0x0030 && c <= 0x0039
|| c >= 0x0660 && c <= 0x0669
|| c >= 0x06F0 && c <= 0x06F9
|| c >= 0x0966 && c <= 0x096F
|| c >= 0x09E6 && c <= 0x09EF
|| c >= 0x0A66 && c <= 0x0A6F
|| c >= 0x0AE6 && c <= 0x0AEF
|| c >= 0x0B66 && c <= 0x0B6F
|| c >= 0x0BE7 && c <= 0x0BEF
|| c >= 0x0C66 && c <= 0x0C6F
|| c >= 0x0CE6 && c <= 0x0CEF
|| c >= 0x0D66 && c <= 0x0D6F
|| c >= 0x0E50 && c <= 0x0E59
|| c >= 0x0ED0 && c <= 0x0ED9
|| c >= 0x0F20 && c <= 0x0F29
|| c == 0x002E
|| c == 0x002D
|| c == 0x005F
|| Utilities.isLetter(c)
|| c >= 0x0300 && c <= 0x0345
|| c >= 0x0360 && c <= 0x0361
|| c >= 0x0483 && c <= 0x0486
|| c >= 0x0591 && c <= 0x05A1
|| c >= 0x05A3 && c <= 0x05B9
|| c >= 0x05BB && c <= 0x05BD
|| c == 0x05BF
|| c >= 0x05C1 && c <= 0x05C2
|| c == 0x05C4
|| c >= 0x064B && c <= 0x0652
|| c == 0x0670
|| c >= 0x06D6 && c <= 0x06DC
|| c >= 0x06DD && c <= 0x06DF
|| c >= 0x06E0 && c <= 0x06E4
|| c >= 0x06E7 && c <= 0x06E8
|| c >= 0x06EA && c <= 0x06ED
|| c >= 0x0901 && c <= 0x0903
|| c == 0x093C
|| c >= 0x093E && c <= 0x094C
|| c == 0x094D
|| c >= 0x0951 && c <= 0x0954
|| c >= 0x0962 && c <= 0x0963
|| c >= 0x0981 && c <= 0x0983
|| c == 0x09BC
|| c == 0x09BE
|| c == 0x09BF
|| c >= 0x09C0 && c <= 0x09C4
|| c >= 0x09C7 && c <= 0x09C8
|| c >= 0x09CB && c <= 0x09CD
|| c == 0x09D7
|| c >= 0x09E2 && c <= 0x09E3
|| c == 0x0A02
|| c == 0x0A3C
|| c == 0x0A3E
|| c == 0x0A3F
|| c >= 0x0A40 && c <= 0x0A42
|| c >= 0x0A47 && c <= 0x0A48
|| c >= 0x0A4B && c <= 0x0A4D
|| c >= 0x0A70 && c <= 0x0A71
|| c >= 0x0A81 && c <= 0x0A83
|| c == 0x0ABC
|| c >= 0x0ABE && c <= 0x0AC5
|| c >= 0x0AC7 && c <= 0x0AC9
|| c >= 0x0ACB && c <= 0x0ACD
|| c >= 0x0B01 && c <= 0x0B03
|| c == 0x0B3C
|| c >= 0x0B3E && c <= 0x0B43
|| c >= 0x0B47 && c <= 0x0B48
|| c >= 0x0B4B && c <= 0x0B4D
|| c >= 0x0B56 && c <= 0x0B57
|| c >= 0x0B82 && c <= 0x0B83
|| c >= 0x0BBE && c <= 0x0BC2
|| c >= 0x0BC6 && c <= 0x0BC8
|| c >= 0x0BCA && c <= 0x0BCD
|| c == 0x0BD7
|| c >= 0x0C01 && c <= 0x0C03
|| c >= 0x0C3E && c <= 0x0C44
|| c >= 0x0C46 && c <= 0x0C48
|| c >= 0x0C4A && c <= 0x0C4D
|| c >= 0x0C55 && c <= 0x0C56
|| c >= 0x0C82 && c <= 0x0C83
|| c >= 0x0CBE && c <= 0x0CC4
|| c >= 0x0CC6 && c <= 0x0CC8
|| c >= 0x0CCA && c <= 0x0CCD
|| c >= 0x0CD5 && c <= 0x0CD6
|| c >= 0x0D02 && c <= 0x0D03
|| c >= 0x0D3E && c <= 0x0D43
|| c >= 0x0D46 && c <= 0x0D48
|| c >= 0x0D4A && c <= 0x0D4D
|| c == 0x0D57
|| c == 0x0E31
|| c >= 0x0E34 && c <= 0x0E3A
|| c >= 0x0E47 && c <= 0x0E4E
|| c == 0x0EB1
|| c >= 0x0EB4 && c <= 0x0EB9
|| c >= 0x0EBB && c <= 0x0EBC
|| c >= 0x0EC8 && c <= 0x0ECD
|| c >= 0x0F18 && c <= 0x0F19
|| c == 0x0F35
|| c == 0x0F37
|| c == 0x0F39
|| c == 0x0F3E
|| c == 0x0F3F
|| c >= 0x0F71 && c <= 0x0F84
|| c >= 0x0F86 && c <= 0x0F8B
|| c >= 0x0F90 && c <= 0x0F95
|| c == 0x0F97
|| c >= 0x0F99 && c <= 0x0FAD
|| c >= 0x0FB1 && c <= 0x0FB7
|| c == 0x0FB9
|| c >= 0x20D0 && c <= 0x20DC
|| c == 0x20E1
|| c >= 0x302A && c <= 0x302F
|| c == 0x3099
|| c == 0x309A
|| c == 0x00B7
|| c == 0x02D0
|| c == 0x02D1
|| c == 0x0387
|| c == 0x0640
|| c == 0x0E46
|| c == 0x0EC6
|| c == 0x3005
|| c >= 0x3031 && c <= 0x3035
|| c >= 0x309D && c <= 0x309E
|| c >= 0x30FC && c <= 0x30FE;
};
Utilities.coalesceText = function(n) {
for (var m = n.firstChild; m != null; m = m.nextSibling) {
if (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) {
var s = m.nodeValue;
var first = m;
m = m.nextSibling;
while (m != null && (m.nodeType == 3 /*Node.TEXT_NODE*/ || m.nodeType == 4 /*Node.CDATA_SECTION_NODE*/)) {
s += m.nodeValue;
var del = m;
m = m.nextSibling;
del.parentNode.removeChild(del);
}
if (first.nodeType == 4 /*Node.CDATA_SECTION_NODE*/) {
var p = first.parentNode;
if (first.nextSibling == null) {
p.removeChild(first);
p.appendChild(p.ownerDocument.createTextNode(s));
} else {
var next = first.nextSibling;
p.removeChild(first);
p.insertBefore(p.ownerDocument.createTextNode(s), next);
}
} else {
first.nodeValue = s;
}
if (m == null) {
break;
}
} else if (m.nodeType == 1 /*Node.ELEMENT_NODE*/) {
Utilities.coalesceText(m);
}
}
};
Utilities.instance_of = function(o, c) {
while (o != null) {
if (o.constructor === c) {
return true;
}
if (o === Object) {
return false;
}
o = o.constructor.superclass;
}
return false;
};
Utilities.getElementById = function(n, id) {
// Note that this does not check the DTD to check for actual
// attributes of type ID, so this may be a bit wrong.
if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) {
if (n.getAttribute("id") == id
|| n.getAttributeNS(null, "id") == id) {
return n;
}
}
for (var m = n.firstChild; m != null; m = m.nextSibling) {
var res = Utilities.getElementById(m, id);
if (res != null) {
return res;
}
}
return null;
};
// XPathException ////////////////////////////////////////////////////////////
var XPathException = (function () {
function getMessage(code, exception) {
var msg = exception ? ": " + exception.toString() : "";
switch (code) {
case XPathException.INVALID_EXPRESSION_ERR:
return "Invalid expression" + msg;
case XPathException.TYPE_ERR:
return "Type error" + msg;
}
return null;
}
function XPathException(code, error, message) {
var err = Error.call(this, getMessage(code, error) || message);
err.code = code;
err.exception = error;
return err;
}
XPathException.prototype = Object.create(Error.prototype);
XPathException.prototype.constructor = XPathException;
XPathException.superclass = Error;
XPathException.prototype.toString = function() {
return this.message;
};
XPathException.fromMessage = function(message, error) {
return new XPathException(null, error, message);
};
XPathException.INVALID_EXPRESSION_ERR = 51;
XPathException.TYPE_ERR = 52;
return XPathException;
})();
// XPathExpression ///////////////////////////////////////////////////////////
XPathExpression.prototype = {};
XPathExpression.prototype.constructor = XPathExpression;
XPathExpression.superclass = Object.prototype;
function XPathExpression(e, r, p) {
this.xpath = p.parse(e);
this.context = new XPathContext();
this.context.namespaceResolver = new XPathNSResolverWrapper(r);
}
XPathExpression.prototype.evaluate = function(n, t, res) {
this.context.expressionContextNode = n;
var result = this.xpath.evaluate(this.context);
return new XPathResult(result, t);
}
// XPathNSResolverWrapper ////////////////////////////////////////////////////
XPathNSResolverWrapper.prototype = {};
XPathNSResolverWrapper.prototype.constructor = XPathNSResolverWrapper;
XPathNSResolverWrapper.superclass = Object.prototype;
function XPathNSResolverWrapper(r) {
this.xpathNSResolver = r;
}
XPathNSResolverWrapper.prototype.getNamespace = function(prefix, n) {
if (this.xpathNSResolver == null) {
return null;
}
return this.xpathNSResolver.lookupNamespaceURI(prefix);
};
// NodeXPathNSResolver ///////////////////////////////////////////////////////
NodeXPathNSResolver.prototype = {};
NodeXPathNSResolver.prototype.constructor = NodeXPathNSResolver;
NodeXPathNSResolver.superclass = Object.prototype;
function NodeXPathNSResolver(n) {
this.node = n;
this.namespaceResolver = new NamespaceResolver();
}
NodeXPathNSResolver.prototype.lookupNamespaceURI = function(prefix) {
return this.namespaceResolver.getNamespace(prefix, this.node);
};
// XPathResult ///////////////////////////////////////////////////////////////
XPathResult.prototype = {};
XPathResult.prototype.constructor = XPathResult;
XPathResult.superclass = Object.prototype;
function XPathResult(v, t) {
if (t == XPathResult.ANY_TYPE) {
if (v.constructor === XString) {
t = XPathResult.STRING_TYPE;
} else if (v.constructor === XNumber) {
t = XPathResult.NUMBER_TYPE;
} else if (v.constructor === XBoolean) {
t = XPathResult.BOOLEAN_TYPE;
} else if (v.constructor === XNodeSet) {
t = XPathResult.UNORDERED_NODE_ITERATOR_TYPE;
}
}
this.resultType = t;
switch (t) {
case XPathResult.NUMBER_TYPE:
this.numberValue = v.numberValue();
return;
case XPathResult.STRING_TYPE:
this.stringValue = v.stringValue();
return;
case XPathResult.BOOLEAN_TYPE:
this.booleanValue = v.booleanValue();
return;
case XPathResult.ANY_UNORDERED_NODE_TYPE:
case XPathResult.FIRST_ORDERED_NODE_TYPE:
if (v.constructor === XNodeSet) {
this.singleNodeValue = v.first();
return;
}
break;
case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
case XPathResult.ORDERED_NODE_ITERATOR_TYPE:
if (v.constructor === XNodeSet) {
this.invalidIteratorState = false;
this.nodes = v.toArray();
this.iteratorIndex = 0;
return;
}
break;
case XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE:
case XPathResult.ORDERED_NODE_SNAPSHOT_TYPE:
if (v.constructor === XNodeSet) {
this.nodes = v.toArray();
this.snapshotLength = this.nodes.length;
return;
}
break;
}
throw new XPathException(XPathException.TYPE_ERR);
};
XPathResult.prototype.iterateNext = function() {
if (this.resultType != XPathResult.UNORDERED_NODE_ITERATOR_TYPE
&& this.resultType != XPathResult.ORDERED_NODE_ITERATOR_TYPE) {
throw new XPathException(XPathException.TYPE_ERR);
}
return this.nodes[this.iteratorIndex++];
};
XPathResult.prototype.snapshotItem = function(i) {
if (this.resultType != XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE
&& this.resultType != XPathResult.ORDERED_NODE_SNAPSHOT_TYPE) {
throw new XPathException(XPathException.TYPE_ERR);
}
return this.nodes[i];
};
XPathResult.ANY_TYPE = 0;
XPathResult.NUMBER_TYPE = 1;
XPathResult.STRING_TYPE = 2;
XPathResult.BOOLEAN_TYPE = 3;
XPathResult.UNORDERED_NODE_ITERATOR_TYPE = 4;
XPathResult.ORDERED_NODE_ITERATOR_TYPE = 5;
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE = 6;
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7;
XPathResult.ANY_UNORDERED_NODE_TYPE = 8;
XPathResult.FIRST_ORDERED_NODE_TYPE = 9;
// DOM 3 XPath support ///////////////////////////////////////////////////////
function installDOM3XPathSupport(doc, p) {
doc.createExpression = function(e, r) {
try {
return new XPathExpression(e, r, p);
} catch (e) {
throw new XPathException(XPathException.INVALID_EXPRESSION_ERR, e);
}
};
doc.createNSResolver = function(n) {
return new NodeXPathNSResolver(n);
};
doc.evaluate = function(e, cn, r, t, res) {
if (t < 0 || t > 9) {
throw { code: 0, toString: function() { return "Request type not supported"; } };
}
return doc.createExpression(e, r, p).evaluate(cn, t, res);
};
};
// ---------------------------------------------------------------------------
// Install DOM 3 XPath support for the current document.
try {
var shouldInstall = true;
try {
if (document.implementation
&& document.implementation.hasFeature
&& document.implementation.hasFeature("XPath", null)) {
shouldInstall = false;
}
} catch (e) {
}
if (shouldInstall) {
installDOM3XPathSupport(document, new XPathParser());
}
} catch (e) {
}
// ---------------------------------------------------------------------------
// exports for node.js
installDOM3XPathSupport(exports, new XPathParser());
(function() {
var parser = new XPathParser();
var defaultNSResolver = new NamespaceResolver();
var defaultFunctionResolver = new FunctionResolver();
var defaultVariableResolver = new VariableResolver();
function makeNSResolverFromFunction(func) {
return {
getNamespace: function (prefix, node) {
var ns = func(prefix, node);
return ns || defaultNSResolver.getNamespace(prefix, node);
}
};
}
function makeNSResolverFromObject(obj) {
return makeNSResolverFromFunction(obj.getNamespace.bind(obj));
}
function makeNSResolverFromMap(map) {
return makeNSResolverFromFunction(function (prefix) {
return map[prefix];
});
}
function makeNSResolver(resolver) {
if (resolver && typeof resolver.getNamespace === "function") {
return makeNSResolverFromObject(resolver);
}
if (typeof resolver === "function") {
return makeNSResolverFromFunction(resolver);
}
// assume prefix -> uri mapping
if (typeof resolver === "object") {
return makeNSResolverFromMap(resolver);
}
return defaultNSResolver;
}
/** Converts native JavaScript types to their XPath library equivalent */
function convertValue(value) {
if (value === null ||
typeof value === "undefined" ||
value instanceof XString ||
value instanceof XBoolean ||
value instanceof XNumber ||
value instanceof XNodeSet) {
return value;
}
switch (typeof value) {
case "string": return new XString(value);
case "boolean": return new XBoolean(value);
case "number": return new XNumber(value);
}
// assume node(s)
var ns = new XNodeSet();
ns.addArray([].concat(value));
return ns;
}
function makeEvaluator(func) {
return function (context) {
var args = Array.prototype.slice.call(arguments, 1).map(function (arg) {
return arg.evaluate(context);
});
var result = func.apply(this, [].concat(context, args));
return convertValue(result);
};
}
function makeFunctionResolverFromFunction(func) {
return {
getFunction: function (name, namespace) {
var found = func(name, namespace);
if (found) {
return makeEvaluator(found);
}
return defaultFunctionResolver.getFunction(name, namespace);
}
};
}
function makeFunctionResolverFromObject(obj) {
return makeFunctionResolverFromFunction(obj.getFunction.bind(obj));
}
function makeFunctionResolverFromMap(map) {
return makeFunctionResolverFromFunction(function (name) {
return map[name];
});
}
function makeFunctionResolver(resolver) {
if (resolver && typeof resolver.getFunction === "function") {
return makeFunctionResolverFromObject(resolver);
}
if (typeof resolver === "function") {
return makeFunctionResolverFromFunction(resolver);
}
// assume map
if (typeof resolver === "object") {
return makeFunctionResolverFromMap(resolver);
}
return defaultFunctionResolver;
}
function makeVariableResolverFromFunction(func) {
return {
getVariable: function (name, namespace) {
var value = func(name, namespace);
return convertValue(value);
}
};
}
function makeVariableResolver(resolver) {
if (resolver) {
if (typeof resolver.getVariable === "function") {
return makeVariableResolverFromFunction(resolver.getVariable.bind(resolver));
}
if (typeof resolver === "function") {
return makeVariableResolverFromFunction(resolver);
}
// assume map
if (typeof resolver === "object") {
return makeVariableResolverFromFunction(function (name) {
return resolver[name];
});
}
}
return defaultVariableResolver;
}
function makeContext(options) {
var context = new XPathContext();
if (options) {
context.namespaceResolver = makeNSResolver(options.namespaces);
context.functionResolver = makeFunctionResolver(options.functions);
context.variableResolver = makeVariableResolver(options.variables);
context.expressionContextNode = options.node;
} else {
context.namespaceResolver = defaultNSResolver;
}
return context;
}
function evaluate(parsedExpression, options) {
var context = makeContext(options);
return parsedExpression.evaluate(context);
}
var evaluatorPrototype = {
evaluate: function (options) {
return evaluate(this.expression, options);
}
,evaluateNumber: function (options) {
return this.evaluate(options).numberValue();
}
,evaluateString: function (options) {
return this.evaluate(options).stringValue();
}
,evaluateBoolean: function (options) {
return this.evaluate(options).booleanValue();
}
,evaluateNodeSet: function (options) {
return this.evaluate(options).nodeset();
}
,select: function (options) {
return this.evaluateNodeSet(options).toArray()
}
,select1: function (options) {
return this.select(options)[0];
}
};
function parse(xpath) {
var parsed = parser.parse(xpath);
return Object.create(evaluatorPrototype, {
expression: {
value: parsed
}
});
}
exports.parse = parse;
})();
exports.XPath = XPath;
exports.XPathParser = XPathParser;
exports.XPathResult = XPathResult;
exports.Step = Step;
exports.NodeTest = NodeTest;
exports.BarOperation = BarOperation;
exports.NamespaceResolver = NamespaceResolver;
exports.FunctionResolver = FunctionResolver;
exports.VariableResolver = VariableResolver;
exports.Utilities = Utilities;
exports.XPathContext = XPathContext;
exports.XNodeSet = XNodeSet;
exports.XBoolean = XBoolean;
exports.XString = XString;
exports.XNumber = XNumber;
// helper
exports.select = function(e, doc, single) {
return exports.selectWithResolver(e, doc, null, single);
};
exports.useNamespaces = function(mappings) {
var resolver = {
mappings: mappings || {},
lookupNamespaceURI: function(prefix) {
return this.mappings[prefix];
}
};
return function(e, doc, single) {
return exports.selectWithResolver(e, doc, resolver, single);
};
};
exports.selectWithResolver = function(e, doc, resolver, single) {
var expression = new XPathExpression(e, resolver, new XPathParser());
var type = XPathResult.ANY_TYPE;
var result = expression.evaluate(doc, type, null);
if (result.resultType == XPathResult.STRING_TYPE) {
result = result.stringValue;
}
else if (result.resultType == XPathResult.NUMBER_TYPE) {
result = result.numberValue;
}
else if (result.resultType == XPathResult.BOOLEAN_TYPE) {
result = result.booleanValue;
}
else {
result = result.nodes;
if (single) {
result = result[0];
}
}
return result;
};
exports.select1 = function(e, doc) {
return exports.select(e, doc, true);
};
// end non-node wrapper
})(xpath);
},{}],89:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:BaseSpecialCaseIdentifier');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const XsdAttributes = require('./xmlschema/xsdAttributes');
const XsdAttributeValues = require('./xmlschema/xsdAttributeValues');
const XsdNodeTypes = require('./xmlschema/xsdNodeTypes');
const XsdElements = require('./xmlschema/xsdElements');
const specialCases_NAME = Symbol();
/**
* Class representing a collection of logic to identify special cases in XML Schema that cannot be immediately
* converted to JSON Schmea without inspecting the contents of the tag or the tag's siblings. Examples:
*
* 1. A choice where the goal is really anyOf. For example:
* <xs:choice>
* <xs:sequence>
* <xs:element name='DemandingPartyInfo' type='DemandingPartyInfoType'/>
* <xs:element name='ResponsiblePartyInfo' type='DemandingPartyInfoType' minOccurs='0'/>
* <xs:element name='ArbitrationDecisionInfo' type='DemandingPartyInfoType' minOccurs='0'/>
* </xs:sequence>
* <xs:sequence>
* <xs:element name='ResponsiblePartyInfo' type='DemandingPartyInfoType'/>
* <xs:element name='ArbitrationDecisionInfo' type='DemandingPartyInfoType' minOccurs='0'/>
* </xs:sequence>
* <xs:element name='ArbitrationDecisionInfo' type='DemandingPartyInfoType'/>
* </xs:choice>
*
* 2. Sibling choice tag. For example:
* <xs:complexType name='SiblingChoince'>
* <xs:sequence>
* <xs:choice>
* <xs:element name='OptionB' type='xs:string'/>
* <xs:element name='OptionA' type='xs:string' minOccurs='0'/>
* </xs:choice>
* <xs:choice>
* <xs:element name='Option3' type='xs:string' />
* <xs:element name='Option2' type='xs:string' minOccurs='0' />
* <xs:element name='Option1' type='xs:string' minOccurs='0' />
* </xs:choice>
* </xs:sequence>
* </xs:complexType>
*
* 3. Optional sequence and/or choice tags. For example:
* <xs:choice minOccurs="0">
* <xs:element name="Option2" type="xs:string" minOccurs="0"/>
* <xs:element name="Option1" type="xs:string" minOccurs="0"/>
* </xs:choice>
*
*/
class BaseSpecialCaseIdentifier {
constructor() {
this.specialCases = [];
}
// Getters/Setters
get specialCases() {
return this[specialCases_NAME];
}
set specialCases(newSpecialCase) {
this[specialCases_NAME] = newSpecialCase;
}
addSpecialCase(specialCase, jsonschema, node) {
this.specialCases.push({
specialCase: specialCase,
jsonSchema: jsonschema,
node: node
});
}
isOptional(node, xsd, minOccursAttr) {
var minOccurs;
if (minOccursAttr == undefined) {
minOccurs = XsdFile.getAttrValue(node, XsdAttributes.MIN_OCCURS);
} else {
minOccurs = minOccursAttr;
}
return minOccurs !== undefined && minOccurs == 0;
}
isSiblingChoice(node, xsd) {
var retval = XsdFile.countChildren(node.parentNode, XsdElements.CHOICE) > 1;
return retval;
}
countNonTextNodes(nodelist) {
var count = 0;
for (let i = 0; i < nodelist.length; i++) {
if (nodelist.item(i).nodeType != XsdNodeTypes.TEXT_NODE) {
debug(`NodeType=${XsdNodeTypes.getTypeName(nodelist.item(i).nodeType)} NodeName = ${nodelist.item(i).localName}`);
count++;
}
}
return count;
}
locateNewNameType(nameTypes, childrenOfOneOfTheChoiceOptions) {
for (let nt = 0; nt < nameTypes.length; nt++) {
for (let c = 0; c < childrenOfOneOfTheChoiceOptions.length; c++) {
const node = childrenOfOneOfTheChoiceOptions[c];
const name = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const type = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
const minOccurs = XsdFile.getAttrValue(node, XsdAttributes.MIN_OCCURS);
if (nameTypes[nt].name != name && minOccurs == undefined) {
return {
name: name,
type: type
};
}
}
}
return undefined;
}
verifyPriorChoices(nameTypes, childrenOfOneOfTheChoiceOptions) {
for (let nt = 0; nt < nameTypes.length; nt++) {
let optionalPriorNameTypeFound = false;
for (let c = 0; c < childrenOfOneOfTheChoiceOptions.length; c++) {
const node = childrenOfOneOfTheChoiceOptions[c];
const name = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const type = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
const minOccurs = XsdFile.getAttrValue(node, XsdAttributes.MIN_OCCURS);
if (nameTypes[nt].name === name && nameTypes[nt].type === type && minOccurs === XsdAttributeValues.ZERO) {
optionalPriorNameTypeFound = true;
}
}
if (!optionalPriorNameTypeFound) {
return false;
}
}
return true;
}
checkNode(nameTypes, nextChoiceOption, expectedChildCount) {
var retval;
const children = this.nodeListToArray(nextChoiceOption.childNodes);
const actualChildCount = children.length;
if (actualChildCount == expectedChildCount && this.verifyPriorChoices(nameTypes, children)) {
retval = this.locateNewNameType(nameTypes, children);
}
return retval;
}
isOptionallyIncremental(nameTypes, sortedChoiceChildren, index) {
if (index == sortedChoiceChildren.length) {
return true;
}
const node = sortedChoiceChildren[index];
const checkNameType = this.checkNode(nameTypes, node, index + 1);
if (checkNameType != undefined) {
nameTypes.push(checkNameType);
return this.isOptionallyIncremental(nameTypes, sortedChoiceChildren, index + 1);
} else {
return false;
}
}
nodeListToArray(nodelist) {
var array = [];
for (let i = 0; i < nodelist.length; i++) {
if (nodelist.item(i).nodeType != XsdNodeTypes.TEXT_NODE) {
array.push(nodelist.item(i));
}
}
return array;
}
isAnyOfChoice(node, xsd) {
var retval = false;
if (node.hasChildNodes() && node.childNodes.length > 1) {
var sortedChildren = this.nodeListToArray(node.childNodes).sort((a, b) => {
const aHasNodes = a.hasChildNodes();
const bHasNodes = b.hasChildNodes();
var aNodeCount = 0;
var bNodeCount = 0;
if (aHasNodes) {
aNodeCount = a.childNodes.length;
}
if (bHasNodes) {
bNodeCount = b.childNodes.length;
}
if (aNodeCount < bNodeCount) {
return -1;
} else if (aNodeCount > bNodeCount) {
return 1;
} else {
return 0;
}
});
const firstChild = sortedChildren[0];
if (XsdFile.hasAttribute(firstChild, XsdAttributes.NAME) && XsdFile.hasAttribute(firstChild, XsdAttributes.TYPE)) {
var nameTypes = [{}];
nameTypes[0].name = XsdFile.getAttrValue(firstChild, XsdAttributes.NAME);
nameTypes[0].type = XsdFile.getAttrValue(firstChild, XsdAttributes.TYPE);
retval = this.isOptionallyIncremental(nameTypes, sortedChildren, 1);
}
}
return retval;
}
generateAnyOfChoice(jsonSchema) {
if (jsonSchema.oneOf.length == 0) {
return;
}
debug('BEFORE Generating anyOfChoice\n' + jsonSchema);
var anyOf = jsonSchema.oneOf[0];
anyOf.required.length = 0;
Object.keys(anyOf.properties).forEach(function(prop, index, array) {
debug(prop + '=' + anyOf.properties[prop]);
const newAnyOf = jsonSchema.newJsonSchemaFile();
newAnyOf.setProperty(prop, anyOf.properties[prop]);
newAnyOf.addRequired(prop);
jsonSchema.anyOf.push(newAnyOf);
});
jsonSchema.oneOf = [];
debug('AFTER Generating anyOfChoice\n' + jsonSchema);
}
fixAnyOfChoice(jsonSchema, node) {
if (jsonSchema.allOf.length != 0) {
// A sibling choice will have the siblings in the allOf array.
jsonSchema.allOf.forEach(function(choiceSchema, index, array) {
if (choiceSchema.isAnyOfChoice === true) {
this.generateAnyOfChoice(choiceSchema);
}
}, this);
} else {
this.generateAnyOfChoice(jsonSchema);
}
}
// The "Everything else is valid" SOLUTION
// 1) Push an empty schema onto anyOf. Always passes validation, as if the empty schema {}
fixOptionalChoiceTruthy(jsonSchema, node) {
debug('Fixing optional ' + XsdFile.nodeQuickDumpStr(node) + ' using a Truthy schema.');
debug('Optional choice: ' + jsonSchema.toString());
// Add an the optional part (empty schema)
var emptySchema = jsonSchema.newJsonSchemaFile();
emptySchema.description = "This truthy schema is what makes an optional <choice> optional."
jsonSchema.parent.anyOf.push(emptySchema);
debug('Parent: ' + jsonSchema.parent.toString());
}
// The "Not" SOLUTION - elimiated because allows ANYTHING not listed in the dependent properties.
// 1) push oneOf onto anyOf and create new empty oneOf array
// 2) create new 'optional' schema and also push it onto anyOf
// 3) populate optional schema allOf with a 'not' for each member of the original oneOf
fixOptionalChoiceNot(jsonSchema, node) {
debug('Fixing optional choice ' + XsdFile.nodeQuickDumpStr(node) + ' using the Not solution.');
debug('Optional choice: ' + jsonSchema.toString());
const originalOneOf = jsonSchema.newJsonSchemaFile();
originalOneOf.oneOf = jsonSchema.oneOf.slice(0);
//originalOneOf.description = 'originalOneOf';
jsonSchema.anyOf.push(originalOneOf);
const theOptionalPart = jsonSchema.newJsonSchemaFile();
//theOptionalPart.description = 'theOptionalPart';
jsonSchema.oneOf.forEach(function(option, index, array) {
const notSchema = theOptionalPart.newJsonSchemaFile();
notSchema.not = option;
debug('Pushing not schema');
theOptionalPart.allOf.push(notSchema);
});
jsonSchema.anyOf.push(theOptionalPart);
jsonSchema.oneOf = [];
//jsonSchema.description = 'This is the NOT solution';
debug('Parent: ' + jsonSchema.parent.toString());
}
// The "Property Dependency" SOLUTION
// 1) push oneOf onto anyOf and create new empty oneOf array
// 2) create new 'optional' schema and also push it onto anyOf
// 3) populate optional schema allOf with a 'not' for each member of the original oneOf
fixOptionalChoicePropertyDependency(jsonSchema, node) {
debug('Fixing optional choice ' + XsdFile.nodeQuickDumpStr(node) + ' using the Property Dependency solution.');
debug('Optional choice: ' + jsonSchema.toString());
const originalOneOf = jsonSchema.newJsonSchemaFile();
originalOneOf.oneOf = Array.from(jsonSchema.oneOf);
jsonSchema.anyOf.push(originalOneOf);
const theOptionalPart = jsonSchema.newJsonSchemaFile();
jsonSchema.oneOf.forEach(function(option, index, array) {
const dependencySchema = theOptionalPart.newJsonSchemaFile();
dependencySchema.not = option;
theOptionalPart.addPropertyDependency(option.name, option); // This needs to be checked/finished
//theOptionalPart.allOf.push(notSchema);
});
jsonSchema.anyOf.push(theOptionalPart);
jsonSchema.oneOf = [];
debug('Parent: ' + jsonSchema.parent.toString());
}
fixOptionalChoice(jsonSchema, node) {
// switch (options)
//this.fixOptionalChoiceTruthy(jsonSchema, node)
this.fixOptionalChoiceNot(jsonSchema, node)
return;
}
fixOptionalSequence(jsonSchema, node) {
debug("NOT IMPLEMENTED")
return;
}
processSpecialCases() {
while (this.specialCases.length > 0) {
const sc = this.specialCases.pop()
this[sc.specialCase](sc.jsonSchema, sc.node);
}
}
}
module.exports = BaseSpecialCaseIdentifier;
},{"./xmlschema/xsdAttributeValues":119,"./xmlschema/xsdAttributes":120,"./xmlschema/xsdElements":121,"./xmlschema/xsdFileXmlDom":122,"./xmlschema/xsdNodeTypes":123,"debug":3}],90:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:BuiltInTypeConverter');
const CONSTANTS = require('./constants');
const JSON_SCHEMA_TYPES = require('./jsonschema/jsonSchemaTypes');
const JSON_SCHEMA_FORMATS = require('./jsonschema/jsonSchemaFormats');
const JsonSchemaFile = require('./jsonschema/jsonSchemaFileDraft04');
const Options_NAME = Symbol();
/**
* Class representing a collection of XML Handler methods for converting XML Schema built-in types to JSON Schema.
* Handler methods convert XML Schema built-in simple types to JSON Schema types. Each hander minimally sets the
* JSON Schema *type* attribute to the appropriate JSON Schema built-in type. Many handlers will further restrict
* the *type* using a JSON Schmea {@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7|format},
* a regular expression, or a numeric restriction such as JSON Schema
* {@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.4\minimum} or
* {@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.4\maximum}.
*
* Please see:
* {@link http://www.w3.org/TR/xmlschema11-2/ |W3C XML Schema Definition Language (XSD) 1.1 Part 2: Datatypes} for
* more information. Section 3 {@link http://www.w3.org/TR/xmlschema11-2/#built-in-datatypes |XML Schema built-in
* Datatypes and Their Definitions} has a nice diagram showing the built-in type hierarchy. Also,
* {@link http://www.w3.org/TR/xmlschema-0/ |XML Schema Part 0: Primer Second Edition} has a
* {@link http://www.w3.org/TR/xmlschema-0/#simpleTypesTable |reference table} summarizing the XML Schema built-in types.
*/
class BuiltInTypeConverter {
constructor(params) {
if (params != undefined && params.uri != undefined) {
this.options = {
uri: params.uri,
};
} else {
this.options = {
uri: CONSTANTS.RFC_3986,
};
}
}
// Getters/Setters
get options() {
return this[Options_NAME];
}
set options(newOptions) {
this[Options_NAME] = newOptions;
}
// 3.3 Primitive Datatypes: http://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes
// *****************************************************************************************
// 3.3.1 string: http://www.w3.org/TR/xmlschema11-2/#string
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#string |XML Schema String} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema String}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
string(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
return true;
}
anyType(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
return true;
}
anySimpleType(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
return true;
}
anyAtomicType(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
return true;
}
schema(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.OBJECT;
return true;
}
/*
// 3.3.2 boolean: http://www.w3.org/TR/xmlschema11-2/#boolean
/ **
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#boolean |XML Schema Boolean} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema Boolean}.
*
* @param {Node} node - The current element in xsd beingjsonSchema.minimum converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
* /
boolean(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.BOOLEAN;
return true;
}
*/
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#boolean |XML Schema Boolean} to either a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema Boolean} or {@link http://www.w3.org/TR/xmlschema11-2/#integer JSON Schema Integer} with values limited to 0 or 1.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
boolean(node, jsonSchema, xsd) {
var booleanSchema = jsonSchema.newJsonSchemaFile();
booleanSchema.type = JSON_SCHEMA_TYPES.BOOLEAN;
var integerSchema = jsonSchema.newJsonSchemaFile();
integerSchema.type = JSON_SCHEMA_TYPES.INTEGER;
integerSchema.maximum = 1;
integerSchema.minimum = 0;
jsonSchema.oneOf.push(booleanSchema);
jsonSchema.oneOf.push(integerSchema);
return true;
}
// 3.3.3 decimal: http://www.w3.org/TR/xmlschema11-2/#decimal
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#decimal |XML Schema Decimal} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema Number}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
decimal(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.NUMBER;
return true;
}
// 3.3.4 float: http://www.w3.org/TR/xmlschema11-2/#float
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#float |XML Schema Float} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema Number}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
float(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.NUMBER;
return true;
}
// 3.3.5 double: http://www.w3.org/TR/xmlschema11-2/#double
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#double |XML Schema Double} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema Number}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
double(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.NUMBER;
return true;
}
// 3.3.6 duration: http://www.w3.org/TR/xmlschema11-2/#duration
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#duration |XML Schema Duration} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema String}
* and utilizes regex to validate the string against the XML Schema duration specification.
*
* <pre>
* jsonSchema.pattern = '^[-]?P(?!$)(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?!$)(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$';
* </pre>
* Source: {@link http://www.regexlib.com/REDetails.aspx?regexp_id=1219};
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
duration(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'^[-]?P(?!$)(?:\\d+Y)?(?:\\d+M)?(?:\\d+D)?(?:T(?!$)(?:\\d+H)?(?:\\d+M)?(?:\\d+(?:\\.\\d+)?S)?)?$';
// jsonSchema.description = 'Matches the XSD schema duration built in type as defined by http://www.w3.org/TR/xmlschema-2/#duration. Source: http://www.regexlib.com/REDetails.aspx?regexp_id=1219';
//jsonSchema.pattern = '-?P((( [0-9]+Y([0-9]+M)?([0-9]+D)?|([0-9]+M)([0-9]+D)?|([0-9]+D))(T(([0-9]+H)([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\\.[0-9]+)?S)?|([0-9]+(\\.[0-9]+)?S)))?)|(T(([0-9]+H)([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|([0-9]+M)([0-9]+(\\.[0-9]+)?S)?|([0-9]+(\\.[0-9]+)?S))))';
// jsonSchema.description = 'Source: http://www.w3.org/TR/xmlschema-2/#duration';
return true;
}
// 3.3.7 dateTime: http://www.w3.org/TR/xmlschema11-2/#dateTime
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#dateTime |XML Schema dateTime} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema String}
* and utilizes regex to validate the string against the XML Schema dateTime specification. Note XML Schema dateTime values are based on ISO 8601 whereas JSON Schema date-time values are based on RFC 3339.
* Because of this the regular expression below is used to validate dateTime values converted from XML Schema.
*
* <pre>
* jsonSchema.pattern = ^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$
* </pre>
* Source: {@link http://www.regexlib.com/REDetails.aspx?regexp_id=1219};
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
dateTime(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?|(24:00:00(\\.0+)?))(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?';
// jsonSchema.description = 'Source: http://www.w3.org/TR/xmlschema11-2/#dateTime'
return true;
}
// 3.3.8 time: http://www.w3.org/TR/xmlschema11-2/#time
time(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'(([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\\.[0-9]+)?|(24:00:00(\\.0+)?))(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?';
// jsonSchema.description = 'Source: http://www.w3.org/TR/xmlschema11-2/#time'
return true;
}
// 3.3.9 date: http://www.w3.org/TR/xmlschema11-2/#date
date(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'-?([1-9][0-9]{3,}|0[0-9]{3})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?';
// jsonSchema.description = 'Source: http://www.w3.org/TR/xmlschema11-2/#date'
return true;
}
// 3.3.10 gYearMonth: http://www.w3.org/TR/xmlschema11-2/#gYearMonth
gYearMonth(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'^(-?[0-9]+-[0-9][0-9])(Z|[+-][0-9][0-9]:[0-9][0-9])?$';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.value.GYearMonthValue.java';
return true;
}
// 3.3.11 gYear: http://www.w3.org/TR/xmlschema11-2/#gYear
gYear(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern = '^(-?[0-9]+)(Z|[+-][0-9][0-9]:[0-9][0-9])?$';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.value.GYearValue.java';
return true;
}
// 3.3.12 gMonthDay: http://www.w3.org/TR/xmlschema11-2/#gMonthDay
gMonthDay(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
'^--([0-9][0-9]-[0-9][0-9])(Z|[+-][0-9][0-9]:[0-9][0-9])?$';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.value.GMonthDayValue.java';
return true;
}
// 3.3.13 gDay: http://www.w3.org/TR/xmlschema11-2/#gDay
gDay(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern = '^---([0-9][0-9])(Z|[+-][0-9][0-9]:[0-9][0-9])?$';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.value.GDateValue.java';
return true;
}
// 3.3.14 gMonth: http://www.w3.org/TR/xmlschema11-2/#gMonth
gMonth(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern = '^--([0-9][0-9])(Z|[+-][0-9][0-9]:[0-9][0-9])?$';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.value.GMonthValue.java';
return true;
}
// 3.3.15 hexBinary: http://www.w3.org/TR/xmlschema11-2/#hexBinary
hexBinary(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern = '^([0-9a-fA-F])*$';
// jsonSchema.description = 'Hex string of any length; source: http://www.regexlib.com/REDetails.aspx?regexp_id=886 also see http://www.datypic.com/sc/xsd/t-xsd_hexBinary.html';
return true;
}
// 3.3.16 base64Binary: http://www.w3.org/TR/xmlschema11-2/#base64Binary
base64Binary(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
// Removed because it doesn't ignore spaces in base64 encoded strings. Going with just string validation for now.
// jsonSchema.pattern = '^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$';
// jsonSchema.description = 'Base64-encoded binary string; source: http://stackoverflow.com/questions/475074/regex-to-parse-or-validate-base64-data also see http://www.schemacentral.com/sc/xsd/t-xsd_base64Binary.html';
jsonSchema.contentEncoding = 'base64';
return true;
}
// 3.3.17 anyURI: http://www.w3.org/TR/xmlschema11-2/#anyURI
/**
* XML handler method to convert a {@link http://www.w3.org/TR/xmlschema11-2/#anyURI |XML Schema dateTime} to a {@link https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2 |JSON Schema String}
* and utilizes regex to validate the string against the XML Schema anyURI specification. Note XML Schema URI values are based on {@link https://tools.ietf.org/html/rfc2396|RFC2396} whereas JSON Schema URI values are based on {@link https://tools.ietf.org/html/rfc3986|RFC3986}.
* Because of this the regular expression below is used to validate dateTime values converted from XML Schema.
*
* <pre>
* jsonSchema.pattern = ^(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?\/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?$
* </pre>
* Source: {@link http://lists.xml.org/archives/xml-dev/200108/msg00891.html | Regular expression for URI matching} (28);
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
anyURI_RFC2396(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern =
"^(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?\\/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?$";
return true;
}
/**
* TODO Make this an option for the above implementation
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
anyURI_RFC3986(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.format = JSON_SCHEMA_FORMATS.URI;
return true;
}
/**
* TODO Make this an option for the above implementation
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current type from the XML schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
anyURI(node, jsonSchema, xsd) {
if (this.options.uri === CONSTANTS.RFC_3986) {
return this.anyURI_RFC3986(node, jsonSchema, xsd);
}
if (this.options.uri === CONSTANTS.RFC_2396) {
return this.anyURI_RFC2396(node, jsonSchema, xsd);
}
debug('Unknown value for options.uri [' + this.options.uri + ']');
return false;
}
// 3.3.18 QName: http://www.w3.org/TR/xmlschema11-2/#QName
QName(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the QName format.';
return true;
}
// 3.3.19 NOTATION: http://www.w3.org/TR/xmlschema11-2/#NOTATION
NOTATION(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the NOTATION format.';
return true;
}
// 3.4 Other Built-in Datatypes: http://www.w3.org/TR/xmlschema11-2/#ordinary-built-ins
// ************************************************************************************
// 3.4.1 normalizedString: http://www.w3.org/TR/xmlschema11-2/#normalizedString
normalizedString(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the normalizedString format.';
return true;
}
// 3.4.2 token: http://www.w3.org/TR/xmlschema11-2/#token
token(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the token format.';
return true;
}
// 3.4.3 language: http://www.w3.org/TR/xmlschema11-2/#language
language(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.pattern = '[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*';
// jsonSchema.description = 'Source: saxon.sourceforge.net. See net.sf.saxon.type.StringConverter.java#StringToLanguage';
return true;
}
// 3.4.4 NMTOKEN: http://www.w3.org/TR/xmlschema11-2/#NMTOKEN
NMTOKEN(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the NMTOKEN format.';
return true;
}
// 3.4.5 NMTOKENS: http://www.w3.org/TR/xmlschema11-2/#NMTOKENS
NMTOKENS(node, jsonSchema, xsd) {
var items = jsonSchema.newJsonSchemaFile();
items.type = JSON_SCHEMA_TYPES.STRING;
//items.description = 'TODO: This should have a regex applied to validate the NMTOKEN format.';
jsonSchema.items = items;
jsonSchema.type = JSON_SCHEMA_TYPES.ARRAY;
return true;
}
// 3.4.6 Name: http://www.w3.org/TR/xmlschema11-2/#Name
Name(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the Name format.';
return true;
}
// 3.4.7 NCName: http://www.w3.org/TR/xmlschema11-2/#NCName
NCName(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the NCName format.';
return true;
}
// 3.4.8 ID: http://www.w3.org/TR/xmlschema11-2/#ID
ID(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the ID format.';
return true;
}
// 3.4.9 IDREF: http://www.w3.org/TR/xmlschema11-2/#IDREF
IDREF(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the IDREF format.';
return true;
}
// 3.4.10 IDREFS: http://www.w3.org/TR/xmlschema11-2/#IDREFS
IDREFS(node, jsonSchema, xsd) {
var items = jsonSchema.newJsonSchemaFile();
items.type = JSON_SCHEMA_TYPES.STRING;
//items.description = 'TODO: This should have a regex applied to validate the IDREFS format.';
jsonSchema.items = items;
jsonSchema.type = JSON_SCHEMA_TYPES.ARRAY;
return true;
}
// 3.4.11 ENTITY: http://www.w3.org/TR/xmlschema11-2/#ENTITY
ENTITY(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.description = 'TODO: This should have a regex applied to validate the ENTITY format.';
return true;
}
// 3.4.12 ENTITIES: http://www.w3.org/TR/xmlschema11-2/#ENTITIES
ENTITIES(node, jsonSchema, xsd) {
var items = jsonSchema.newJsonSchemaFile();
items.type = JSON_SCHEMA_TYPES.STRING;
//items.description = 'TODO: This should have a regex applied to validate the ENTITIES format.';
jsonSchema.items = items;
jsonSchema.type = JSON_SCHEMA_TYPES.ARRAY;
return true;
}
// 3.4.13 integer: http://www.w3.org/TR/xmlschema11-2/#integer
integer(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
return true;
}
// 3.4.14 nonPositiveInteger: http://www.w3.org/TR/xmlschema11-2/#nonPositiveInteger
nonPositiveInteger(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.maximum = 0;
return true;
}
// 3.4.15 negativeInteger: http://www.w3.org/TR/xmlschema11-2/#negativeInteger
negativeInteger(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.maximum = 0;
jsonSchema.exclusiveMinimum = true;
return true;
}
// 3.4.16 long: http://www.w3.org/TR/xmlschema11-2/#long
long(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = -9223372036854775808;
jsonSchema.maximum = 9223372036854775807;
return true;
}
// 3.4.17 int: http://www.w3.org/TR/xmlschema11-2/#int
int(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = -2147483648;
jsonSchema.maximum = 2147483647;
return true;
}
// 3.4.18 short: http://www.w3.org/TR/xmlschema11-2/#short
short(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = -32768;
jsonSchema.maximum = 32767;
return true;
}
// 3.4.19 byte: http://www.w3.org/TR/xmlschema11-2/#byte
byte(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = -128;
jsonSchema.maximum = 127;
return true;
}
// 3.4.20 nonNegativeInteger: http://www.w3.org/TR/xmlschema11-2/#nonNegativeInteger
nonNegativeInteger(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
return true;
}
// 3.4.21 unsignedLong: http://www.w3.org/TR/xmlschema11-2/#unsignedLong
unsignedLong(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
jsonSchema.maximum = 18446744073709551615;
return true;
}
// 3.4.22 unsignedInt: http://www.w3.org/TR/xmlschema11-2/#unsignedInt
unsignedInt(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
jsonSchema.maximum = 4294967295;
return true;
}
// 3.4.23 unsignedShort: http://www.w3.org/TR/xmlschema11-2/#unsignedShort
unsignedShort(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
jsonSchema.maximum = 65535;
return true;
}
// 3.4.24 unsignedByte: http://www.w3.org/TR/xmlschema11-2/#unsignedByte
unsignedByte(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
jsonSchema.maximum = 255;
return true;
}
// 3.4.25 positiveInteger: http://www.w3.org/TR/xmlschema11-2/#positiveInteger
positiveInteger(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.INTEGER;
jsonSchema.minimum = 0;
jsonSchema.maximum = 4294967295;
jsonSchema.exclusiveMinimum = -1;
return true;
}
// 3.4.26 yearMonthDuration: http://www.w3.org/TR/xmlschema11-2/#yearMonthDuration
yearMonthDuration(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
// jsonSchema.pattern = '^[-]?P(?!$)(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?!$)(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$';
// jsonSchema.description = 'TODO: (modify) The pattern above: Matches the XSD schema duration built in type as defined by http://www.w3.org/TR/xmlschema-2/#duration. Source: http://www.regexlib.com/REDetails.aspx?regexp_id=1219';
return true;
}
// 3.4.27 dayTimeDuration: http://www.w3.org/TR/xmlschema11-2/#dayTimeDuration
dateTimeDuration(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
//jsonSchema.pattern = '^[-]?P(?!$)(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?!$)(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$';
// jsonSchema.description = 'TODO: (modify) The pattern above: Matches the XSD schema duration built in type as defined by http://www.w3.org/TR/xmlschema-2/#duration. Source: http://www.regexlib.com/REDetails.aspx?regexp_id=1219';
return true;
}
// 3.4.28 dateTimeStamp: http://www.w3.org/TR/xmlschema11-2/#dateTimeStamp
dateTimeStamp(node, jsonSchema, xsd) {
jsonSchema.type = JSON_SCHEMA_TYPES.STRING;
jsonSchema.format = JSON_SCHEMA_FORMATS.DATE_TIME;
return true;
}
}
module.exports = BuiltInTypeConverter;
},{"./constants":91,"./jsonschema/jsonSchemaFileDraft04":98,"./jsonschema/jsonSchemaFormats":101,"./jsonschema/jsonSchemaTypes":106,"debug":3}],91:[function(require,module,exports){
'use strict';
/**
* Defines general purpose constants
*
* @module Constants
*/
module.exports = {
GLOBAL_ATTRIBUTES_SCHEMA_NAME: 'globalAttributes',
RFC_2396: 'RFC2396',
RFC_3986: 'RFC3986',
SUBSCHEMA: 'SUBSCHEMA',
FILENAME: 'FILENAME',
DEFINITIONS: 'definitions',
FORWARD_REFERENCE: 'FORWARD_REFERENCE',
XML_SCHEMA_NAMESPACE: 'http://www.w3.org/2001/XMLSchema',
XML_SCHEMA_DEFAULT_NAMESPACE_NAME_XS: 'xs',
XML_SCHEMA_DEFAULT_NAMESPACE_NAME_XSD: 'xsd',
NO_NAMESPACE: 'NO_NAMESPACE',
DRAFT_04: 'draft-04',
DRAFT_06: 'draft-06',
DRAFT_07: 'draft-07'
}
},{}],92:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:ConverterDraft04');
const URI = require('urijs');
const Qname = require('./qname');
const jsonSchemaTypes = require('./jsonschema/jsonSchemaTypes');
const JsonSchemaFile = require('./jsonschema/jsonSchemaFile');
const Processor = require('./processor');
const XsdElements = require('./xmlschema/xsdElements');
const XsdAttributes = require('./xmlschema/xsdAttributes');
const XsdAttributeValues = require('./xmlschema/xsdAttributeValues');
const XsdNodeTypes = require('./xmlschema/xsdNodeTypes');
const utils = require('./utils');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const BaseSpecialCaseIdentifier = require('./baseSpecialCaseIdentifier');
const SpecialCases = require('./specialCases');
const NamespaceManager = require('./namespaceManager');
const namespaceManager_NAME = Symbol();
const specialCaseIdentifier_NAME = Symbol();
const includeTextAndCommentNodes_NAME = Symbol();
/**
* Class representing a collection of XML Handler methods for converting XML Schema elements to JSON Schema. XML
* handler methods are methods used to convert an element of the corresponding name an equiviant JSON Schema
* representation. Handlers all check the current state (i.e. thier parent node) to determine how to convert the
* node at hand. See the {@link ConverterDraft04#choice|choice} handler for a complex example.
*
* Subclasses can override any handler method to customize the conversion as needed.
*
* @see {@link ParsingState}
*/
class ConverterDraft04 extends Processor {
/**
* Constructs an instance of ConverterDraft04.
* @constructor
*/
constructor(options) {
super(options);
if (options != undefined) {
this.namespaceManager =
options.namespaceManager != undefined
? options.namespaceManager
: new NamespaceManager();
this.specialCaseIdentifier =
options.specialCaseIdentifier != undefined
? options.specialCaseIdentifier
: new BaseSpecialCaseIdentifier();
} else {
//this.namespaceManager = new NamespaceManager();
//this.specialCaseIdentifier = new BaseSpecialCaseIdentifier();
}
// The working schema is initilized as needed through XML Handlers
}
// Getters/Setters
get namespaceManager() {
return this[namespaceManager_NAME];
}
set namespaceManager(newNamespaceManager) {
this[namespaceManager_NAME] = newNamespaceManager;
}
get specialCaseIdentifier() {
return this[specialCaseIdentifier_NAME];
}
set specialCaseIdentifier(newSpecialCaseIdentifier) {
this[specialCaseIdentifier_NAME] = newSpecialCaseIdentifier;
}
get includeTextAndCommentNodes() {
return this[includeTextAndCommentNodes_NAME];
}
set includeTextAndCommentNodes(newIncludeTextAndCommentNodes) {
this[includeTextAndCommentNodes_NAME] = newIncludeTextAndCommentNodes;
}
dumpJsonSchema(jsonSchema) {
Object.keys(jsonSchema).forEach(function (prop, index, array) {
debug(prop + '=' + jsonSchema[prop]);
});
}
// Read-only properties
get builtInTypeConverter() {
return this.namespaceManager.builtInTypeConverter;
}
set builtInTypeConverter(unused) {
throw new Error('Unsupported operation');
}
/**
* Creates a namespaces for the given namespace name. This method is called from the schema XML Handler.
*
* @see {@link NamespaceManager#createNamespace|NamespaceManager.createNamespace()}
*/
initializeNamespaces(xsd) {
Object.keys(xsd.namespaces).forEach(function (namespace, index, array) {
this.namespaceManager.addNamespace(xsd.namespaces[namespace]);
}, this);
}
/**
* This method is called for each node in the XML Schema file being processed. It performs three actions
* 1) processes an ID attribute if present
* 2) calls the appropriate XML Handler method.
* 3) calls super.process() to provide detailed logging
* @param {Node} node - the current {@link https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-745549614 element} in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - the JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - the XML schema file currently being converted.
*
* @returns {Boolean} - handler methods can return false to cancel traversal of {@link XsdFile|xsd}. An XML Schema handler method
* has a common footprint and a name that corresponds to one of the XML Schema element names found in {@link module:XsdElements}.
* For example, the <choice> handler method is <pre><code>choice(node, jsonSchema, xsd)</code></pre>
*/
process(node, jsonSchema, xsd) {
const id = XsdFile.getAttrValue(node, XsdAttributes.ID);
if (id !== undefined) {
let qualifiedTypeName = new Qname(id);
this.workingJsonSchema.addAttributeProperty(
qualifiedTypeName.getLocal(),
this.createAttributeSchema(node, jsonSchema, xsd, qualifiedTypeName)
);
}
const fnName = XsdFile.getNodeName(node);
if (
(debug.enabled === true &&
node.nodeType != XsdNodeTypes.TEXT_NODE &&
node.nodeType != XsdNodeTypes.COMMENT_NODE) ||
this.includeTextAndCommentNodes === true
) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const valueAttr = XsdFile.getValueAttr(node);
debug(
'Processing [' +
fnName +
'] ' +
(nameAttr == undefined ? '' : '[' + nameAttr + ']') +
(valueAttr == undefined ? '' : '[' + valueAttr + ']')
);
}
let keepProcessing = true;
if (this[fnName] != undefined) {
keepProcessing = this[fnName](node, jsonSchema, xsd);
} else {
this.skippingUnknownNode(fnName, node, jsonSchema, xsd);
}
super.process(node, jsonSchema, xsd);
return keepProcessing;
}
skippingUnknownNode(fnName, node, jsonSchema, xsd) {
debug(`Skipping unknown node [${fnName}]`);
}
all(node, jsonSchema, xsd) {
// TODO: id, minOccurs, maxOccurs
// (TBD)
}
alternative(node, jsonSchema, xsd) {
// TODO: id, test, type, xpathDefaultNamespace
// (TBD)
return true;
}
annotation(node, jsonSchema, xsd) {
// TODO: id
// Ignore this grouping and continue processing children
return true;
}
any(node, jsonSchema, xsd) {
// TODO: id, minOccurs, maxOccurs, namespace, processContents, notNamespace, not QName
// (TBD)
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.CHOICE:
throw new Error('any() needs to be implemented within choice!');
case XsdElements.SEQUENCE:
break;
// throw new Error('any() needs to be implemented within sequence!');
case XsdElements.ALL:
throw new Error('any() needs to be implemented within all!');
case XsdElements.OPEN_CONTENT:
throw new Error('any() needs to be implemented within openContent!');
case XsdElements.DEFAULT_OPEN_CONTENT:
throw new Error(
'any() needs to be implemented within defaultOpenContent'
);
default:
throw new Error('any() called from within unexpected parsing state!');
}
return true;
}
anyAttribute(node, jsonSchema, xsd) {
// TODO: id, namespace, processContents, notNamespace, not QName
// (TBD)
return true;
}
appinfo(node, jsonSchema, xsd) {
// TODO: source
// (TBD)
return true;
}
assert(node, jsonSchema, xsd) {
// TODO: id, test, xpathDefaultNamespace
// (TBD)
return true;
}
assertion(node, jsonSchema, xsd) {
// TODO: id, test, xpathDefaultNamespace
// (TBD)
return true;
}
isBuiltInType(qualifiedTypeName) {
return this.builtInTypeConverter[qualifiedTypeName.getLocal()] != undefined;
}
/*
* A factory method to create JSON Schemas of one of the XML Schema built-in types.
*
*/
createAttributeSchema(node, xsd, qualifiedTypeName) {
const attributeJsonSchema = this.workingJsonSchema.newJsonSchemaFile();
this.builtInTypeConverter[qualifiedTypeName.getLocal()](
node,
attributeJsonSchema,
xsd
);
return attributeJsonSchema;
}
// Delete this?
createAttributeReference(typeAttr, jsonSchema, xsd) {
const refType = this.namespaceManager.getType(
typeAttr,
this.workingJsonSchema,
jsonSchema,
xsd,
false
);
return refType.get$RefToSchema(jsonSchema);
}
handleAttributeGlobal(node, jsonSchema, xsd) {
const name = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const typeName = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
// TODO: id, default, fixed, inheritable (TBD)
var attributeJsonSchema;
const fixed = XsdFile.getAttrValue(node, XsdAttributes.FIXED);
this.parsingState.pushSchema(this.workingJsonSchema);
if (typeName !== undefined) {
const qualifiedTypeName = new Qname(typeName);
attributeJsonSchema = this.namespaceManager.getGlobalAttribute(
name,
jsonSchema
);
jsonSchema
.getGlobalAttributesSchema()
.setSubSchema(name, attributeJsonSchema);
if (fixed) {
attributeJsonSchema.addEnum(fixed);
}
return this.builtInTypeConverter[qualifiedTypeName.getLocal()](
node,
attributeJsonSchema
);
} else {
// Setup the working schema and allow processing to continue for any contained simpleType or annotation nodes.
attributeJsonSchema = this.namespaceManager.getGlobalAttribute(
name,
jsonSchema
);
jsonSchema
.getGlobalAttributesSchema()
.setSubSchema(name, attributeJsonSchema);
this.workingJsonSchema = attributeJsonSchema;
}
return true;
}
handleAttributeLocal(node, jsonSchema, xsd) {
const name = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const type = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
const use = XsdFile.getAttrValue(node, XsdAttributes.USE);
// TODO: id, form, default, fixed, targetNamespace, inheritable (TBD)
var attributeJsonSchema;
this.parsingState.pushSchema(this.workingJsonSchema);
if (type !== undefined) {
const qualifiedTypeName = new Qname(type);
if (this.isBuiltInType(qualifiedTypeName)) {
attributeJsonSchema = this.createAttributeSchema(
node,
xsd,
qualifiedTypeName
);
} else {
attributeJsonSchema = this.namespaceManager.getTypeReference(
type,
this.workingJsonSchema,
jsonSchema,
xsd
);
}
this.workingJsonSchema.addAttributeProperty(
name,
attributeJsonSchema,
use
);
} else {
// Setup the working schema and allow processing to continue for any contained simpleType or annotation nodes.
attributeJsonSchema = this.workingJsonSchema.newJsonSchemaFile();
this.workingJsonSchema.addAttributeProperty(
name,
attributeJsonSchema,
use
);
this.workingJsonSchema = attributeJsonSchema;
}
return true;
}
handleAttributeReference(node, jsonSchema, xsd) {
const ref = XsdFile.getAttrValue(node, XsdAttributes.REF);
const use = XsdFile.getAttrValue(node, XsdAttributes.USE);
// TODO: id, default, fixed, inheritable (TBD)
if (ref !== undefined) {
var attrSchema = this.namespaceManager.getGlobalAttribute(
ref,
jsonSchema
);
this.workingJsonSchema.addAttributeProperty(
ref,
attrSchema.get$RefToSchema(this.workingJsonSchema),
use
);
}
return true;
}
attribute(node, jsonSchema, xsd) {
// (TBD)
//dumpNode(node);
if (XsdFile.isReference(node)) {
return this.handleAttributeReference(node, jsonSchema, xsd);
} else if (this.parsingState.isTopLevelEntity()) {
return this.handleAttributeGlobal(node, jsonSchema, xsd);
} else {
return this.handleAttributeLocal(node, jsonSchema, xsd);
}
}
handleAttributeGroupDefinition(node, jsonSchema, xsd) {
// TODO id, name
// (TBD)
}
handleAttributeGroupReference(node, jsonSchema, xsd) {
// TODO id, ref (TBD)
}
attributeGroup(node, jsonSchema, xsd) {
// (TBD)
return true;
}
getMinMaxOccurs(node, minmax) {
var retval = XsdFile.getAttrValue(node, minmax);
if (retval != undefined && retval != XsdAttributeValues.UNBOUNDED) {
retval = XsdFile.getAttrValueAsNumber(node, minmax);
}
return retval;
}
handleChoiceArray(node, jsonSchema, xsd) {
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
// TODO: id
// (TBD Don't forget to support singles)
throw new Error('choice array needs to be implemented!!');
return true;
}
allChildrenAreOptional(node) {
var retval = true;
const children = Array.from(node.childNodes);
children.forEach(function (childNode) {
if (childNode.nodeType != XsdNodeTypes.TEXT_NODE) {
const minOccursAttr = this.getMinMaxOccurs(
childNode,
XsdAttributes.MIN_OCCURS
);
if (minOccursAttr != 0) {
retval = false;
}
}
}, this);
return retval;
}
choice(node, jsonSchema, xsd) {
// TODO: id
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
const isAnyOfChoice = this.specialCaseIdentifier.isAnyOfChoice(node, xsd);
if (isAnyOfChoice === true) {
this.specialCaseIdentifier.addSpecialCase(
SpecialCases.ANY_OF_CHOICE,
this.workingJsonSchema,
node
);
// This could be optional too. Need a test!
}
const isArray =
maxOccursAttr !== undefined &&
(maxOccursAttr > 1 || maxOccursAttr === XsdAttributeValues.UNBOUNDED);
if (isArray) {
return this.handleChoiceArray(node, jsonSchema, xsd);
}
const isOptional = this.specialCaseIdentifier.isOptional(
node,
xsd,
minOccursAttr
);
const allChildrenAreOptional = this.allChildrenAreOptional(node);
const isSiblingChoice = this.specialCaseIdentifier.isSiblingChoice(
node,
xsd
);
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.CHOICE:
// Allow to fall through and continue processing. The schema is estabished with the complexType.
//throw new Error('choice() needs to be implemented within choice');
let oneOfSchema = this.workingJsonSchema.newJsonSchemaFile();
this.workingJsonSchema.oneOf.push(oneOfSchema);
this.parsingState.pushSchema(this.workingJsonSchema);
this.workingJsonSchema = oneOfSchema;
break;
case XsdElements.COMPLEX_TYPE:
// Allow to fall through and continue processing. The schema is estabished with the complexType.
//throw new Error('choice() needs to be implemented within complexType');
break;
case XsdElements.EXTENSION:
throw new Error('choice() needs to be implemented within extension');
case XsdElements.GROUP:
// Allow to fall through and continue processing. The schema is estabished with the group.
//throw new Error('choice() needs to be implemented within group');
break;
case XsdElements.RESTRICTION:
throw new Error('choice() needs to be implemented within restriction');
case XsdElements.SEQUENCE:
if (isSiblingChoice) {
debug('Found sibling <choice>');
let allOfSchema = this.workingJsonSchema.newJsonSchemaFile();
this.workingJsonSchema.allOf.push(allOfSchema);
this.parsingState.pushSchema(this.workingJsonSchema);
this.workingJsonSchema = allOfSchema;
if (isAnyOfChoice === true) {
debug(' ... that is an anyOfChoice');
// Ducktype it on there for now. This is checked in baseSpecialCaseIdentifier.fixAnyOfChoice.
// It is needed because all sibling choices may not be anyOfChoices.
allOfSchema.isAnyOfChoice = true;
}
}
if (allChildrenAreOptional || isOptional) {
debug('Found optional <choice> for ' + jsonSchema.id);
let optionalChoiceSchema = this.workingJsonSchema.newJsonSchemaFile();
this.workingJsonSchema.anyOf.push(optionalChoiceSchema);
if (!isSiblingChoice) {
this.parsingState.pushSchema(this.workingJsonSchema);
}
this.workingJsonSchema = optionalChoiceSchema;
// The optional part will be added as a special case
this.specialCaseIdentifier.addSpecialCase(
SpecialCases.OPTIONAL_CHOICE,
optionalChoiceSchema,
node
);
} else {
debug('Found required <choice>');
// This is an needless grouping just allow to fall through and continue processing
// Allow to fall through and continue processing.
// The schema should be estabished by the parent of the sequence.
// (Keep an eye on this one)
//throw new Error('choice() needs to be implemented within sequence');
}
break;
default:
throw new Error(
'choice() called from within unexpected parsing state!'
);
}
return true;
}
comment(node, jsonSchema, xsd) {
// do nothing - This is an XML comment (e.g. <!-- text -->)
return true;
}
complexContent(node, jsonSchema, xsd) {
// TODO: id, mixed
// Ignore this grouping and continue processing children
return true;
}
handleNamedComplexType(node, jsonSchema, xsd) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
// TODO: id, mixed, abstract, block, final, defaultAttributesApply
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.SCHEMA:
this.workingJsonSchema = this.namespaceManager.getType(
nameAttr,
jsonSchema,
jsonSchema,
xsd
);
jsonSchema.setSubSchema(nameAttr, this.workingJsonSchema);
this.workingJsonSchema.type = jsonSchemaTypes.OBJECT;
break;
case XsdElements.REDEFINE:
throw new Error('complexType() needs to be impemented within redefine');
case XsdElements.OVERRIDE:
throw new Error('complexType() needs to be impemented within override');
default:
throw new Error(
'complexType() called from within unexpected parsing state! state=' +
state.name
);
}
return true;
}
handleAnonymousComplexType(node, jsonSchema, xsd) {
// TODO: id, mixed, defaultAttributesApply
// Ignore this grouping and continue processing children
return true;
}
complexType(node, jsonSchema, xsd) {
if (XsdFile.isNamed(node)) {
return this.handleNamedComplexType(node, jsonSchema, xsd);
} else {
return this.handleAnonymousComplexType(node, jsonSchema, xsd);
}
}
defaultOpenContent(node, jsonSchema, xsd) {
// TODO: schema
// (TBD)
return true;
}
documentation(node, jsonSchema, xsd) {
// TODO: source, xml:lang
// Ignore this grouping and continue processing children. The actual text will come through the text() method.
return true;
}
handleElementGlobal(node, jsonSchema, xsd) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const typeAttr = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
// TODO: id, defaut, fixed, nillable, abstract, substitutionGroup, block, final
if (typeAttr !== undefined) {
var typeName = typeAttr;
var refType = this.namespaceManager.getTypeReference(
typeName,
jsonSchema,
jsonSchema,
xsd
);
//refType.id = jsonSchema.id;
this.namespaceManager.addTypeReference(
nameAttr,
refType,
jsonSchema,
xsd
);
this.workingJsonSchema = refType;
jsonSchema.setSubSchema(nameAttr, this.workingJsonSchema);
//workingJsonSchema.type = jsonSchemaTypes.OBJECT;
} else {
this.workingJsonSchema = this.namespaceManager.getType(
nameAttr,
jsonSchema,
jsonSchema,
xsd
);
jsonSchema.setSubSchema(nameAttr, this.workingJsonSchema);
this.workingJsonSchema.type = jsonSchemaTypes.OBJECT;
}
if (this.parsingState.inChoice()) {
throw new Error(
'choice needs to be implemented in handleElementGlobal()!'
);
}
return true;
}
addProperty(targetSchema, propertyName, customType, minOccursAttr) {
if (
minOccursAttr === undefined ||
minOccursAttr === XsdAttributeValues.REQUIRED ||
minOccursAttr > 0
) {
targetSchema.addRequired(propertyName);
}
targetSchema.setProperty(propertyName, customType);
}
addChoiceProperty(targetSchema, propertyName, customType, minOccursAttr) {
var choiceSchema = targetSchema.newJsonSchemaFile();
//choiceSchema.additionalProperties = false;
this.addProperty(choiceSchema, propertyName, customType, minOccursAttr);
targetSchema.oneOf.push(choiceSchema);
}
addPropertyAsArray(
targetSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
) {
const oneOfSchema = targetSchema.newJsonSchemaFile();
const arraySchema = oneOfSchema.newJsonSchemaFile();
const min = minOccursAttr === undefined ? undefined : minOccursAttr;
const max = maxOccursAttr === undefined ? undefined : maxOccursAttr;
arraySchema.type = jsonSchemaTypes.ARRAY;
arraySchema.minItems = min;
arraySchema.maxItems =
max === XsdAttributeValues.UNBOUNDED ? undefined : max;
arraySchema.items = customType.get$RefToSchema(arraySchema);
oneOfSchema.oneOf.push(customType.get$RefToSchema(oneOfSchema));
oneOfSchema.oneOf.push(arraySchema);
this.addProperty(targetSchema, propertyName, oneOfSchema, minOccursAttr);
}
addChoicePropertyAsArray(
targetSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
) {
const choiceSchema = targetSchema.newJsonSchemaFile();
//choiceSchema.additionalProperties = false;
this.addPropertyAsArray(
choiceSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
);
targetSchema.oneOf.push(choiceSchema);
}
handleElementLocal(node, jsonSchema, xsd) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
const typeAttr = XsdFile.getAttrValue(node, XsdAttributes.TYPE);
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
// TODO: id, form, defaut, fixed, nillable, block, targetNamespace
var lookupName;
if (typeAttr !== undefined) {
lookupName = typeAttr;
}
const propertyName = nameAttr;
var customType;
if (lookupName !== undefined) {
if (this.namespaceManager.isBuiltInType(lookupName, xsd)) {
//customType = this.namespaceManager.getBType(lookupName, this.workingJsonSchema, jsonSchema, xsd, false);
customType = this.namespaceManager.getBuiltInType(
lookupName,
this.workingJsonSchemaent,
xsd
);
} else {
customType = this.namespaceManager.getTypeReference(
lookupName,
this.workingJsonSchema,
jsonSchema,
xsd
);
}
} else {
//propertyName = nameAttr + '-' + XsdFile.getNameOfFirstParentWithNameAttribute(node); // local element names attributes are scoped to the parent so they are not unique within the namespace.
//customType = this.namespaceManager.getType(propertyName, this.workingJsonSchema, jsonSchema, xsd);
customType = this.workingJsonSchema.newJsonSchemaFile();
}
var isArray =
maxOccursAttr !== undefined &&
(maxOccursAttr > 1 || maxOccursAttr === XsdAttributeValues.UNBOUNDED);
var state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.CHOICE:
if (
this.allChildrenAreOptional(node.parentNode) &&
this.specialCaseIdentifier.isOptional(node.parentNode, xsd)
) {
if (isArray) {
this.addPropertyAsArray(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
);
} else {
this.addProperty(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr
);
}
} else {
if (isArray) {
this.addChoicePropertyAsArray(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
);
} else {
this.addChoiceProperty(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr
);
}
}
break;
case XsdElements.SEQUENCE:
case XsdElements.ALL:
if (isArray) {
this.addPropertyAsArray(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr,
maxOccursAttr
);
} else {
this.addProperty(
this.workingJsonSchema,
propertyName,
customType,
minOccursAttr
);
}
break;
default:
throw new Error(
'element() [local] called from within unexpected parsing state!'
);
}
this.parsingState.pushSchema(this.workingJsonSchema);
this.workingJsonSchema = customType;
return true;
}
handleElementReference(node, jsonSchema, xsd) {
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
const refAttr = XsdFile.getAttrValue(node, XsdAttributes.REF);
// TODO: id
// An element within a model group (such as 'group') may be a reference. References have neither
// a name nor a type attribute - just a ref attribute. This is awkward when the reference elmenent
// is a property of an object in JSON. With no other options to name the property ref is used.
const propertyName = refAttr; // ref attribute is required for an element reference
const ref = this.namespaceManager.getTypeReference(
propertyName,
this.workingJsonSchema,
jsonSchema,
xsd
);
const isArray =
maxOccursAttr !== undefined &&
(maxOccursAttr > 1 || maxOccursAttr === XsdAttributeValues.UNBOUNDED);
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.CHOICE:
if (
this.allChildrenAreOptional(node.parentNode) &&
this.specialCaseIdentifier.isOptional(node.parentNode, xsd)
) {
if (isArray) {
this.addPropertyAsArray(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr,
maxOccursAttr
);
} else {
this.addProperty(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr
);
}
} else {
if (isArray) {
this.addChoicePropertyAsArray(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr,
maxOccursAttr
);
} else {
this.addChoiceProperty(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr
);
}
}
break;
case XsdElements.SEQUENCE:
case XsdElements.ALL:
if (isArray) {
this.addPropertyAsArray(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr,
maxOccursAttr
);
} else {
this.addProperty(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr
);
}
break;
default:
throw new Error(
'element() [reference] called from within unexpected parsing state!'
);
}
return true;
}
element(node, jsonSchema, xsd) {
const refAttr = XsdFile.getAttrValue(node, XsdAttributes.REF);
const localNamespaceDefinition = XsdFile.getAttrValueByPrefix(
node,
XsdAttributeValues.XMLNS
);
if (localNamespaceDefinition) {
xsd.addNamespace(
localNamespaceDefinition.localName,
localNamespaceDefinition.nodeValue
);
}
if (refAttr !== undefined) {
return this.handleElementReference(node, jsonSchema, xsd);
} else if (this.parsingState.isTopLevelEntity()) {
return this.handleElementGlobal(node, jsonSchema, xsd);
} else {
return this.handleElementLocal(node, jsonSchema, xsd);
}
}
enumeration(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttr(node);
// TODO: id, fixed
this.workingJsonSchema.addEnum(val);
return true;
}
explicitTimezone(node, jsonSchema, xsd) {
// TODO: id, fixed, value
// (TBD)
return true;
}
extension(node, jsonSchema, xsd) {
const baseAttr = XsdFile.getAttrValue(node, XsdAttributes.BASE);
const localNamespaceDefinition = XsdFile.getAttrValueByPrefix(
node,
XsdAttributeValues.XMLNS
);
if (localNamespaceDefinition) {
xsd.addNamespace(
localNamespaceDefinition.localName,
localNamespaceDefinition.nodeValue
);
}
// TODO: id
const state = this.parsingState.getCurrentState();
// This switch isn't really needed since both content types are being handled the same, but keeping it just in case this turns out to be a false assumption.
switch (state.name) {
case XsdElements.COMPLEX_CONTENT:
this.parsingState.pushSchema(this.workingJsonSchema);
let typeRef = this.namespaceManager.getTypeReference(
baseAttr,
this.workingJsonSchema,
jsonSchema,
xsd
);
this.workingJsonSchema = this.workingJsonSchema.extend(typeRef); //, jsonSchemaTypes.OBJECT);
break;
case XsdElements.SIMPLE_CONTENT:
if (this.namespaceManager.isBuiltInType(baseAttr, xsd)) {
let baseType = new Qname(baseAttr);
let baseTypeName = baseType.getLocal();
return this.builtInTypeConverter[baseTypeName](
node,
this.workingJsonSchema
);
} else {
this.parsingState.pushSchema(this.workingJsonSchema);
let typeRef = this.namespaceManager.getTypeReference(
baseAttr,
this.workingJsonSchema,
jsonSchema,
xsd
);
this.workingJsonSchema = this.workingJsonSchema.extend(typeRef); //, jsonSchemaTypes.OBJECT);
}
break;
default:
throw new Error(
'extension() called from within unexpected parsing state!'
);
}
return true;
}
field(node, jsonSchema, xsd) {
// TODO: id, xpath, xpathDefaultNamespace
// (TBD)
return true;
}
fractionDigits(node, jsonSchema, xsd) {
return true;
}
handleGroupDefinition(node, jsonSchema, xsd) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
// TODO: id
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.SCHEMA:
this.workingJsonSchema = this.namespaceManager.getType(
nameAttr,
jsonSchema,
jsonSchema,
xsd
);
jsonSchema.setSubSchema(nameAttr, this.workingJsonSchema);
this.workingJsonSchema.type = jsonSchemaTypes.OBJECT;
break;
case XsdElements.REDEFINE:
throw new Error(
'group() [definition] needs to be impemented within redefine!'
);
case XsdElements.OVERRIDE:
throw new Error(
'group() [definition] needs to be impemented within override!'
);
default:
throw new Error(
'group() [definition] called from within unexpected parsing state!'
);
}
return true;
}
handleGroupReference(node, jsonSchema, xsd) {
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
const refAttr = XsdFile.getAttrValue(node, XsdAttributes.REF);
// TODO: id
const propertyName = refAttr; // ref attribute is required for group reference
const ref = this.namespaceManager.getTypeReference(
propertyName,
this.workingJsonSchema,
jsonSchema,
xsd
);
const isArray =
maxOccursAttr !== undefined &&
(maxOccursAttr > 1 || maxOccursAttr === XsdAttributeValues.UNBOUNDED);
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.EXTENSION:
throw new Error(
'group() [reference] needs to be impemented within extension!'
);
case XsdElements.RESTRICTION:
throw new Error(
'group() [reference] needs to be impemented within restriction!'
);
case XsdElements.CHOICE:
if (isArray) {
this.addChoicePropertyAsArray(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr,
maxOccursAttr
);
} else {
this.addChoiceProperty(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr
);
}
break;
case XsdElements.COMPLEX_TYPE:
case XsdElements.SEQUENCE:
case XsdElements.ALL:
if (isArray) {
this.addPropertyAsArray(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr,
maxOccursAttr
);
} else {
this.addProperty(
this.workingJsonSchema,
propertyName,
ref,
minOccursAttr
);
}
break;
default:
throw new Error(
'group() [reference] called from within unexpected parsing state!'
);
}
return true;
}
group(node, jsonSchema, xsd) {
if (XsdFile.isReference(node)) {
return this.handleGroupReference(node, jsonSchema, xsd);
} else {
return this.handleGroupDefinition(node, jsonSchema, xsd);
}
}
import(node, jsonSchema, xsd) {
const namespace = XsdFile.getAttrValue(node, XsdAttributes.NAMESPACE);
const schemaLocation = XsdFile.getAttrValue(
node,
XsdAttributes.SCHEMA_LOCATION
);
// TODO: id
xsd.imports[namespace] = new URI(xsd.directory)
.segment(schemaLocation)
.toString();
return true;
}
include(node, jsonSchema, xsd) {
// TODO: id, schemaLocation
// do nothing
return true;
}
handleKeyConstraint() {
// TODO: id, name
// (TBD)
return true;
}
handleKeyReferenceToKeyConstraint() {
// TODO: id, ref
// (TBD)
return true;
}
key(node, jsonSchema, xsd) {
// (TBD)
return true;
}
handleKeyReference(node, jsonSchema, xsd) {
// TODO: id, name, refer
// (TBD)
return true;
}
handleKeyReferenceToKeyReference(node, jsonSchema, xsd) {
// TODO: id, ref
// (TBD)
return true;
}
keyref(node, jsonSchema, xsd) {
// (TBD)
return true;
}
length(node, jsonSchema, xsd) {
// TODO: id, fixed
const len = XsdFile.getValueAttrAsNumber(node);
this.workingJsonSchema.maxLength = len;
this.workingJsonSchema.minLength = len;
return true;
}
list(node, jsonSchema, xsd) {
// TODO: id, itemType
// (TBD)
return true;
}
maxExclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.maximum = val;
this.workingJsonSchema.exlusiveMaximum = true;
return true;
}
maxInclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.maximum = val; // inclusive is the JSON Schema default
return true;
}
maxLength(node, jsonSchema, xsd) {
const len = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.maxLength = len;
return true;
}
minExclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.minimum = val;
this.workingJsonSchema.exclusiveMinimum = true;
return true;
}
minInclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.minimum = val; // inclusive is the JSON Schema default
return true;
}
minLength(node, jsonSchema, xsd) {
const len = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.minLength = len;
return true;
}
notation(node, jsonSchema, xsd) {
// TODO: id, name, public, system
// (TBD)
return true;
}
openContent(node, jsonSchema, xsd) {
// TODO: id, mode
// (TBD)
return true;
}
override(node, jsonSchema, xsd) {
// TODO: id, schemaLocation
// (TBD)
return true;
}
pattern(node, jsonSchema, xsd) {
const pattern = XsdFile.getValueAttr(node);
// TODO: id
this.workingJsonSchema.pattern = pattern;
return true;
}
redefine(node, jsonSchema, xsd) {
// TODO: id, schemaLocation
// (TBD)
return true;
}
restriction(node, jsonSchema, xsd) {
const baseAttr = XsdFile.getAttrValue(node, XsdAttributes.BASE);
const baseType = new Qname(baseAttr);
const baseTypeName = baseType.getLocal();
// TODO: id, (base inheritance via allOf)
if (this.namespaceManager.isBuiltInType(baseAttr, xsd)) {
return this.builtInTypeConverter[baseTypeName](
node,
this.workingJsonSchema
);
} else {
this.parsingState.pushSchema(this.workingJsonSchema);
let typeRef = this.namespaceManager.getTypeReference(
baseAttr,
jsonSchema,
jsonSchema,
xsd
);
if (XsdFile.isEmpty(node)) {
jsonSchema.setSubSchema(
XsdFile.getNameAttrValue(node.parentNode),
typeRef
);
} else {
this.workingJsonSchema = this.workingJsonSchema.extend(typeRef);
}
return true;
}
}
schema(node, jsonSchema, xsd) {
// TODO: id, version, targetNamespace, attributeFormDefualt, elementFormDefualt, blockDefault, finalDefault, xml:lang, defaultAttributes, xpathDefaultNamespace
jsonSchema.description =
'Schema tag attributes: ' +
utils.objectToString(XsdFile.buildAttributeMap(node));
this.initializeNamespaces(xsd);
this.workingJsonSchema = jsonSchema;
return true;
}
selector(node, jsonSchema, xsd) {
// TODO: key, keyref, unique
// (TBD)
return true;
}
sequence(node, jsonSchema, xsd) {
const minOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MIN_OCCURS);
const maxOccursAttr = this.getMinMaxOccurs(node, XsdAttributes.MAX_OCCURS);
const isArray =
maxOccursAttr !== undefined &&
(maxOccursAttr > 1 || maxOccursAttr === XsdAttributeValues.UNBOUNDED);
if (isArray) {
throw new Error('sequence arrays need to be implemented!');
}
var isOptional = minOccursAttr !== undefined && minOccursAttr == 0;
if (isOptional === true) {
let type = XsdFile.getTypeNode(node);
let typeName = type.getAttribute('name');
debug('Optional Sequence Found : ' + xsd.filename + ':' + typeName);
if (typeName == '') {
this.parsingState.dumpStates(xsd.filename);
XsdFile.dumpNode(node);
}
}
const state = this.parsingState.getCurrentState();
switch (state.name) {
case XsdElements.CHOICE:
let choiceSchema = this.workingJsonSchema.newJsonSchemaFile();
//choiceSchema.additionalProperties = false;
this.workingJsonSchema.oneOf.push(choiceSchema);
this.parsingState.pushSchema(this.workingJsonSchema);
this.workingJsonSchema = choiceSchema;
break;
case XsdElements.COMPLEX_TYPE:
break;
case XsdElements.EXTENSION:
break;
case XsdElements.GROUP:
break;
case XsdElements.RESTRICTION:
break;
case XsdElements.SEQUENCE:
if (isOptional) {
let optionalSequenceSchema =
this.workingJsonSchema.newJsonSchemaFile();
this.workingJsonSchema.anyOf.push(optionalSequenceSchema);
this.specialCaseIdentifier.addSpecialCase(
SpecialCases.OPTIONAL_SEQUENCE,
optionalSequenceSchema,
node
);
// Add an the optional part (empty schema)
let emptySchema = this.workingJsonSchema.newJsonSchemaFile();
emptySchema.description =
'This truthy schema is what makes an optional <sequence> optional.';
this.workingJsonSchema.anyOf.push(emptySchema);
this.parsingState.pushSchema(this.workingJsonSchema);
this.workingJsonSchema = optionalSequenceSchema;
} else {
throw new Error('Required nested sequences need to be implemented!');
}
break;
default:
throw new Error(
'sequence() called from within unexpected parsing state! state = [' +
state.name +
']'
);
}
return true;
}
simpleContent(node, jsonSchema, xsd) {
// TODO: id
// Ignore this grouping and continue processing children
return true;
}
handleSimpleTypeNamedGlobal(node, jsonSchema, xsd) {
const nameAttr = XsdFile.getAttrValue(node, XsdAttributes.NAME);
// TODO: id, final
this.workingJsonSchema = this.namespaceManager.getType(
nameAttr,
jsonSchema,
jsonSchema,
xsd
);
jsonSchema.setSubSchema(nameAttr, this.workingJsonSchema);
return true;
}
handleSimpleTypeAnonymousLocal(node, jsonSchema, xsd) {
// TODO: id
// Ignore this grouping and continue processing children
return true;
}
simpleType(node, jsonSchema, xsd) {
debug('Found SimpleType');
var continueParsing;
if (XsdFile.isNamed(node)) {
continueParsing = this.handleSimpleTypeNamedGlobal(node, jsonSchema, xsd);
} else {
continueParsing = this.handleSimpleTypeAnonymousLocal(
node,
jsonSchema,
xsd
);
}
if (this.parsingState.inAttribute()) {
// need to pop
}
return continueParsing;
}
text(node, jsonSchema, xsd) {
if (this.parsingState.inDocumentation()) {
// TODO: This should be a configurable option
this.workingJsonSchema.description = node.parentNode.childNodes
.toString()
.replace(/\s+/g, ' ')
.trim();
} else if (this.parsingState.inAppInfo()) {
//this.workingJsonSchema.concatDescription(node.parentNode.nodeName + '=' + node.textContent + ' ');
this.workingJsonSchema.description +=
node.parentNode.nodeName + '=' + node.textContent + ' ';
}
return true;
}
totalDigits(node, jsonSchema, xsd) {
// TODO: id, fixed
let len = XsdFile.getValueAttrAsNumber(node);
if(len > 10)
{
len = 10;
}
let max = '';
for (let index = 0; index < len; index++) {
max += '9'
}
this.workingJsonSchema.maximum = max * 1;
return true;
}
union(node, jsonSchema, xsd) {
// TODO: id, memberTypes
// (TBD)
return true;
}
handleUniqueConstraint(node, jsonSchema, xsd) {
// TODO: id, name
// (TBD)
return true;
}
handleUniqueReferenceToUniqueConstraint(node, jsonSchema, xsd) {
// TODO: id, ref
// (TBD)
return true;
}
unique(node, jsonSchema, xsd) {
// (TBD)
return true;
}
whitespace(node, jsonSchema, xsd) {
// TODO: id, value, fixed
// (TBD)
return true;
}
processSpecialCases() {
this.specialCaseIdentifier.processSpecialCases();
}
}
module.exports = ConverterDraft04;
},{"./baseSpecialCaseIdentifier":89,"./jsonschema/jsonSchemaFile":97,"./jsonschema/jsonSchemaTypes":106,"./namespaceManager":107,"./processor":109,"./qname":111,"./specialCases":112,"./utils":113,"./xmlschema/xsdAttributeValues":119,"./xmlschema/xsdAttributes":120,"./xmlschema/xsdElements":121,"./xmlschema/xsdFileXmlDom":122,"./xmlschema/xsdNodeTypes":123,"debug":3,"urijs":11}],93:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:ConverterDraft06')
const ConverterDraft04 = require('./converterDraft04');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
class ConverterDraft06 extends ConverterDraft04 {
/**
* Constructs an instance of ConverterDraft06.
* @constructor
*/
constructor(options) {
super(options);
}
// Override maxExclusive with new draft-v6 behavior
maxExclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.exclusiveMaximum = val;
return true;
}
// Override minExclusive with new draft-v6 behavior
minExclusive(node, jsonSchema, xsd) {
const val = XsdFile.getValueAttrAsNumber(node);
// TODO: id, fixed
this.workingJsonSchema.exclusiveMinimum = val;
return true;
}
}
module.exports = ConverterDraft06;
},{"./converterDraft04":92,"./xmlschema/xsdFileXmlDom":122,"debug":3}],94:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:ConverterDraft07')
const ConverterDraft06 = require('./converterDraft06');
class ConverterDraft07 extends ConverterDraft06 {
/**
* Constructs an instance of ConverterDraft07.
* @constructor
*/
constructor(options) {
super(options);
}
}
module.exports = ConverterDraft07;
},{"./converterDraft06":93,"debug":3}],95:[function(require,module,exports){
'use strict';
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const okayToContinue_NAME = Symbol();
const NOT_PROCESSED_NODES = ['appinfo'];
/**
* Class represtending a depth first traversal algorithm. This class is used as part of a visitor pattern
* to traverse the nodes within an XML Schema visiting each to facitiate conversion to JSON Schema.
*/
class DepthFirstTraversal {
/**
* Constructs an instance of DepthFirstTraversal.
* @constructor
*/
constructor() {
this.okayToContinue = true;
}
// Getters/Setters
get okayToContinue() {
return this[okayToContinue_NAME];
}
set okayToContinue(NewOkayToContinue) {
this[okayToContinue_NAME] = NewOkayToContinue;
}
/**
* This function implements a recursive algorithm to traverse a tree of xml schema nodes in a depth first manner. Each
* node is visited and a customizalbe {@link BaseConversionVisitor|visiter} is applied. The visiter can abandon the traversal at any time by
* returning false from the {@link BaseConversionVisitor#visit|visit()} method.
*
* @param {BaseConversionVisitor} visitor - {@link BaseConversionVisitor} or a subclass of {@link BaseConversionVisitor}
* @param {Node} node - The XML 'schema' element within {@link XsdFile|xsd} to be used as the start of conversion.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @see {@link BaseConversionVisitor#visit|BaseConversionVisitor.visit()}
*/
walk(visitor, node, jsonSchema, xsd) {
// walk the tree
if (node !== null) {
visitor.enterState(node, jsonSchema, xsd);
this.okayToContinue = visitor.visit(node, jsonSchema, xsd);
if (this.okayToContinue) {
var children = NOT_PROCESSED_NODES.includes(node.localName) ?
[] :
XsdFile.getChildNodes(node);
if (children !== null && children.length > 0) {
for(let child of children) {
this.walk(visitor, child, jsonSchema, xsd);
if(!this.okayToContinue) {
break;
}
};
}
}
visitor.exitState(node, jsonSchema, xsd);
}
}
/**
* Begins a traversal of {@link XsdFile|xsd} by first calling visitor's {@link BaseConversionVisitor#onBegin|onBegin()} method. The traversal can be abandoned by
* returning false from {@link BaseConversionVisitor#onBegin|onBegin()}. After the traversal is complete the vistor's {@link BaseConversionVisitor#onEnd|OnEnd()}
* method is called.
*
* @param {BaseConversionVisitor} visitor - {@link BaseConversionVisitor} or a subclass of {@link BaseConversionVisitor}
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current XML Schema file {@link XsdFile|xsd} to be converted.
* @param {XsdFile} xsd - The XML schema file to be converted.
*
* @see {@link BaseConversionVisitor#onBegin|BaseConversionVisitor.onBegin()}
* @see {@link BaseConversionVisitor#onEnd|BaseConversionVisitor.onEnd()}
*/
traverse(visitor, jsonSchema, xsd) {
if (visitor.onBegin(jsonSchema, xsd)) {
this.walk(visitor, xsd.schemaElement, jsonSchema, xsd);
}
return visitor.onEnd(jsonSchema, xsd);
}
}
module.exports = DepthFirstTraversal;
},{"./xmlschema/xsdFileXmlDom":122}],96:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:ForwardReference')
const URI = require('urijs');
const clone = require('clone');
const Constants = require('./constants');
const JsonSchemaRef = require('./jsonschema/jsonSchemaRef');
const parent_NAME = Symbol();
const namespaceManager_NAME = Symbol();
/**
* TBD
*
* @module ForwardReference
*/
class ForwardReference {
constructor(namespaceManager, namespace, fullTypeName, parent, baseJsonSchema, xsd) {
if (namespaceManager === undefined) {
throw new Error('\'namespaceManager\' parameter required');
}
if (namespace === undefined) {
throw new Error('\'namespace\' parameter required');
}
if (fullTypeName === undefined) {
throw new Error('\'fullTypeName\' parameter required');
}
if (parent === undefined) {
throw new Error('\'parent\' parameter required');
}
if (baseJsonSchema === undefined) {
throw new Error('\'baseJsonSchema\' parameter required');
}
if (xsd === undefined) {
throw new Error('\'xsd\' parameter required');
}
this.namespaceManager = namespaceManager;
this.namespace = namespace;
this.fullTypeName = fullTypeName;
this.parent = parent;
this.baseJsonSchema = baseJsonSchema;
this.xsd = xsd;
this.ref = new JsonSchemaRef({
$ref: Constants.FORWARD_REFERENCE + '#' + '/to/' + namespace + '/' + fullTypeName,
parent: parent,
forwardReference: this
});
}
// ES6 getters/setters are not enumerable by default. Leverage this by defining the getters/seters
// to exclude these properties from the deep clone.
get namespaceManager() {
return this[namespaceManager_NAME];
}
set namespaceManager(newNamespaceManager) {
this[namespaceManager_NAME] = newNamespaceManager;
}
get parent() {
return this[parent_NAME];
}
set parent(newParent) {
this[parent_NAME] = newParent;
}
clone(parent) {
const c = clone(this, true);
c.parent = parent;
c.ref.parent = parent;
c.namespaceManager = this.namespaceManager
}
}
module.exports = ForwardReference;
},{"./constants":91,"./jsonschema/jsonSchemaRef":102,"clone":2,"debug":3,"urijs":11}],97:[function(require,module,exports){
(function (process){(function (){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFile');
const path = (process && typeof process.platform === 'string') ? require('path') : require('path-browserify');
const URI = require('urijs');
const clone = require('clone');
const deepEql = require('deep-eql');
const utils = require('../utils');
const Constants = require('../constants');
const PropertyDefinable = require('../propertyDefinable');
const jsonSchemaTypes = require('./jsonSchemaTypes');
const XsdAttributeValues = require('../xmlschema/xsdAttributeValues');
//const parent_NAME = Symbol();
//const targetSchema_NAME = Symbol();
/*
const properties = [
'namespaceMode',
'parent',
'filename',
'targetSchema',
'targetNamespace',
'ref',
'$ref',
'id',
'schemaId',
'subSchemas',
'$schema',
'title',
'description',
'default',
'format',
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'properties',
'patternProperties',
'dependencies',
'enum',
'type',
'allOf',
'anyOf',
'oneOf',
'not',
'definitions'
]
*/
/**
* JSON Schema file operations. This is based on the JSON Schema meta-schema located at http://json-schema.org/draft-04/schema#.
*
*
* Please see http://json-schema.org for more details.
*/
class JsonSchemaFile extends PropertyDefinable {
/**
*
* @param {Object} options - And object used to override default options.
* @param {string} options.baseFilename - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.baseId - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.targetNamespace - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.title - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.$ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {JsonSchmeaFile} options.parent - A reference to the parent JSON Schema.
* @param {string} options.namespaceMode - The method of handling namespaces. Must be one of: undefined, SUBSCHEMA, or FILENAME
*/
constructor(options) {
/*
var superProperties;
if (options != undefined && options.properties !== undefined) {
superProperties = [ ... new Set(properties.concat(options.properties))];
} else {
superProperties = properties;
}
super({
propertyNames: superProperties
});
*/
super();
super.defineStringProperty('namespaceMode');
super.defineObjectProperty('parent');
super.defineStringProperty('filename');
super.defineObjectProperty('targetSchema');
super.defineStringProperty('targetNamespace');
super.defineObjectProperty('ref');
super.defineStringProperty('$ref');
super.defineStringProperty('id');
super.defineStringProperty('schemaId');
super.defineObjectProperty('subSchemas');
super.defineStringProperty('$schema');
super.defineStringProperty('title');
super.defineStringProperty('description');
super.defineProperty('default');
super.defineStringProperty('format');
super.defineNumericProperty('multipleOf');
super.defineNumericProperty('maximum');
super.defineBooleanProperty('exclusiveMaximum');
super.defineNumericProperty('minimum');
super.defineBooleanProperty('exclusiveMinimum');
super.defineNumericProperty('maxLength');
super.defineNumericProperty('minLength');
super.defineStringProperty('pattern');
super.defineProperty('additionalItems');
super.defineProperty('items');
super.defineNumericProperty('maxItems');
super.defineNumericProperty('minItems');
super.defineBooleanProperty('uniqueItems');
super.defineNumericProperty('maxProperties');
super.defineNumericProperty('minProperties');
super.defineArrayProperty('required');
super.defineProperty('additionalProperties');
super.defineObjectProperty('properties');
super.defineObjectProperty('patternProperties');
super.defineObjectProperty('dependencies');
super.defineArrayProperty('enum')
super.defineProperty('type');
super.defineArrayProperty('allOf');
super.defineArrayProperty('anyOf');
super.defineArrayProperty('oneOf');
super.defineObjectProperty('not');
super.defineObjectProperty('definitions');
this.parent = undefined;
this.filename = undefined;
this.targetSchema = this;
this.targetNamespace = undefined;
this.ref = undefined; // used to hold a JSON Pointer reference to this named type (Not used for anonymous types)
this.$ref = undefined; // used when this schema is an instance of a reference
// JSON Schema draft v4 (core definitions and terminology referenced)
// 7.2 URI resolution scope alteration with the 'id'
this.id = undefined; // uri
// 3.4 Root schema, subschema (7.2.2 Usage)
this.subSchemas = {};
this.$schema = undefined; // uri
// JSON Schema Validation specification sections referenced unless otherwise noted
// 6.1 Metadata keywords 'title' and 'description'
this.title = undefined;
this.description = undefined; // Might need to initialize to '' for concatDescription()
// 6.2 Default
this.default = undefined; // There are no restrictions placed on the value of this keyword.
// 7 Semantic validation with 'format'
this.format = undefined;
// 5.1. Validation keywords for numeric instances (number and integer)
this.multipleOf = undefined; // multiple of 2 is 2, 4, 8, etc.
this.maximum = undefined;
this.exclusiveMaximum = false; // 5.1.2.3
this.minimum = undefined;
this.exclusiveMinimum = false; // 5.1. 3.3
// 5.2. Validation keywords for strings
this.maxLength = undefined;
this.minLength = 0; // 5.2.2.3
this.pattern = undefined; // 5.2.3.1 ECMA 262 regular expression dialect
// 5.3. Validation keywords for arrays
this.additionalItems = {}; // 5.3.1.1 boolean or a schema
this.items = {}; // 5.3.1.4 schema or an array of schemas but the default value is an empty schema
this.maxItems = undefined;
this.minItems = 0; // 5.3.3.3
this.uniqueItems = false; // 5.3.4.3
// 5.4. Validation keywords for objects
this.maxProperties = undefined;
this.minProperties = 0; // 5.4.2.3
this.required = []; // 5.4.3.1 string array - must have unique values and minimum length=1
this.additionalProperties = undefined; // boolean or a schema
this.properties = {}; // 5.4.4.1 MUST be an object. Each property of this object MUST be a valid JSON Schema.
this.patternProperties = {}; // 5.4.4.1 MUST be an object. Each property name of this object SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect. Each property value of this object MUST be a valid JSON Schema.
// 5.4.5. Dependencies
// This keyword's value MUST be an object. Each value of this object MUST be either an object or an array.
// If the value is an object, it MUST be a valid JSON Schema. This is called a schema dependency.
// If the value is an array, it MUST have at least one element. Each element MUST be a string, and elements in the array MUST be unique. This is called a property dependency.
this.dependencies = {};
// 5.5. Validation keywords for any instance type
this.enum = []; // 5.5.1.1 Elements in the array MUST be unique.
this.type = undefined; // string or string array limited to the seven primitive types (simpleTypes)
this.allOf = []; // 5.5.3.1 Elements of the array MUST be objects. Each object MUST be a valid JSON Schema.
this.anyOf = []; // 5.5.4.1 Elements of the array MUST be objects. Each object MUST be a valid JSON Schema.
this.oneOf = []; // 5.5.5.1 Elements of the array MUST be objects. Each object MUST be a valid JSON Schema.
this.not = {}; // 5.5.6.1 This object MUST be a valid JSON Schema.
this.definitions = undefined; // 5.5.7.1 MUST be an object. Each member value of this object MUST be a valid JSON Schema.
if (options !== undefined) {
if (options.schemaId !== undefined) {
this.schemaId = options.schemaId;
}
if (options.title !== undefined) {
this.title = options.title;
}
// This needs to be documented (CHANGE THIS TO URI AND IMPLEMENT LOCAL REFERENCES)
if (options.ref !== undefined) {
this.ref = options.ref;
}
// This needs to be documented
if (options.$ref !== undefined) {
this.$ref = options.$ref;
}
// If available set the reference to the parent schema.
if (options.parent !== undefined) {
this.parent = options.parent;
}
if (options.baseFilename !== undefined) {
this.targetNamespace = options.targetNamespace;
const filePath = path.parse(options.baseFilename);
const baseFilename = filePath.name;
// If available set the namespaceMode. This is used when creating $ref values to suport subschemas.
if (options.namespaceMode !== undefined) {
this.namespaceMode = options.namespaceMode;
}
if (this.namespaceMode === Constants.FILENAME) {
this.filename = path.join(filePath.dir, baseFilename + utils.getSafeNamespace(this.targetNamespace).replace(/\//g, '.') + '.json');
} else {
this.filename = path.join(filePath.dir, baseFilename + '.json');
}
this.id = new URI(options.baseId === undefined ? '' : options.baseId).filename(baseFilename + '.json').toString();
this.$schema = options.$schema;
if (this.title === undefined) {
this.title = `This JSON Schema file was generated from ${options.baseFilename} on ${new Date()}. For more information please see http://www.xsd2jsonschema.org`;
}
this.type = jsonSchemaTypes.OBJECT;
this.initializeSubschemas();
}
}
}
/**
* Creates all subschemas identified by an array of subschema names and initializes the targetSchema to the inner-most subschema.
*
* @param {JsonSchemaFile} schema - a JsonSchemaFile that will have nested subschemas.
* @param {Array} namespaces - An array of String values representing the components of a URL without the scheme.
* @returns {void}
*/
createNestedSubschema(schema, namespaces) {
const subschemaName = namespaces.shift();
const newSubSchema = schema.newJsonSchemaFile();
schema.subSchemas[subschemaName] = newSubSchema;
this.targetSchema = newSubSchema; // Track the innermost schema as the target
if (namespaces.length > 0) {
this.createNestedSubschema(newSubSchema, namespaces);
}
}
/**
* Initializes the subschemas for this JsonSchemaFile from the previously initialized targetNamespace member. The targetNamespace is
* generally represented by a URL. This URL is broken down into its constituent parts and each part becomes a subschema.
*
* @returns {void}
*/
initializeSubschemas() {
if (this.targetNamespace !== undefined && this.namespaceMode === Constants.SUBSCHEMA) {
var subschemaStr = utils.getSafeNamespace(this.targetNamespace);
if (!this.isEmpty(subschemaStr)) {
var namespaces = subschemaStr.split('/');
if (namespaces.length > 1) {
namespaces.shift();
}
this.createNestedSubschema(this, namespaces);
}
} else {
//this.createNestedSubschema(this, [Constants.DEFINITIONS]);
this.definitions = this.newJsonSchemaFile();
this.targetSchema = this.definitions;
}
}
/**
* Returns true if the val is: null, undefined, a zero length string, a zero length array, or an object with no properties.
*
* @param {Object|String|Array} val - The value to determine whether or not is empty.
* @returns {Boolean} - Returns true if val is empty.
*/
isEmpty(val) {
if (typeof val == 'undefined' || val == 'undefined' || val == null) {
return true;
}
if (typeof val === 'string' && val.length === 0) {
return true;
}
if (typeof val === 'object') {
if (Array.isArray(val)) {
return (val.length === 0)
} else {
const symbols = Object.getOwnPropertySymbols(val);
const keys = Object.keys(val);
if ((symbols.length === 0) && (keys.length === 0)) {
return true;
}
}
}
return false;
}
/**
* Returns true if the all members of the JsonSchemaFile are empty as defined by isEmpty().
*
* @returns {Boolean} - Returns true if the all members of the JsonSchemaFile are empty.
*/
isBlank() {
if (!this.isEmpty(this.parent)) {
return false;
}
if (!this.isEmpty(this.filename)) {
return false;
}
if (!this.isEmpty(this.targetSchema) && this.targetSchema !== this) {
return false;
}
if (!this.isEmpty(this.targetNamespace)) {
return false;
}
if (!this.isEmpty(this.ref)) {
return false;
}
if (!this.isEmpty(this.$ref)) {
return false;
}
// JSON Schema draft v4 (core definitions and terminology referenced)
// 7.2 URI resolution scope alteration with the 'id'
if (!this.isEmpty(this.id)) {
return false;
}
// 3.4 Root schema, subschema (7.2.2 Usage)
if (!this.isEmpty(this.$schema)) {
return false;
}
// 6.1 Metadata keywords 'title' and 'description'
if (!this.isEmpty(this.title)) {
return false;
}
if (!this.isEmpty(this.description)) {
return false;
}
// 5.5. Validation keywords for any instance type (Type moved up here from the rest of 5.5 below for output formatting)
if (!this.isEmpty(this.type)) {
return false;
}
// 5.1. Validation keywords for numeric instances (number and integer)
if (!this.isEmpty(this.multipleOf)) {
return false;
}
if (!this.isEmpty(this.minimum)) {
return false;
}
if (!this.isEmpty(this.exclusiveMinimum) && this.exclusiveMinimum !== false) {
return false;
}
if (!this.isEmpty(this.maximum)) {
return false;
}
if (!this.isEmpty(this.exclusiveMaximum) && this.exclusiveMaximum !== false) {
return false;
}
// 5.2. Validation keywords for strings
if (!this.isEmpty(this.minLength) && this.minLength !== 0) {
return false;
}
if (!this.isEmpty(this.maxLength)) {
return false;
}
if (!this.isEmpty(this.pattern)) {
return false;
}
// 5.5. Validation keywords for any instance type
if (!this.isEmpty(this.enum)) {
return false;
}
if (!this.isEmpty(this.allOf)) {
return false;
}
if (!this.isEmpty(this.anyOf)) {
return false;
}
if (!this.isEmpty(this.oneOf)) {
return false;
}
if (!this.isEmpty(this.not)) {
return false;
}
// 6.2 Default
if (!this.isEmpty(this.default)) {
return false;
}
// 7 Semantic validation with 'format'
if (!this.isEmpty(this.format)) {
return false;
}
// 5.4.5. Dependencies
if (!this.isEmpty(this.dependencies)) {
return false;
}
// 5.3. Validation keywords for arrays
if (!this.isEmpty(this.additionalItems)) {
return false;
}
if (!this.isEmpty(this.maxItems)) {
return false;
}
if (!this.isEmpty(this.minItems) && this.minItems != 0) {
return false;
}
if (!this.isEmpty(this.uniqueItems) && this.uniqueItems !== false) {
return false;
}
if (!this.isEmpty(this.items)) {
return false;
}
// 5.4. Validation keywords for objects
if (!this.isEmpty(this.maxProperties)) {
return false;
}
if (!this.isEmpty(this.minProperties) && this.minProperties !== 0) {
return false;
}
if (!this.isEmpty(this.additionalProperties)) {
return false;
}
if (!this.isEmpty(this.properties)) {
return false;
}
if (!this.isEmpty(this.patternProperties)) {
return false;
}
if (!this.isEmpty(this.required)) {
return false;
}
if (!this.isEmpty(this.definitions)) {
return this.definitions.isBlank();
}
if (!this.isEmpty(this.subSchemas)) {
return false;
}
return true;
}
/**
* Sets a subSchema on the targetSchema. The targetSchema is not updated because it represents the active XSD Namespace.
*
* @param {String} schemaName - the name of the subschema.
* @param {JsonSchemaFile} subSchema - a JsonSchemaFile representing the subschema.
*
* @returns {JsonSchemaFile} subSchema - the subSchema parameter is returned for chaining or for use updating the targetSchema
* if constructing a schema manually.
*/
setSubSchema(schemaName, subSchema) {
this.targetSchema.subSchemas[schemaName] = subSchema;
return subSchema;
}
/**
* Performs a recursive search through all subschemas for a schema with the given name.
*
* @param {String} searchName - The name of the subschema to return.
* @returns {JsonSchemaFile} - Returns a JsonSchemaFile representing the requested subschema if found.
*/
getSubschema(searchName) {
var retval;
if (this.subSchemas[searchName] != undefined) {
retval = this.subSchemas[searchName];
} else {
Object.keys(this.subSchemas).forEach(function (subschemaName, index, array) {
retval = this.subSchemas[subschemaName].getSubschema(searchName);
}, this);
}
return retval;
}
// Read-only properties
/**
* Returns a $ref limited to the JSON Pointer in the ref URI fragement if the $ref is being used internally to this file. Otherwise, the full ref URI is returned.
*
* @param {JsonSchemaFile} parent - the parent of this $ref
* @returns {JsonSchemaFile} - a JsonSchemaFile representing a $ref to itself.
*/
get$RefToSchema(parent) {
let refStr;
if(parent == undefined) {
throw new Error('Parameter "parent" is required');
}
if (this.ref == undefined) {
refStr = this.$ref
} else if (Object.is(parent.getTopLevelJsonSchema(), this.getTopLevelJsonSchema())) {
refStr = '#' + this.ref.fragment();
} else {
refStr = this.ref.toString();
}
return this.newJsonSchemaFile({
$ref: refStr,
parent: parent
});
}
/**
* Returns a JSON Pointer representation of the targetNamespace, which is generally based on a URL.
*
* @returns {String} - JSON Pointer representation of the targetNamespace.
*/
getSubschemaJsonPointer() {
if (this.namespaceMode == Constants.SUBSCHEMA) {
return utils.getSafeNamespace(this.targetNamespace);
}
return '/' + Constants.DEFINITIONS;
}
findTopLevelSchema(type) {
if (type.parent === undefined) {
return type;
}
return this.findTopLevelSchema(type.parent);
}
/**
* Returns the top level JSON Schema for this schema by the parent without a parent.
*
* @returns {JsonSchemaFile} - The top JsonSchemaFile representing a single file.
*/
getTopLevelJsonSchema() {
if (this.parent === undefined) {
return this;
}
return this.findTopLevelSchema(this.parent);
}
/**
* Returns the subschema used to track global attributes initiazing the subschema if needed.
*
* @returns {JsonSchemaFile} - The subschema used to track global attributes.
*/
getGlobalAttributesSchema() {
if (this.subSchemas[Constants.GLOBAL_ATTRIBUTES_SCHEMA_NAME] == undefined) {
this.subSchemas[Constants.GLOBAL_ATTRIBUTES_SCHEMA_NAME] = this.newJsonSchemaFile();
}
return this.subSchemas[Constants.GLOBAL_ATTRIBUTES_SCHEMA_NAME];
}
/**
* Returns a POJO of this jsonSchema. Items are added in the order we wouild like them to appear in the resulting JsonSchema.
*
* @param {JsonSchemaSerializer} serializer - the serializer to be used to serialize this JsonSchemaFile into a POJO
* @returns {Object} - POJO of this jsonSchema.
*/
getJsonSchema(serializer) {
if(serializer == undefined) {
throw new Error('Parameter "serializer" is required');
}
const pojo = serializer.serialize(this);
return pojo;
}
/**
* Returns a deep copy of this JsonSchemaFile.
*
* @returns {JsonSchemaFile} - A deep copy of this JsonSchemaFile.
*/
clone() {
return clone(this, true);
}
/**
* Returns true if the a deep copy of this JsonSchemaFile.
*
* @param {JsonSchemaFile} other - The JsonSchemaFile to compare with this for equality.
* @returns {Boolean} - true if the JsonSchemaFile objects are equal.
*/
equals(other) {
return deepEql(this, other);
}
/**
* Adds a String value to the enum array removing any duplicates.
*
* @param {String} val - The string value to add to the enum array.
* @returns {void}
*/
addEnum(val) {
if(this.enum.indexOf(val) == -1) {
this.enum.push(val);
}
}
/**
* Adds a String value to the required array.
*
* @param {String} _required - String value to be added to the required array.
* @returns {void}
*/
addRequired(_required) {
this.required.push(_required);
}
/**
* Returns the JsonSchemaFile property that corresponds to the given propertyName value.
*
* @param {String} propertyName - The name of the property to return.
* @returns {JsonSchemaFile} - The JsonSchemaFile property that corresponds to the given propertyName value.
*/
getProperty(propertyName) {
return this.properties[propertyName];
}
/**
* Sets the value of the given propertyName to the jsonSchema provided in the type parameter.
*
* @param {String} propertyName - The name of the property
* @param {JsonSchemaFile} type - The jsonSchema for the given propertyName
* @returns {void}
*/
setProperty(propertyName, type) {
this.properties[propertyName] = type;
}
/**
* The notion of extending a base schema is implemented in JSON Schema using allOf with schemas. The base
* type is added to the allOf array as well as a new schema. The new schema is returned to be built out
* as the working schema.
*
* @param {JsonSchemaFile} baseType - JSON Schema of the base type.
* @param {JsonSchemaFile} [extensionType] - One of the seven core JSON Schema types.
* @returns {void}
*/
extend(baseType, extensionType) {
if (baseType == undefined) {
throw new Error('Required parameter "baseType" is undefined');
}
this.allOf.push(baseType.get$RefToSchema(this));
const extensionSchema = this.newJsonSchemaFile();
if (extensionType != undefined) {
extensionSchema.type = extensionType;
}
this.allOf.push(extensionSchema);
return extensionSchema;
}
addOneOfSchema(oneOfSchema) {
if (this.oneOf === undefined) {
this.oneOf = this.newJsonSchemaFile();
}
}
/**
* Creates a property with a name prefixed by the @sign to represet an XML attribute.
*
* @param {String} propertyName - Name of the new property.
* @param {JsonSchemaFile} customType - JsonSchema governing the new property.
* @param {String} minOccursAttr - If this optional parameter equals 'required' the new property will
* be added to the jsonSchema's required array.
* @returns {void}
*/
addAttributeProperty(propertyName, customType, minOccursAttr) {
if (propertyName == undefined) {
throw new Error('Required parameter "propertyName" is undefined');
}
if (customType == undefined) {
throw new Error('Required parameter "customType" is undefined');
}
const name = '@' + propertyName;
if (minOccursAttr === XsdAttributeValues.REQUIRED) {
this.addRequired(name);
}
this.setProperty(name, customType);
}
/**
* Adds the given property and lists it in the anyOf array as a singular required property. This is used to
* expose a type from a subschema so it can be used in validation.
*
* @see {@link NamespaceManager#getType|NamespaceManager.getType()}
* @param {String} name - The name of the property to be added.
* @param {JsonSchema} type - The property to be added.
* @returns {void}
*/
addRequiredAnyOfPropertyByReference(name, type) {
if (name == undefined) {
throw new Error('Required parameter "name" is undefined');
}
if (type == undefined) {
throw new Error('Required parameter "type" is undefined');
}
// if (this.getProperty(name) == undefined) {
var anyOfProp = this.newJsonSchemaFile();
anyOfProp.addRequired(name);
this.anyOf.push(anyOfProp);
this.setProperty(name, type);
// } else {
// const msg = this.id + ' - Unable to add required anyOf property by reference because [' + name + '] is already defined as [' + this.getProperty(name) + '] Not adding [' + type + ']';
//debug(msg);
// throw new Error(msg);
// }
}
/**
* Returns true if the propertyName parameter represents a defined property dependency. A
* dependency is considered a defined property dependency if it is defined as an array.
*
* @param {String} propertyName - The Name of the property that may represent a property dependency
* as defined in 5.4.5 above.
* @returns {Boolean} - True if the propertyName parameter represents a defined property dependency.
*/
isPropertyDependencyDefined(propertyName) {
if (propertyName == undefined) {
throw new Error('Required parameter "propertyName" is undefined');
}
if (this.dependencies[propertyName] != undefined && Array.isArray(this.dependencies[propertyName])) {
return true;
}
return false;
}
/**
* Adds a property dependency allocating the dependency's array if needed.
*
* @param {String} propertyName - The name of the property that will have a new dependency added.
* @param {String} dependencyProperty - The name of the property that propertyName is dependent on.
* @returns {void}
*/
addPropertyDependency(propertyName, dependencyProperty) {
if (propertyName == undefined) {
throw new Error('Required parameter "propertyname" is undefined');
}
if (dependencyProperty == undefined) {
throw new Error('Required parameter "dependencyProperty" is undefined');
}
if (this.isPropertyDependencyDefined(propertyName)) {
throw new Error('Property dependency already defined. "' + propertyName + '"');
}
if (this.dependencies[propertyName] == undefined) {
this.dependencies[propertyName] = [];
}
this.dependencies[propertyName].push(dependencyProperty);
}
/**
* Adds a jsonSchema as a schema dependency with the given name.
*
* @param {String} propertyName - The name of the property that will have a new dependency added.
* @param {JsonSchemaFile} dependencySchema - The jsonSchema representing the schema dependecy
* as defined in 5.4.5 above.
* @returns {void}
*/
addSchemaDependency(propertyName, dependencySchema) {
if (propertyName == undefined) {
throw new Error('Required parameter "propertyname" is undefined');
}
if (dependencySchema == undefined) {
throw new Error('Required parameter "dependencySchema" is undefined');
}
if (this.dependencies[propertyName] == undefined) {
this.dependencies[propertyName] = dependencySchema;
} else {
throw new Error('Unable to add schema dependency because [' + propertyName + '] is already defined as [' + this.dependencies[propertyName] + '] Not adding [' + dependencySchema + ']');
}
}
/**
* Removes any empty JsonSchemaFile entries from the given Array.
*
* @see {@link BaseConversionVisitor#exitState|BaseConversionVisitor.exitState()}
* @param {Array} array - Array from which emtpy JsonSchemas will be removed.
* @returns {void}
*/
removeEmptySchemasFromArray(array) {
if (array == undefined) {
throw new Error('Required parameter "array" is undefined');
}
// Run throught the array back to front removing any blank schemas.
for (let pos = array.length - 1; pos >= 0; pos--) {
if (array[pos].isBlank()) {
array.splice(pos, 1);
}
}
}
/**
* Remove empty schema's from this jsonSchema's array properties.
*
* @see {@link BaseConversionVisitor#exitState|BaseConversionVisitor.exitState()}
* @returns {void}
*/
removeEmptySchemas() {
this.removeEmptySchemasFromArray(this.allOf);
this.removeEmptySchemasFromArray(this.anyOf);
this.removeEmptySchemasFromArray(this.oneOf);
}
isForwardRef() {
return false;
}
isRef() {
return !(this.$ref == undefined)
}
}
module.exports = JsonSchemaFile;
}).call(this)}).call(this,require('_process'))
},{"../constants":91,"../propertyDefinable":110,"../utils":113,"../xmlschema/xsdAttributeValues":119,"./jsonSchemaTypes":106,"_process":129,"clone":2,"debug":3,"deep-eql":5,"path":128,"path-browserify":7,"urijs":11}],98:[function(require,module,exports){
(function (process){(function (){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFileDraft04');
const path = (process && typeof process.platform === 'string') ? require('path') : require('path-browserify');
const URI = require('urijs');
const JsonSchemaFile = require('./jsonSchemaFile');
const JsonSchemaSerializerDraft04 = require('./jsonSchemaSerializerDraft04');
/**
* JSON Schema file operations. This is based on the JSON Schema meta-schema located at http://json-schema.org/draft-04/schema#.
*
*
* Please see http://json-schema.org for more details.
*/
class JsonSchemaFileDraft04 extends JsonSchemaFile {
constructor(options) {
if (options != undefined) {
options.$schema = options.$schema != undefined ? options.$schema : 'http://json-schema.org/draft-04/schema#';
options.schemaId = options.schemaId != undefined ? options.schemaId : 'id';
}
super(options);
}
/**
* Creates a child JsonSchemaFile using the given options. The parent is set automatically.
*
* @param {Object} options - An object used to override default options.
* @param {string} options.baseFilename - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.id - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.targetNamespace - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.title - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.$ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {JsonSchemaFile} options.parent - If this parameter is not set the parent will be the current JsonSchemaFile.
*
* @returns {JsonSchemaFileDraft04} - Returns a new JsonSchemaFileDraft04 that has the current JsonSchemaFile as its parent.
*/
newJsonSchemaFile(options) {
if (options != undefined) {
if (options.parent == undefined) {
options.parent = this;
}
return new JsonSchemaFileDraft04(options);
} else {
return new JsonSchemaFileDraft04({ parent: this });
}
}
/**
* Returns a POJO of this jsonSchema. Items are added in the order we wouild like them to appear in the resulting JsonSchema.
*
* @returns {Object} - POJO of this jsonSchema.
*/
getJsonSchema(serializer) {
if (serializer == undefined) {
serializer = new JsonSchemaSerializerDraft04();
}
return super.getJsonSchema(serializer);
}
toString() {
return JSON.stringify(this.getJsonSchema(), null, '\t');
}
}
module.exports = JsonSchemaFileDraft04;
}).call(this)}).call(this,require('_process'))
},{"./jsonSchemaFile":97,"./jsonSchemaSerializerDraft04":103,"_process":129,"debug":3,"path":128,"path-browserify":7,"urijs":11}],99:[function(require,module,exports){
(function (process){(function (){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFileDraft06');
const path = (process && typeof process.platform === 'string') ? require('path') : require('path-browserify');
const URI = require('urijs');
const JsonSchemaFileDraft04 = require('./jsonSchemaFileDraft04');
const JsonSchemaSerializerDraft06 = require('./jsonSchemaSerializerDraft06');
/**
* JSON Schema file operations. This is based on the JSON Schema meta-schema located at http://json-schema.org/draft-04/schema#.
*
*
* Please see http://json-schema.org for more details.
*/
class JsonSchemaFileDraft06 extends JsonSchemaFileDraft04 {
constructor(options) {
if (options != undefined) {
options.$schema = options.$schema != undefined ? options.$schema : 'http://json-schema.org/draft-06/schema#';
options.schemaId = options.schemaId != undefined ? options.schemaId : '$id';
}
super(options);
// Redefine exclusiveMaximum & exclusiveMinimum as numeric to comply with the new draft-v6 definition.
super.defineNumericProperty('exclusiveMaximum');
super.defineNumericProperty('exclusiveMinimum');
super.defineObjectProperty('propertyNames');
super.defineArrayProperty('contains');
super.defineArrayProperty('const');
super.defineArrayProperty('examples');
}
/**
* Creates a child JsonSchemaFile using the given options. The parent is set automatically.
*
* @param {Object} options - An object used to override default options.
* @param {string} options.baseFilename - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.baseId - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.targetNamespace - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.title - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.$ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {JsonSchemaFile} options.parent - If this parameter is not set the parent will be the current JsonSchemaFile.
*
* @returns {JsonSchemaFileDraft06} - Returns a new JsonSchemaFileDraft06 that has the current JsonSchemaFile as its parent.
*/
newJsonSchemaFile(options) {
if (options != undefined) {
if (options.parent == undefined) {
options.parent = this;
}
return new JsonSchemaFileDraft06(options);
} else {
return new JsonSchemaFileDraft06({ parent: this });
}
}
/**
* Returns a POJO of this jsonSchema. Items are added in the order we wouild like them to appear in the resulting JsonSchema.
*
* @returns {Object} - POJO of this jsonSchema.
*/
getJsonSchema(serializer) {
if (serializer == undefined) {
serializer = new JsonSchemaSerializerDraft06();
}
return super.getJsonSchema(serializer);
}
toString() {
return JSON.stringify(this.getJsonSchema(), null, '\t');
}
}
module.exports = JsonSchemaFileDraft06;
}).call(this)}).call(this,require('_process'))
},{"./jsonSchemaFileDraft04":98,"./jsonSchemaSerializerDraft06":104,"_process":129,"debug":3,"path":128,"path-browserify":7,"urijs":11}],100:[function(require,module,exports){
(function (process){(function (){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFileDraft07');
const path = (process && typeof process.platform === 'string') ? require('path') : require('path-browserify');
const URI = require('urijs');
const JsonSchemaFileDraft06 = require('./jsonSchemaFileDraft06');
const JsonSchemaSerializerDraft07 = require('./jsonSchemaSerializerDraft07');
/**
* JSON Schema file operations. This is based on the JSON Schema meta-schema located at http://json-schema.org/draft-04/schema#.
*
*
* Please see http://json-schema.org for more details.
*/
class JsonSchemaFileDraft07 extends JsonSchemaFileDraft06 {
constructor(options) {
if (options !== undefined) {
options.$schema = options.$schema != undefined ? options.$schema : 'http://json-schema.org/draft-07/schema#';
}
super(options);
}
/**
* Creates a child JsonSchemaFile using the given options. The parent is set automatically.
*
* @param {Object} options - An object used to override default options.
* @param {string} options.baseFilename - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.baseId - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.targetNamespace - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.title - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {string} options.$ref - The directory from which xml schema's should be loaded. The default value is the current directory.
* @param {JsonSchemaFile} options.parent - If this parameter is not set the parent will be the current JsonSchemaFile.
*
* @returns {JsonSchemaFileDraft07} - Returns a new JsonSchemaFileDraft07 that has the current JsonSchemaFile as its parent.
*/
newJsonSchemaFile(options) {
if (options != undefined) {
if (options.parent == undefined) {
options.parent = this;
}
return new JsonSchemaFileDraft07(options);
} else {
return new JsonSchemaFileDraft07({ parent: this });
}
}
/**
* Returns a POJO of this jsonSchema. Items are added in the order we wouild like them to appear in the resulting JsonSchema.
*
* @returns {Object} - POJO of this jsonSchema.
*/
getJsonSchema(serializer) {
if (serializer == undefined) {
serializer = new JsonSchemaSerializerDraft07();
}
return super.getJsonSchema(serializer);
}
toString() {
return JSON.stringify(this.getJsonSchema(), null, '\t');
}
}
module.exports = JsonSchemaFileDraft07;
}).call(this)}).call(this,require('_process'))
},{"./jsonSchemaFileDraft06":99,"./jsonSchemaSerializerDraft07":105,"_process":129,"debug":3,"path":128,"path-browserify":7,"urijs":11}],101:[function(require,module,exports){
'use strict';
/**
* Defines constants for the JSON Schema semantic validation defined formats. For more information please see:
* {@link http://json-schema.org/latest/json-schema-validation.html#rfc.section.7|Semantic validation with 'format'}
*
* @module JsonSchemaFormats
*/
module.exports = {
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.1|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.1|IETF}
*/
DATE_TIME: 'date-time',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.2|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.2|IETF}
*/
EMAIL : 'email',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.3|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.3|IETF}
*/
HOSTNAME: 'hostname',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.4|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.4|IETF}
*/
IPV4: 'ipv4',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.5|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.5|IETF}
*/
IPV6: 'ipv6',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.6|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.6|IETF}
*/
URI: 'uri',
/**
* {@link http://json-schema.org/draft-04/json-schema-validation.html#rfc.section.7.3.7|main site}|
* {@link https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-7.3.7|IETF}
*/
URIREF: 'uriref',
// draft-06 {@link https://json-schema.org/draft-06/json-schema-release-notes.html|Release Notes}
/**
* Allows relative URI references per RFC 3986; see the section in the draft-06 release notes about "uri" as a format
*/
URI_REFERENCE: 'uri-reference',
/**
* Indicates an RFC 6570 conforming URI Template value, as is used in JSON Hyper-Schema for "href"
*/
URI_TEMPLATE: 'uri-template',
/**
* Indicates a JSON Pointer value such as /foo/bar; do not use this for JSON Pointer URI fragments such as #/foo/bar: the proper format for those is "uri-reference"
*/
JSON_POINTER: 'json-pointer',
/**
* Array of examples with no validation effect; the value of "default" is usable as an example without repeating it under this keyword
*/
EXAMPLES: 'examples'
}
},{}],102:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaRef');
const JsonSchemaFile = require('./jsonSchemaFile');
const JsonSchemaSerializerDraft04 = require('./jsonSchemaSerializerDraft04');
const references_NAME = Symbol();
const resovled_NAME = Symbol();
const forwardReference_NAME = Symbol();
const properties = [
'references',
'resolved',
'forwardReference'
];
class JsonSchemaRef extends JsonSchemaFile {
constructor(options) {
if (options == undefined) {
throw new Error('Parameter "options" is required');
}
if (options.ref == undefined && options.$ref == undefined) {
throw new Error('Either options.ref or options.$ref must be supplied');
}
if (options.forwardReference == undefined) {
throw new Error('Parameter options.forwardReference is required');
}
options.properties = properties;
super(options)
this.references = [];
this.resolved = false;
this.forwardReference = options.forwardReference;
}
// Getters/Setters
get references() {
return this[references_NAME];
}
set references(newReferences) {
this[references_NAME] = newReferences;
}
get resolved() {
return this[resovled_NAME];
}
set resolved(newResolved) {
this[resovled_NAME] = newResolved;
}
get forwardReference() {
return this[forwardReference_NAME];
}
set forwardReference(newForwardReference) {
this[forwardReference_NAME] = newForwardReference;
}
get$RefToSchema(parent) {
let refStr;
if(parent == undefined) {
throw new Error('Parameter "parent" is required');
}
if (this.ref == undefined) {
refStr = this.$ref
} else if (Object.is(parent.getTopLevelJsonSchema(), this.getTopLevelJsonSchema())) {
refStr = '#' + this.ref.fragment();
} else {
refStr = this.ref.toString();
}
const ref = new JsonSchemaRef({
$ref: refStr,
parent: parent,
forwardReference: this.forwardReference
});
this.references.push(ref);
return ref;
}
resolveRef(type) {
this.references.forEach(function (ref, index, array) {
ref.resolveRef(type);
})
if (type.ref == undefined) {
this.$ref = type.$ref.toString();
} else {
this.$ref = type.ref.toString();
}
this.resolved = true;
}
isForwardRef() {
return true;
}
/**
* Returns a POJO of this jsonSchema. Items are added in the order we wouild like them to appear in the resulting JsonSchema.
*
* @returns {Object} - POJO of this jsonSchema.
*/
getJsonSchema(serializer) {
if (serializer == undefined) {
// Any of the serializers are fine for a JsonSchemaRef.
serializer = new JsonSchemaSerializerDraft04();
}
return super.getJsonSchema(serializer);
}
toString() {
return JSON.stringify(this.getJsonSchema(), null, '\t');
}
}
module.exports = JsonSchemaRef;
},{"./jsonSchemaFile":97,"./jsonSchemaSerializerDraft04":103,"debug":3}],103:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFile');
const PropertyDefinable = require('../propertyDefinable');
const DEFAULT_DRAFT04_ORDER = [
'$ref',
'id',
'subSchemas',
'$schema',
'title',
'description',
'default',
'format',
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'properties',
'patternProperties',
'dependencies',
'enum',
'type',
'allOf',
'anyOf',
'oneOf',
'not',
'definitions'
];
/**
* Class representing a serializer for an instance of JsonSchemaFileDraft04.
*/
class JsonSchemaSerializerDraft04 extends PropertyDefinable {
constructor() {
super();
super.defineObjectProperty('jsonSchemaPojo');
this.jsonSchemaPojo = {};
}
serialize(jsonSchema, customOrder) {
const order = customOrder == undefined ? DEFAULT_DRAFT04_ORDER : customOrder;
this.jsonSchemaPojo = {};
order.forEach(function(fn, index, array) {
this[fn](jsonSchema);
}, this);
return this.jsonSchemaPojo;
}
$ref(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.$ref)) {
this.jsonSchemaPojo.$ref = jsonSchema.$ref;
}
}
id(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.id)) {
//jsonSchema.id = jsonSchema.id;
this.jsonSchemaPojo[jsonSchema.schemaId] = jsonSchema.id
}
}
$schema(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.$schema)) {
this.jsonSchemaPojo.$schema = jsonSchema.$schema;
}
}
// 6.1 Metadata keywords 'title' and 'description'
title(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.title)) {
this.jsonSchemaPojo.title = jsonSchema.title;
}
}
description(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.description)) {
this.jsonSchemaPojo.description = jsonSchema.description;
}
}
// 5.5. Validation keywords for any instance type (Type moved up here from the rest of 5.5 below for output formatting)
type(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.type)) {
this.jsonSchemaPojo.type = jsonSchema.type;
}
}
// 5.1. Validation keywords for numeric instances (number and integer)
multipleOf(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.multipleOf)) {
this.jsonSchemaPojo.multipleOf = jsonSchema.multipleOf;
}
}
minimum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.minimum)) {
this.jsonSchemaPojo.minimum = jsonSchema.minimum;
}
}
exclusiveMinimum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.exclusiveMinimum) && jsonSchema.exclusiveMinimum !== false) {
this.jsonSchemaPojo.exclusiveMinimum = jsonSchema.exclusiveMinimum;
}
}
maximum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.maximum)) {
this.jsonSchemaPojo.maximum = jsonSchema.maximum;
}
}
exclusiveMaximum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.exclusiveMaximum) && jsonSchema.exclusiveMaximum !== false) {
this.jsonSchemaPojo.exclusiveMaximum = jsonSchema.exclusiveMaximum;
}
}
// 5.2. Validation keywords for strings
minLength(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.minLength) && jsonSchema.minLength !== 0) {
this.jsonSchemaPojo.minLength = jsonSchema.minLength;
}
}
maxLength(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.maxLength)) {
this.jsonSchemaPojo.maxLength = jsonSchema.maxLength;
}
}
pattern(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.pattern)) {
this.jsonSchemaPojo.pattern = jsonSchema.pattern;
}
}
// 5.5. Validation keywords for any instance type
enum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.enum)) {
this.jsonSchemaPojo.enum = jsonSchema.enum;
}
}
allOf(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.allOf)) {
this.jsonSchemaPojo.allOf = [];
for (let i = 0; i < jsonSchema.allOf.length; i++) {
this.jsonSchemaPojo.allOf[i] = jsonSchema.allOf[i].getJsonSchema();
}
}
}
anyOf(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.anyOf)) {
this.jsonSchemaPojo.anyOf = [];
for (let i = 0; i < jsonSchema.anyOf.length; i++) {
this.jsonSchemaPojo.anyOf[i] = jsonSchema.anyOf[i].getJsonSchema();
}
}
}
oneOf(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.oneOf)) {
this.jsonSchemaPojo.oneOf = [];
for (let i = 0; i < jsonSchema.oneOf.length; i++) {
this.jsonSchemaPojo.oneOf[i] = jsonSchema.oneOf[i].getJsonSchema();
}
}
}
not(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.not)) {
this.jsonSchemaPojo.not = jsonSchema.not.getJsonSchema();
}
}
// 6.2 Default
default(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.default)) {
this.jsonSchemaPojo.default = jsonSchema.default;
}
}
// 7 Semantic validation with 'format'
format(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.format)) {
this.jsonSchemaPojo.format = jsonSchema.format;
}
}
// 5.4.5. Dependencies
dependencies(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.dependencies)) {
this.jsonSchemaPojo.dependencies = {}
const propKeys = Object.keys(jsonSchema.dependencies);
propKeys.forEach(function (key, index, array) {
if (Array.isArray(jsonSchema.dependencies[key])) {
this.jsonSchemaPojo.dependencies[key] = jsonSchema.dependencies[key]; // property dependency
} else {
if (jsonSchema.dependencies[key] !== undefined) {
this.jsonSchemaPojo.dependencies[key] = jsonSchema.dependencies[key].getJsonSchema(); // schema dependency
}
}
}, this);
}
}
// 5.3. Validation keywords for arrays
additionalItems(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.additionalItems)) {
if (typeof (jsonSchema.additionalItems) === 'boolean') {
this.jsonSchemaPojo.additionalItems = jsonSchema.additionalItems;
} else {
this.jsonSchemaPojo.additionalItems = jsonSchema.additionalItems.getJsonSchema();
}
}
}
maxItems(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.maxItems)) {
this.jsonSchemaPojo.maxItems = jsonSchema.maxItems;
}
}
minItems(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.minItems) && jsonSchema.minItems != 0) {
this.jsonSchemaPojo.minItems = jsonSchema.minItems;
}
}
uniqueItems(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.uniqueItems) && jsonSchema.uniqueItems !== false) {
this.jsonSchemaPojo.uniqueItems = jsonSchema.uniqueItems;
}
}
items(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.items)) {
if (Array.isArray(jsonSchema.items)) {
this.jsonSchemaPojo.items = [];
jsonSchema.items.forEach(function (item, index, array) {
this.jsonSchemaPojo.items[index] = item.getJsonSchema();
}, this);
} else {
this.jsonSchemaPojo.items = jsonSchema.items.getJsonSchema();
}
}
}
// 5.4. Validation keywords for objects
maxProperties(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.maxProperties)) {
this.jsonSchemaPojo.maxProperties = jsonSchema.maxProperties;
}
}
minProperties(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.minProperties) && jsonSchema.minProperties !== 0) {
this.jsonSchemaPojo.minProperties = jsonSchema.minProperties;
}
}
additionalProperties(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.additionalProperties)) {
this.jsonSchemaPojo.additionalProperties = jsonSchema.additionalProperties;
}
}
properties(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.properties)) {
this.jsonSchemaPojo.properties = {};
const propKeys = Object.keys(jsonSchema.properties);
propKeys.forEach(function (key, index, array) {
if (jsonSchema.properties[key] !== undefined) {
this.jsonSchemaPojo.properties[key] = jsonSchema.properties[key].getJsonSchema();
}
}, this);
}
}
patternProperties(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.patternProperties)) {
this.jsonSchemaPojo.patternProperties = {};
const propKeys = Object.keys(jsonSchema.patternProperties);
propKeys.forEach(function (key, index, array) {
if (jsonSchema.patternProperties[key] !== undefined) {
this.jsonSchemaPojo.patternProperties[key] = jsonSchema.patternProperties[key].getJsonSchema();
}
}, this);
}
}
required(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.required)) {
this.jsonSchemaPojo.required = jsonSchema.required;
}
}
definitions(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.definitions)) {
this.jsonSchemaPojo.definitions = jsonSchema.definitions.getJsonSchema();
}
}
subSchemas(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.subSchemas)) {
const subschemaNames = Object.keys(jsonSchema.subSchemas);
subschemaNames.forEach(function (subschemaName, index, array) {
try {
this.jsonSchemaPojo[subschemaName] = jsonSchema.subSchemas[subschemaName].getJsonSchema();
} catch (err) {
debug(err);
debug(jsonSchema.subSchemas);
throw err;
}
}, this);
}
}
}
module.exports = JsonSchemaSerializerDraft04;
},{"../propertyDefinable":110,"debug":3}],104:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFile');
const JsonSchemaSerializerDraft04 = require('./jsonSchemaSerializerDraft04');
const DEFAULT_DRAFT06_ORDER = [
'$ref',
'id',
'subSchemas',
'$schema',
'title',
'description',
'default',
'format',
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'properties',
'patternProperties',
'dependencies',
'enum',
'type',
'allOf',
'anyOf',
'oneOf',
'not',
'definitions'
];
/**
* Class representing a serializer for an instance of JsonSchemaFileDraft06.
*/
class JsonSchemaSerializerDraft06 extends JsonSchemaSerializerDraft04 {
constructor() {
super();
super.defineObjectProperty('jsonSchemaPojo');
this.jsonSchemaPojo = {};
}
serialize(jsonSchema, customOrder) {
const order = customOrder == undefined ? DEFAULT_DRAFT06_ORDER : customOrder;
return super.serialize(jsonSchema, order);
}
exclusiveMinimum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.exclusiveMinimum)) {
this.jsonSchemaPojo.exclusiveMinimum = jsonSchema.exclusiveMinimum;
}
}
exclusiveMaximum(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.exclusiveMaximum)) {
this.jsonSchemaPojo.exclusiveMaximum = jsonSchema.exclusiveMaximum;
}
}
}
module.exports = JsonSchemaSerializerDraft06;
},{"./jsonSchemaSerializerDraft04":103,"debug":3}],105:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:JsonSchemaFile');
const JsonSchemaSerializerDraft06 = require('./jsonSchemaSerializerDraft06');
const DEFAULT_DRAFT07_ORDER = [
'$ref',
'id',
'subSchemas',
'$schema',
'title',
'description',
'default',
'format',
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'properties',
'patternProperties',
'dependencies',
'enum',
'type',
'allOf',
'anyOf',
'oneOf',
'not',
'definitions',
'contentEncoding'
];
/**
* Class representing a serializer for an instance of JsonSchemaFileDraft06.
*/
class JsonSchemaSerializerDraft07 extends JsonSchemaSerializerDraft06 {
constructor() {
super();
super.defineObjectProperty('jsonSchemaPojo');
this.jsonSchemaPojo = {};
}
serialize(jsonSchema, customOrder) {
const order = customOrder == undefined ? DEFAULT_DRAFT07_ORDER : customOrder;
return super.serialize(jsonSchema, order);
}
contentEncoding(jsonSchema) {
if (!jsonSchema.isEmpty(jsonSchema.contentEncoding)) {
this.jsonSchemaPojo.contentEncoding = jsonSchema.contentEncoding;
}
}
}
module.exports = JsonSchemaSerializerDraft07;
},{"./jsonSchemaSerializerDraft06":104,"debug":3}],106:[function(require,module,exports){
'use strict';
/**
* Defines constants for the JSON Schema primitive types. For more information please see
* {@link http://json-schema.org/latest/json-schema-core.html#rfc.section.4.2}
*
* @module JsonSchemaTypes
*/
module.exports = {
/**
* Indicates a JSON Schema array type.
*/
ARRAY: 'array',
/**
* Indicates a JSON Schema boolean type.
*/
BOOLEAN: 'boolean',
/**
* Indicates a JSON Schema integer type.
*/
INTEGER: 'integer',
/**
* Indicates a JSON Schema number type.
*/
NUMBER: 'number',
/**
* Indicates a JSON Schema null type.
*/
NULL: 'null',
/**
* Indicates a JSON Schema object type.
*/
OBJECT: 'object',
/**
* Indicates a JSON Schema string type.
*/
STRING: 'string'
}
},{}],107:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:NamespaceManager');
const URI = require('urijs');
const XsdAttributes = require('./xmlschema/xsdAttributes');
const JsonSchemaFileDraft04 = require('./jsonschema/jsonSchemaFileDraft04');
const JsonSchemaFileDraft06 = require('./jsonschema/jsonSchemaFileDraft06');
const JsonSchemaFileDraft07 = require('./jsonschema/jsonSchemaFileDraft07');
const Qname = require('./qname');
const CONSTANTS = require('./constants');
const ForwardReference = require('./forwardReference');
const namespaces_NAME = Symbol();
const builtInTypeConverter_NAME = Symbol();
const jsonSchema_NAME = Symbol();
const xmlSchemas_NAME = Symbol();
const forwardReferences_NAME = Symbol();
const jsonSchemaVersion_NAME = Symbol();
/**
* Class responsible for managaging namespaces and types within those namespaces, which are defined as
* XML Schema aggregates that have been converted to JSON Schema. Types are arranged by XML
* Namespaces. Types can be added and retrieved as needed.
*
* This module also manages global attributes. As a reminder global attributes are global accross all XML
* Schema files being considered. This includes schemas that are brought in by an *<include>* tag
* or by an *<import>* tag.
*
* An object is used to manage any number of XML Namespaces including a specialized namespace for global
* attributes and the XSD well known namespaces. Namespaces are themselves JSON objects with one property named types. Initially,
* the collection of namespaces contains only the globalAttributes specialized namespace. Additional
* namespaces will be added to the collection as they are encountered.
*
* <pre>
* this.namespaces = {};
* this.namespaces[''] = { types: {} };
* this.namespaces.globalAttributes = { types: {} };
* </pre>
*
* @module NamespaceManager
*/
class NamespaceManager {
constructor(options) {
this.namespaces = {};
this.addNamespace(CONSTANTS.GLOBAL_ATTRIBUTES_SCHEMA_NAME);
this.addNamespace(CONSTANTS.XML_SCHEMA_NAMESPACE);
if (options == undefined) {
throw new Error('Parameter "options" is required');
}
if (options.jsonSchemaVersion == undefined) {
throw new Error('Parameter options.jsonSchemaVersion is required');
}
if (options.builtInTypeConverter != undefined) {
this.builtInTypeConverter = options.builtInTypeConverter;
}
this.jsonSchemaVersion = options.jsonSchemaVersion;
this.reset();
}
// Getters/Setters
/**
* Returns the namespaces object. It will have been initialized with at least the globalAttributes
* specialized namespace, but it will include any other namespaces that have been added.
*
* @returns {Object} Returns the namespaces object.
*/
get namespaces() {
return this[namespaces_NAME];
}
set namespaces(newNamespaces) {
this[namespaces_NAME] = newNamespaces;
}
get XML_SCHEMA_NAMESPACE() {
throw new Error();
}
set XML_SCHEMA_NAMESPACE(newXmlSchemaNamespace) {
throw new Error();
}
get builtInTypeConverter() {
return this[builtInTypeConverter_NAME];
}
set builtInTypeConverter(newBuiltInTypeConverter) {
this[builtInTypeConverter_NAME] = newBuiltInTypeConverter;
}
get jsonSchemas() {
return this[jsonSchema_NAME];
}
set jsonSchemas(newJsonSchema) {
this[jsonSchema_NAME] = newJsonSchema;
}
get xmlSchemas() {
return this[xmlSchemas_NAME];
}
set xmlSchemas(newXmlSchemas) {
this[xmlSchemas_NAME] = newXmlSchemas;
}
get forwardReferences() {
return this[forwardReferences_NAME];
}
set forwardReferences(newForwardReferences) {
this[forwardReferences_NAME] = newForwardReferences;
}
get jsonSchemaVersion() {
return this[jsonSchemaVersion_NAME];
}
set jsonSchemaVersion(newJsonSchemaVersion) {
this[jsonSchemaVersion_NAME] = newJsonSchemaVersion;
}
newJsonSchema(newJsonSchemaOptions) {
var jsonSchema;
debug(
`Allocating new JsonSchmeaFileXXX using options [${newJsonSchemaOptions}] JsonSchemaVersion=${this.jsonSchemaVersion}`
);
switch (this.jsonSchemaVersion) {
case CONSTANTS.DRAFT_04:
jsonSchema = new JsonSchemaFileDraft04(newJsonSchemaOptions);
break;
case CONSTANTS.DRAFT_06:
jsonSchema = new JsonSchemaFileDraft06(newJsonSchemaOptions);
break;
case CONSTANTS.DRAFT_07:
jsonSchema = new JsonSchemaFileDraft07(newJsonSchemaOptions);
break;
default:
throw new Error(
`Unknown jsonSchemaVersion supplied [${this.jsonSchemaVersion}]`
);
}
return jsonSchema;
}
addNewJsonSchema(newJsonSchemaOptions) {
this.jsonSchemas[newJsonSchemaOptions.uri.toString()] =
this.newJsonSchema(newJsonSchemaOptions);
}
reset() {
this.jsonSchemas = {};
this.xmlSchemas = {};
this.forwardReferences = [];
}
/**
* Adds a namespace to the to the collection. The namespace is initially empty.
*
* @param {String} _namespace The name of the XML Namespace.
* @see {@link ConverterDraft04#initializeNamespaces|ConverterDraft04.initializeNamespaces()}
*
* @returns {void}
*/
addNamespace(_namespace) {
//var namespace = utils.getSafeNamespace(_namespace);
const namespace = _namespace;
if (!this.namespaces.hasOwnProperty(namespace)) {
this.namespaces[namespace] = { types: {} };
}
}
/**
* Returns the namespace object for a given namespace.
*
* @param {String} namespace The name of the namespace. For example: this could be
* 'targetNamespace' of the *<schema>* tag in an XML Schema file.
* @returns {Object} The namespace if present or enstantiats a new namesapce otherwise.
*/
getNamespace(namespace) {
return this.namespaces[namespace];
}
isWellKnownXmlNamespace(namespace) {
return namespace === CONSTANTS.XML_SCHEMA_NAMESPACE;
}
/**
*
* @param {String} fullTypeName The name of the type to be returned. One of the seven core JSON Schema types.
* @param {JsonSchemaFile} parent The parent of this type.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {JsonSchemaFile} The requested custom type.
*/
getBuiltInType(fullTypeName, parent, xsd) {
const qname = new Qname(fullTypeName);
const typeName = qname.getLocal();
if (
this.namespaces[CONSTANTS.XML_SCHEMA_NAMESPACE].types[typeName] ===
undefined
) {
const newType = this.newJsonSchema();
// The 'node' parameter to the builtInTypeConverter's xml handler methods is not currently
// used so it is safe to pass in null for now. This is likely a future bug!
debug(`Returning JSON Schema type [${typeName}]`);
this.builtInTypeConverter[typeName](null, newType, xsd);
this.namespaces[CONSTANTS.XML_SCHEMA_NAMESPACE].types[typeName] = newType;
}
const builtInType =
this.namespaces[CONSTANTS.XML_SCHEMA_NAMESPACE].types[typeName].clone();
builtInType.parent = parent;
return builtInType;
}
getNamespaceName(qname, xsd) {
let namespaceName = qname.getPrefix();
if (
namespaceName == '' &&
xsd.resolveNamespace(namespaceName) == undefined
) {
namespaceName = XsdAttributes.TARGET_NAMESPACE;
}
return namespaceName;
}
getNamespaceValue(qname, xsd) {
let namespaceName = qname.getPrefix();
if (
namespaceName == '' &&
xsd.resolveNamespace(namespaceName) == undefined
) {
namespaceName = XsdAttributes.TARGET_NAMESPACE;
}
return xsd.resolveNamespace(namespaceName);
}
isBuiltInType(fullTypeName, xsd) {
const qname = new Qname(fullTypeName);
const namespace = this.getNamespaceValue(qname, xsd);
return (
this.isWellKnownXmlNamespace(namespace) &&
this.builtInTypeConverter[qname.getLocal()] != undefined
);
}
createForwardReference(namespace, typeName, parent, baseJsonSchema, xsd) {
debug(
'Creating FORWARD REFERENCE to [' +
typeName +
'] in namespace [' +
namespace +
'] from [' +
xsd.uri.toString() +
']'
);
// Create the ForwardReference type, which will be resolved later after the type has been processed.
const forwardRef = new ForwardReference(
this,
namespace,
typeName,
parent,
baseJsonSchema,
xsd
);
this.forwardReferences.push(forwardRef);
return forwardRef.ref;
}
/**
* This method returns a reference to the requested type, which can be either a custom type or an
* XML built-in type. If the type exists in the namesapce of xsd then a reference to the type is
* retuned. If the type does not exist a forwardReference to the type is created and then returned.
*
* @param {String} fullTypeName The name of the type to be returned. The format of this
* parameter is 'prefix:localName' as defined {@link http://www.w3.org/TR/xml-names/#NT-QName |here}.
* @param {JsonSchemaFile} parent The parent of this type.
* @param {JsonSchemaFile} baseJsonSchema The JsonShemaFile being created as a result of converting an XML
* Schema file to JSON Schema.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {JsonSchemaFile} The requested custom type.
*/
getTypeReference(fullTypeName, parent, baseJsonSchema, xsd, createType) {
if (fullTypeName === undefined) {
throw new Error("'fullTypeName' parameter required");
}
if (parent === undefined) {
throw new Error("'parent' parameter required");
}
if (baseJsonSchema === undefined) {
throw new Error("'baseJsonSchema' parameter required");
}
if (xsd === undefined) {
throw new Error("'xsd' parameter required");
}
if (createType != undefined) {
throw new Error("'createType' parameter not allowed");
}
const namespaceQname = new Qname(fullTypeName);
const namespace = this.getNamespaceValue(namespaceQname, xsd);
if (namespace === undefined) {
throw new Error(
'A namespace has not been defined for [' + fullTypeName + ']'
);
}
const typeName = namespaceQname.getLocal();
if (this.isWellKnownXmlNamespace(namespace)) {
return this.getBuiltInType(typeName, parent, xsd);
}
if (this.namespaces[namespace].types[typeName] === undefined) {
return this.createForwardReference(
namespace,
fullTypeName,
parent,
baseJsonSchema,
xsd
);
} else {
debug(
'Returning reference to existing type [' +
fullTypeName +
'] in namespace [' +
namespace +
']'
);
const baseJsonSchemaForNamespace =
this.jsonSchemas[xsd.imports[namespace]] == undefined
? baseJsonSchema
: this.jsonSchemas[xsd.imports[namespace]];
const type = this.namespaces[namespace].types[typeName];
return type.get$RefToSchema(parent);
}
}
createType(namespace, typeName, parent, baseJsonSchema, xsd) {
debug(
'Creating TYPE [' +
typeName +
'] in namespace [' +
namespace +
'] from [' +
xsd.uri.toString() +
']'
);
// Create the type, which will be filled out later as the XSD is processed, and add it to the namespace.
const baseJsonSchemaForNamespace =
this.jsonSchemas[xsd.imports[namespace]] == undefined
? baseJsonSchema
: this.jsonSchemas[xsd.imports[namespace]];
const newType = this.newJsonSchema({
ref: new URI(
baseJsonSchemaForNamespace.id +
'#' +
baseJsonSchemaForNamespace.getSubschemaJsonPointer() +
'/' +
typeName
),
});
this.namespaces[namespace].types[typeName] = newType;
// const type = this.namespaces[namespace].types[typeName].clone();
const type = this.namespaces[namespace].types[typeName];
type.parent = parent;
// Add the type type to the anyOf in baseJsonSchema so it can be used directly for validation.
const baseId = new URI(baseJsonSchema.id);
const typeId = new URI(newType.ref);
if (baseId.filename() == typeId.filename()) {
baseJsonSchema.addRequiredAnyOfPropertyByReference(
typeName,
type.get$RefToSchema(baseJsonSchema)
);
}
return type;
}
/**
* This method returns the requested type, which can be either a custom type or an
* XML built-in type. If the type exists in the namesapce of xsd then the type is
* retuned. If the type does not exist it is created and then returned.
*
* @param {String} fullTypeName The name of the type to be returned. The format of this
* parameter is 'prefix:localName' as defined {@link http://www.w3.org/TR/xml-names/#NT-QName |here}.
* @param {JsonSchemaFile} parent The parent of this type.
* @param {JsonSchemaFile} baseJsonSchema The JsonShemaFile being created as a result of converting an XML
* Schema file to JSON Schema.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {JsonSchemaFile} The requested custom type.
*/
getType(fullTypeName, parent, baseJsonSchema, xsd, createType) {
if (fullTypeName === undefined) {
throw new Error("'fullTypeName' parameter required");
}
if (parent === undefined) {
throw new Error("'parent' parameter required");
}
if (baseJsonSchema === undefined) {
throw new Error("'baseJsonSchema' parameter required");
}
if (xsd === undefined) {
throw new Error("'xsd' parameter required");
}
if (createType != undefined) {
throw new Error("'createType' parameter not allowed");
}
const namespaceQname = new Qname(fullTypeName);
const namespace = this.getNamespaceValue(namespaceQname, xsd);
if (namespace == undefined) {
throw new Error(
'A namespace has not been defined for [' + fullTypeName + ']'
);
}
const typeName = namespaceQname.getLocal();
if (this.isWellKnownXmlNamespace(namespace)) {
return this.getBuiltInType(typeName, parent, xsd);
}
if (this.namespaces[namespace].types[typeName] === undefined) {
return this.createType(namespace, typeName, parent, baseJsonSchema, xsd);
} else {
debug(
'Returning existing type [' +
typeName +
'] in namespace [' +
namespace +
']'
);
let type = this.namespaces[namespace].types[typeName]; //.clone();
if (type.isForwardRef()) {
// create the new type
const newType = this.createType(
namespace,
typeName,
parent,
baseJsonSchema,
xsd
);
debug(
`Replacing forward reference [${type.ref}] with new type [${newType.ref}]`
);
// resolve any references that were created.
type.resolveRef(newType);
// remove the forward reference because it does not need to be resolved later.
const index = this.forwardReferences.indexOf(type.forwardReference);
this.forwardReferences.splice(index, 1);
// replace the forward reference with the actual type in the namespace
this.namespaces[namespace].types[typeName] = newType;
type = this.namespaces[namespace].types[typeName];
}
return type;
}
}
compilePointer(pointer) {
if (typeof pointer === 'string') {
pointer = pointer.split('/');
if (Array.isArray(pointer)) {
return pointer;
}
}
throw new Error(`Invalid JSON pointer [${pointer}}]`);
}
getReferencedTypeName(type) {
if (!type.isRef()) {
return new Error(`ref expected but found ${type.toString()}`);
}
var pointer = this.compilePointer(type.$ref);
return pointer[pointer.length - 1];
}
/**
* This method returns the requested type, which can be either a custom type or an
* XML built-in type. If the type exists in the namesapce of the xsd the type is
* retuned. If the type does not exist it is created and then returned.
*
* @param {String} fullTypeName The name of the type to be returned. The format of this
* parameter is 'prefix:localName' as defined {@link http://www.w3.org/TR/xml-names/#NT-QName |here}.
* @param {JsonSchemaFile} parent The parent of this type.
* @param {JsonSchemaFile} baseJsonSchema The JsonShemaFile being created as a result of converting an XML
* Schema file to JSON Schema.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {JsonSchemaFile} The requested custom type.
*/
getTypeReferenceFromRefChain(fullTypeName, parent, baseJsonSchema, xsd) {
if (fullTypeName === undefined) {
throw new Error("'fullTypeName' parameter required");
}
if (parent === undefined) {
throw new Error("'parent' parameter required");
}
if (baseJsonSchema === undefined) {
throw new Error("'baseJsonSchema' parameter required");
}
if (xsd === undefined) {
throw new Error("'xsd' parameter required");
}
const namespaceQname = new Qname(fullTypeName);
const namespace = this.getNamespaceValue(namespaceQname, xsd);
if (namespace == undefined) {
throw new Error(
'A namespace has not been defined for [' + fullTypeName + ']'
);
}
const typeName = namespaceQname.getLocal();
if (this.isWellKnownXmlNamespace(namespace)) {
return this.getBuiltInType(typeName, parent, xsd);
}
if (this.namespaces[namespace].types[typeName] === undefined) {
return this.createForwardReference(
namespace,
fullTypeName,
parent,
baseJsonSchema,
xsd
);
} else {
debug(
'Returning reference to existing type [' +
fullTypeName +
'] in namespace [' +
namespace +
']'
);
const baseJsonSchemaForNamespace =
this.jsonSchemas[xsd.imports[namespace]] == undefined
? baseJsonSchema
: this.jsonSchemas[xsd.imports[namespace]];
const type = this.namespaces[namespace].types[typeName];
// Return a reference to a type. Don't return a reference to a reference.
if (type.isRef()) {
return this.getTypeReferenceFromRefChain(
this.getReferencedTypeName(type),
parent,
baseJsonSchema,
xsd
);
} else {
return type.get$RefToSchema(parent);
}
}
}
dumpForwardReferences() {
debug('Begin Forward References (' + this.forwardReferences.length + ')');
this.forwardReferences.forEach(function (fRef, index, array) {
if (fRef.ref.ref == undefined) {
debug(index + ') $ref:' + fRef.ref.$ref.toString());
} else {
debug(index + ') ref:' + fRef.ref.ref.toString());
}
}, this);
}
resolveForwardReferenceOld(fRef) {
const type = this.getTypeReferenceFromRefChain(
fRef.fullTypeName,
fRef.parent,
fRef.baseJsonSchema,
fRef.xsd
);
//const displayRef = type.ref == undefined ? type.$ref : type.ref;
const fromType = fRef.ref.$ref;
const toType = type.ref == undefined ? type.$ref : type.ref;
debug(
`Resolving type [${fRef.ref.$ref}] to [${
type.ref == undefined ? type.$ref : type.ref
}]`
);
if (
type.resolved != undefined &&
type.resolved != true &&
fromType != toType
) {
this.resolveForwardReference(type.forwardReference);
}
const newRef = type.ref != undefined ? type.ref : type.$ref;
debug(
'Updating ' +
fRef.ref.$ref.toString() +
' to ' +
newRef.toString() +
', from ' +
fRef.baseJsonSchema.filename
);
fRef.ref.resolveRef(type);
}
resolveForwardReference(fRef) {
const type = this.getTypeReferenceFromRefChain(
fRef.fullTypeName,
fRef.parent,
fRef.baseJsonSchema,
fRef.xsd
);
const fromType = fRef.ref.$ref;
const toType = type.ref == undefined ? type.$ref : type.ref;
debug(
`Resolving type [${fRef.ref.$ref}] to [${
type.ref == undefined ? type.$ref : type.ref
}]`
);
if (
type.resolved != undefined &&
type.resolved != true &&
fromType != toType
) {
this.resolveForwardReference(type.forwardReference);
}
debug(
`'Updating [${fromType}] to [${toType}] from ${fRef.baseJsonSchema.filename}`
);
fRef.ref.resolveRef(type);
}
resolveForwardReferences() {
this.forwardReferences.forEach(function (fRef, index, array) {
this.resolveForwardReference(fRef);
}, this);
this.dumpForwardReferences();
}
cloneForwardReference(forwardRef) {
for (let i = 0; i < this.forwardReferences.length; i++) {
const fRef = this.forwardReferences[i];
if (forwardRef.equals(fRef.ref)) {
const cloneRef = this.getTypeReference(
fRef.fullTypeName,
fRef.parent,
fRef.baseJsonSchema,
fRef.xsd
);
return cloneRef;
}
}
return undefined;
}
/**
* This method returns true if the type exists in the namespace of the .
*
* @param {String} fullTypeName The name of the type to be returned. The format of this
* parameter is 'prefix:localName' as defined {@link http://www.w3.org/TR/xml-names/#NT-QName |here}.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {boolean} The requested custom type.
*/
typeExists(fullTypeName, xsd) {
if (fullTypeName === undefined) {
throw new Error("'fullTypeName' parameter required");
}
const namespaceQname = new Qname(fullTypeName);
const namespace = this.getNamespaceValue(namespaceQname, xsd);
if (namespace == undefined) {
throw new Error(
'A namespace has not been defined for [' + fullTypeName + ']'
);
}
const typeName = namespaceQname.getLocal();
return this.namespaces[namespace].types[typeName] != undefined;
}
/**
* This method inserts an entry into the given namespace by reference name rather than by type name.
* This way it can be looked up by type name or by reference.
*
* @param {String} fullTypeName - The name of the custom type to be used for references. The format of this
* parameter is 'prefix:localName' where localName is require and the prefix and separating colon are optional.
* @param {JsonSchemaFile} type - The type to be referenced by its name.
* @param {JsonSchemaFile} baseJsonSchema - The JsonShemaFile being created as a result of converting an XML
* Schema file to JSON Schema.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {void}
*/
addTypeReference(fullTypeName, type, baseJsonSchema, xsd) {
const namespaceQname = new Qname(fullTypeName);
const namespaceName = this.getNamespaceName(namespaceQname, xsd);
const namespace = xsd.resolveNamespace(namespaceName);
const refName = namespaceQname.getLocal();
if (this.namespaces[namespace].types[refName] === undefined) {
debug(
'Creating reference [' +
refName +
'] in namespace [' +
namespace +
'] from [' +
xsd.uri.toString() +
']'
);
this.namespaces[namespace].types[refName] = type;
baseJsonSchema.addRequiredAnyOfPropertyByReference(refName, type);
} else {
debug(
'Reference [' +
refName +
'] already exists in namespace [' +
namespace +
'] from [' +
xsd.uri.toString() +
']'
);
}
}
/**
* This method returns the requested global attribute. If the attribute exists in the global attribute
* namesapce the attribute is return. If the attribute does not exist it is created and then returned.
*
* @param {String} name The name of the global attribute to be returned.
* @param {JsonSchemaFile} baseJsonSchema The JsonSchemaFile being created as a result of converting an XML
* Schema file to JSON Schema.
*
* @returns {JsonSchemaFile} The request global attribute.
*/
getGlobalAttribute(name, baseJsonSchema) {
if (name === undefined) {
throw new Error("'name' parameter required");
}
if (baseJsonSchema === undefined) {
throw new Error("'baseJsonSchema' parameter required");
}
var globalAttributesNamespace = this.namespaces.globalAttributes;
if (globalAttributesNamespace.types[name] === undefined) {
globalAttributesNamespace.types[name] = this.newJsonSchema({
ref: new URI(
baseJsonSchema.id +
'#/' +
CONSTANTS.GLOBAL_ATTRIBUTES_SCHEMA_NAME +
'/' +
name
),
});
}
return globalAttributesNamespace.types[name].clone();
}
toString() {
//return JSON.stringify(this.namespaces, null, '\n');
}
}
module.exports = NamespaceManager;
},{"./constants":91,"./forwardReference":96,"./jsonschema/jsonSchemaFileDraft04":98,"./jsonschema/jsonSchemaFileDraft06":99,"./jsonschema/jsonSchemaFileDraft07":100,"./qname":111,"./xmlschema/xsdAttributes":120,"debug":3,"urijs":11}],108:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:ParsingState');
const XsdElements = require('./xmlschema/xsdElements');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const XsdNodeTypes = require('./xmlschema/xsdNodeTypes');
const states_NAME = Symbol();
const node_NAME = Symbol();
const workingJsonSchema_NAME = Symbol();
const attribute_NAME = Symbol();
/**
* This class is used to track the current depth of parsing an XML Schema file. The current state is defined as the
* name of the parent of current element in the XML Schema. For example, when processing an *<include>* element the current
* state is 'schema' because the parent of *<include>* is *<schema>*. The top of the XML Schema file is the *<schema>*
* element. When processing the *<schema>* element there is no current state because it has not been established.
*
* The current state of traversing the XML Schema tree is used to help facilitate conversion to JSON Schema. For example, it is
* beneficial to know what the parent element (or state) is when converting an *<attribute>* elememnt because annonymous attributes
* need to be handled differenlty than named attributes.
*
* It is an error to get the current state before it has been established by fully processing the <schema> element.
*
* Example state
* var state = {
* name : '',
* workingJsonSchema : {},
* attribute: 'value'
* }
*
* @module ParsingState
* @see {@link ConverterDraft04#attribute|ConverterDraft04.attribute()}
*/
class State {
constructor(values) {
if (values == undefined) {
throw new Error('values is required for a new State');
}
if (values.node == undefined) {
throw new Error('node is required for a new State');
}
this.node = values.node;
this.workingJsonSchema = values.workingJsonSchema;
this.attribute = values.attribute;
}
get node() {
return this[node_NAME];
}
set node(newNode) {
this[node_NAME] = newNode;
}
get workingJsonSchema() {
return this[workingJsonSchema_NAME];
}
set workingJsonSchema(newWorkingJsonSchema) {
this[workingJsonSchema_NAME] = newWorkingJsonSchema;
}
get attribute() {
return this[attribute_NAME];
}
set attribute(newAttribute) {
this[attribute_NAME] = newAttribute;
}
get name() {
return XsdFile.getNodeName(this.node);
}
get typeName() {
return XsdFile.getNameAttrValue(this.node);
}
}
class ParsingState {
constructor() {
// A stack of states
this.states = [];
}
// getters/setters
get states() {
return this[states_NAME]
}
set states(newStates) {
this[states_NAME] = newStates;
}
/**
* Pushes a new state onto the stack.
* @param {String} state - The name of the current elment in the XML Schema file. This method is called before processing the current element.
*
* @see {@link DepthFirstTraversal#walk|DepthFirstTraversal.walk()}
*/
enterState(state) {
this.states.push(state);
}
/**
* Pops the most recent state off the stack.
*
* @returns {String} - The name of the elment in the XML Schema file that just finished conversion.
* @see {@link DepthFirstTraversal#walk|DepthFirstTraversal.walk()}
*/
exitState() {
return this.states.pop();
}
/*
* Use pushSchema() to store a schema you would like to restore after processing a
* given element. This schema will be restored as the 'workingJsonSchema' upon exiting
* a state. See baseConversionVisitor.js.
*/
pushSchema(schema) {
this.states[this.states.length-1].workingJsonSchema = schema;
}
/**
* Returns the state most recently entered.
*
* @returns {String} - The name of the elment in the XML Schema file that is currently being converted.
* @see {@link DepthFirstTraversal#walk|DepthFirstTraversal.walk()}
*/
getCurrentState() {
if (this.states.length > 1) {
return this.states[this.states.length-2];
} else if (this.states.length === 1) {
throw new Error('Not \'in\' a state yet. We are \'on\' state=\'' + this.states[0].name + '\'!');
} else {
throw new Error('There are no states!');
}
}
/**
* @returns {Boolean} - True if the current state is 'attribute'.
*/
inAttribute() {
return this.getCurrentState().name === XsdElements.ATTRIBUTE;
}
/**
* @returns {Boolean} - True if the current state is 'element'.
*/
inElement() {
return this.getCurrentState().name === XsdElements.ELEMENT;
}
/**
* @returns {Boolean} - True if the current state is 'documentation'.
*/
inDocumentation() {
return this.getCurrentState().name === XsdElements.DOCUMENTATION;
}
/**
* @returns {Boolean} - True if the current state is 'appinfo'.
*/
inAppInfo() {
return this.getCurrentState().name === XsdElements.APPINFO;
}
/**
* @returns {Boolean} - True if the current state is 'choice'.
*/
inChoice() {
return this.getCurrentState().name === XsdElements.CHOICE;
}
/**
* @returns {Boolean} - True if the parent of the current state is 'schema'.
*/
isTopLevelEntity() {
if (this.states.length == 2) {
return true;
} else {
return false;
}
}
/**
* Dumps the stack of states to the console for error reporting or debugging purposes.
*/
dumpStates(filename) {
if (debug.enabled === true) {
debug('Current parsing state within [' + filename + ']:');
const maxLen = 0
for (let i = 0; i < this.states.length; i++) {
var schema = this.states[i].workingJsonSchema == undefined ? '': ' ' + this.states[i].workingJsonSchema
schema = schema.length > maxLen ? schema.substring(0, maxLen) + '\n...TRUNCATED to ' + maxLen + ' characters' : schema
debug(i + ') ' + XsdFile.nodeQuickDumpStr(this.states[i].node) + ' ' + schema);
}
debug('________________________________________________________________________________________');
}
}
}
module.exports.ParsingState = ParsingState;
module.exports.State = State;
},{"./xmlschema/xsdElements":121,"./xmlschema/xsdFileXmlDom":122,"./xmlschema/xsdNodeTypes":123,"debug":3}],109:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:Processor');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const XsdNodeTypes = require('./xmlschema/xsdNodeTypes');
const ParsingState = require('./parsingState').ParsingState;
const parsingState_NAME = Symbol();
const workingJsonSchema_NAME = Symbol();
const includeTextAndCommentNodes_NAME = Symbol();
/**
* Class representing an XML processor containing XML Handler methods for converting XML Schema into JSON
* Schema. XML handler methods convert XML elements into the equiviant JSON Schema representation.
* An XML Handler method has a common footprint shown by the process()
* {@link Processor#process|Processor.process()} method and a name that corresponds to one of the XML Schema element names
* found in {@link module:XsdElements}. For example, the choice handler method:\
* <pre><code>choice(node, jsonSchema, xsd)</code></pre>
*
* This base class provides
*/
class Processor {
/**
* Constructs an instance of Processor.
* @constructor
*/
constructor(options) {
this.parsingState = new ParsingState();
if (options != undefined) {
this.includeTextAndCommentNodes = options.includeTextAndCommentNodes != undefined ? options.includeTextAndCommentNodes : false;
} else {
this.includeTextAndCommentNodes = false;
}
}
// getters/setters
get parsingState() {
return this[parsingState_NAME];
}
set parsingState(newParsingState) {
this[parsingState_NAME] = newParsingState;
}
get workingJsonSchema() {
return this[workingJsonSchema_NAME];
}
set workingJsonSchema(newWorkingSchema) {
this[workingJsonSchema_NAME] = newWorkingSchema;
}
get includeTextAndCommentNodes() {
return this[includeTextAndCommentNodes_NAME];
}
set includeTextAndCommentNodes(newIncludeTextAndCommentNodes) {
this[includeTextAndCommentNodes_NAME] = newIncludeTextAndCommentNodes;
}
/**
* This method is called for each node in the XML Schema file being processed. It provides detailed logging if enabled. Subclasses
* should override this method and call it only for logging purposes.
*
* @param {Node} node - the current element in xsd being processed.
* @param {JsonSchemaFile} jsonSchema - the JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being processed.
* @param {XsdFile} xsd - the XML schema file currently being processed.
*
* @returns {Boolean} - handler methods can return false to cancel traversal of {@link XsdFile|xsd}.
*
* @see {@link ConverterDraft04#process|ConverterDraft04.process()}
*/
process(node, jsonSchema, xsd) {
// parsingState.dumpStates() will check for debug.enabled so it's okay to call unchecked. This allows ParsingState logging to be enabled separately from Processor.
if ((node.nodeType != XsdNodeTypes.TEXT_NODE && node.nodeType != XsdNodeTypes.COMMENT_NODE) || this.includeTextAndCommentNodes === true) {
this.parsingState.dumpStates(xsd.uri);
XsdFile.dumpNode(node);
if(debug.enabled === true) {
debug('***********************************************************************************\n' +
'XSD_Node_TO_APPLY= ' + node + '\nJSON_SCHEMA_WITH_XSD_NODE_APPLIED=\n' + jsonSchema);
}
}
return true;
}
/**
* This method is called after processing is complete to perform processing that couldn't be handled by
* the XML Handler methods. Subclasses should override this method as needed.
*
* @see {@link ConverterDraft04#processSpecialCases|ConverterDraft04.processSpecialCases()}
*/
processSpecialCases() {
debug('Processing special cases')
//throw new Error('Please implement this method. Processor.processSpecialCases()');
}
}
module.exports = Processor;
},{"./parsingState":108,"./xmlschema/xsdFileXmlDom":122,"./xmlschema/xsdNodeTypes":123,"debug":3}],110:[function(require,module,exports){
'use strict';
/**
* PropertyDefinable is a utility base class providing methods to create properties that are enumerable and configurable.
*/
class PropertyDefinable {
/**
* @param {Object} [options] - Used to configure a set of properties at once.
*
* * options.propertyNames - An array of property names to be created.
* * options.enumerable - A boolean used to determine if created properties are enumerable. Only used in conjunction with options.propertyNames.
* * options.properties - Key value pairs where the key is the propertyName to be created and the value is the descriptor as defined by
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty | Object.defineProperty()}
*/
constructor(options) {
if (options == undefined) {
return;
}
if (options.propertyNames != undefined) {
this.definePropertiesFromArray(options.propertyNames, options.enumerable);
}
if (options.properties != undefined) {
this.definePropertiesFromObject(options.properties)
}
}
/**
* Creates a set of accessor properties with the provided names and enumerable property.
*
* @param {Array} propertyNames - An array of strings represending the properties to be created.
* @param {Boolean} [enumerable] - True if all the properties created from the provided propertyNames should be enumerable. False otherwise.
*
* @returns {void}
*/
definePropertiesFromArray(propertyNames, enumerable) {
propertyNames.forEach(function (propertyName) {
this.defineAccessorProperty(propertyName, Symbol(propertyName), {
enumerable: enumerable == undefined ? true : enumerable
});
}, this);
}
/**
*
* @param {Object} properties - Key value pairs where the key is the propertyName to be created and the value is the descriptor as defined by
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty | Object.defineProperty()}
*
* @returns {void}
*/
definePropertiesFromObject(properties) {
Object.keys(properties).forEach(function (propertyName) {
Reflect.defineProperty(this, propertyName, properties[propertyName]);
}, this);
}
/**
* Adds a basic property with the given name and symbol. The property will have a getter & setter and be both enumerable and configurable
* unless overridden by the descriptor parameter.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
* @param {Object} [descriptor] - Can be used to customize the property.as defined by
* {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty | Object.defineProperty()}
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineAccessorProperty(propertyName, symbol, descriptor) {
var attributes = {
enumerable: true,
configurable: true,
get: function () {
return this[symbol];
},
set: function (newVal) {
this[symbol] = newVal;
}
};
Object.assign(attributes, descriptor);
return Reflect.defineProperty(this, propertyName, attributes);
}
/**
* Adds a basic property with the given name and symbol. Properties will have a getters & setters and be enumerable.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
get: function () {
return this[symbol];
},
set: function (newVal) {
this[symbol] = newVal;
}
});
}
/**
* Adds a numeric property with the given name The enumerable property will have a standard getter and
* a setter that validates new values to ensure only numeric values are allowed.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineNumericProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
set: function(newProperty) {
if (typeof newProperty !== 'number' && newProperty != undefined) {
throw new Error(`${newProperty} must be a number`);
}
this[symbol] = newProperty;
}
});
}
/**
* Adds a String property with the given name. The enumerable property will have a standard getter and
* a setter that validates new values to ensure only String values are allowed.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineStringProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
set: function(newProperty) {
if (typeof newProperty !== 'string' && newProperty != undefined) {
throw new Error(`${newProperty} must be a string`);
}
this[symbol] = newProperty;
}
});
}
/**
* Adds a boolean property with the given name. The enumerable property will have a standard getter and
* a setter that validates new values to ensure only boolean values are allowed.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineBooleanProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
set: function(newProperty) {
if (typeof newProperty !== 'boolean' && newProperty != undefined) {
throw new Error(`${newProperty} must be a boolean`);
}
this[symbol] = newProperty;
}
});
}
/**
* Adds an Object property with the given name. The enumerable property will have a standard getter and
* a setter that validates new values to ensure only Object values are allowed.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineObjectProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
set: function(newProperty) {
if (newProperty != undefined) {
if (typeof newProperty !== 'object' || Array.isArray(newProperty)) {
throw new Error(`${newProperty} must be an object`);
}
}
this[symbol] = newProperty;
}
});
}
/**
* Adds an Object property with the given name. The enumerable property will have a standard getter and
* a setter that validates new values to ensure only Object values are allowed.
*
* @param {String} propertyName - Name of the property
* @param {Symbol} symbol - {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol | Symbol} to use to retrieve this this property
*
* @returns {Boolean} - Indicating whether or not the property was successfully defined.
*/
defineArrayProperty(propertyName, symbol) {
if (symbol == undefined) {
symbol = Symbol();
}
return this.defineAccessorProperty(propertyName, symbol, {
set: function(newProperty) {
if (newProperty != undefined) {
if (typeof newProperty !== 'object' && !Array.isArray(newProperty)) {
throw new Error(`${newProperty} must be an array object`);
}
}
this[symbol] = newProperty;
}
});
}
}
module.exports = PropertyDefinable;
},{}],111:[function(require,module,exports){
/**
* New node file
*/
'use strict';
var qualName_NAME = Symbol();
class Qname {
constructor(qname) {
var i = qname.indexOf(':');
this.qualName = i < 0 ? [ '', qname ] : qname.split(':');
}
get qualName() {
return this[qualName_NAME];
}
set qualName(newQualName) {
this[qualName_NAME] = newQualName;
}
getPrefix() {
return this.qualName[0];
}
getLocal() {
return this.qualName[1];
}
}
module.exports = Qname;
},{}],112:[function(require,module,exports){
'use strict';
/**
* Defines constants for identifying special cases in XML Schema that cannot be directly translated into JSON Schema.
*
* @module SpecialCases
*/
module.exports = {
ANY_OF_CHOICE : 'fixAnyOfChoice',
SIBLING_CHOICE : 'fixSiblingChoice',
OPTIONAL_CHOICE : 'fixOptionalChoice',
OPTIONAL_SEQUENCE : 'fixOptionalSequence'
}
},{}],113:[function(require,module,exports){
/**
* Utility methods.
*/
'use strict';
const url = require('url');
const validator = require('validator');
/**
* A collection of utility functions
*
* @module Utils
*/
module.exports = {
/**
* @param {String} str - a string containing a potential URL.
* @returns {String} - a resconstruction of the URL without the scheme, colon, or any parameters.
*/
compactURL: function (str) {
var retval = '';
if (str != undefined) {
var urlParser = url.parse(str);
var hostname = urlParser.hostname;
var pathStr = urlParser.pathname;
var namespaces = pathStr.split('/');
if (namespaces.length > 1) {
namespaces.shift();
}
if(hostname != undefined) {
namespaces.unshift(hostname);
}
for (let i = 0; i < namespaces.length; i++) {
retval += '/' + namespaces[i];
}
}
return retval;
},
/**
* @param {String} xmlNamespace - a string containing a potential URL.
* @returns {String} - if the paraemter does not contain a URL then the parameter is returned unchanged.
* If the parameter is determined to contain a URL then the return value is the return value of sending
* the parameter through {@link module:Utils.compactURL}.
*/
getSafeNamespace: function (xmlNamespace) {
var retval = xmlNamespace;
if (validator.isURL(xmlNamespace)) {
retval = this.compactURL(xmlNamespace);
}
return retval;
},
/**
* Provies basic object.toString() functionality for logging purposes.
*
* @param {Object} obj - an object.
* @returns {String} - a string of name/value pairs of any properties the object has.
*/
objectToString: function (obj) {
var str = '';
Object.keys(obj).forEach(function (key, index, array) {
str += key + '=\'' + obj[key] + '\' ';
});
return str.trim();
}
}
},{"url":134,"validator":13}],114:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:BaseConversionVisitor');
const Visitor = require('./visitor');
const XsdElements = require('./../xmlschema/xsdElements');
const State = require('./../parsingState').State;
/**
* Class representing a visitor. Vistors are utilized by {@link DepthFirstTraversal} to process each node within an XML
* Schema file. This base implmention simply calls the processor member's process() method to facilitate conversion
* from XMLSchema to JSON Schema. It also adds error handling.
*/
class BaseConversionVisitor extends Visitor {
/**
* Constructs an instance of BaseConversionVisiter.
* @constructor
* @param {Processor} processor - {@link ConverterDraft04} or a subclass of {@link Processor}
*/
constructor(processor) {
super(processor);
}
/**
* Utilizes {@link module:ParsingState|ParsingState} to push the current elment name (or state) to a stack. When convertion begins for a given element this method is called. When conversion ends for the same element the {@link BaseConversionVisitor#exitState|exitState()} method is called. The stack of element names (or states) represents current depth of the conversion process within {@link XsdFile|xsd}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @return {undefined}
*/
enterState(node, jsonSchema, xsd) {
var state = new State({
node: node
});
this.processor.parsingState.enterState(state);
}
/**
* Utilizes {@link module:ParsingState|ParsingState} to pop and element (or state) from a stack of element nodes. The stack
* of element names (or states) represents current depth of the conversion process within {@link XsdFile|xsd}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @return {undefined}
*/
exitState(node, jsonSchema, xsd) {
var state = this.processor.parsingState.exitState();
if (state.workingJsonSchema !== undefined) {
this.processor.workingJsonSchema = state.workingJsonSchema;
}
/**
* <simpleType> tags that take advantage of <restriction> tags are converted to JsonSchema utilizing allOf. It is
* possible a <simpleType> doesn't contain anything meaningful other than the restriction. In this case the conversion
* will end with an empty JsonSchema in the simpleType's allOf array. To correct this empty JsonSchema's are removed
* from a sympleType's allOf array. Example:
* <xs:simpleType name='SomeSimpleType'>
* <xs:annotation>
* <xs:documentation xml:lang='en'>Blah Blah Blah</xs:documentation>
* </xs:annotation>
* <xs:restriction base='SomeBaseType'/>
* </xs:simpleType>
*/
if (state.name === XsdElements.SIMPLE_TYPE && this.processor.workingJsonSchema !== undefined) {
this.processor.workingJsonSchema.removeEmptySchemas();
}
}
/**
* This method is called before conversion of {@link XsdFile|xsd} is started. Subclasss can override this method to implement class
* specific pre-processing behavior. The default implementation logs a message and returns true to allow conversion to start.
*
* @param {JsonSchemaFile} jsonSchema - The JSON Schema file that will represent converted XML Schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file about to be processed.
*
* @returns {Boolean} - True. Subclasses can return false to cancel traversal of {@link XsdFile|xsd}
*/
onBegin(jsonSchema, xsd) {
debug('\n\n****************************************************************************************************');
debug('Converting ' + xsd.filename);
debug('****************************************************************************************************\n');
return true;
}
/**
* This method is called after conversion of {@link XsdFile|xsd} has completed. Subclasss can override this method to implement
* class specific post-processing behavior. The default implementation calls {@link ConverterDraft04#processSpecialCases|ConverterDraft04.processSpecialCases()}.
*
* @param {JsonSchemaFile} jsonSchema - The resulting JSON Schema file from the conversion.
* @param {XsdFile} xsd - The XML Schema file {@link XsdFile|xsd} that was just converted.
*
* @returns {Boolean} - Returns true if the xml schema file needs to be reprocessed due to forward references or otherwise.
*/
onEnd(jsonSchema, xsd) {
this.processor.processSpecialCases();
return this.processor.anotherPassNeeded
}
}
module.exports = BaseConversionVisitor;
},{"./../parsingState":108,"./../xmlschema/xsdElements":121,"./visitor":116,"debug":3}],115:[function(require,module,exports){
'use strict';
var ConverterDraft07 = require('./../converterDraft07');
var BaseConvertionVisitor = require('./baseConversionVisitor');
/**
* Class representing minimial use of the {@link BaseConversionVisitor#visit|BaseConversionVisitor} class to convert XML Schema
* to JSON Schema. {@link BaseConversionVisitor|BaseConversionVisitor} is subclassed and no additional logic is added.
* The constructor allocates an instance of {@link ConverterDraft04} which is passed to super constructor.
*
* @see {@link XmlUsageVisitor}
* @see {@link XmlUsageVisitorSum}
*/
class DefaultConversionVisitor extends BaseConvertionVisitor {
/**
* Constructs an instance of DefaultConversionVisitor. Allocates a {@link ConverterDraft07} and passes it to the super constructor.
* @constructor
*/
constructor() {
super(new ConverterDraft07());
}
}
module.exports = DefaultConversionVisitor;
},{"./../converterDraft07":94,"./baseConversionVisitor":114}],116:[function(require,module,exports){
'use strict'
const debug = require('debug')('xsd2jsonschema:Visitor');
const Processor = require('./../processor');
const XsdFile = require('./../xmlschema/xsdFileXmlDom');
const processor_NAME = Symbol();
/**
* Class representing a visitor. Vistors are utilized by {@link DepthFirstTraversal} to process each node within an XML
* Schema file. This base implmention simply calls the processor member's {@link Processor#process|Processor.process()}
* method to facilitate processing of the current node of the {@link XsdFile} being traversed.
*
* @module Visitor
* @see {@link BaseConversionVisitor}
* @see {@link XmlUsageVisitor}
* @see {@link XmlUsageVisitorSum}
* @see {@link Processor}
*/
class Visitor {
/**
* Constructs an instance of Visitor.
*
* @constructor
* @param {Processor} processor - {@link Processor} or subclass of {@link Processor}.
*/
constructor(processor) {
if (processor != undefined) {
this.processor = processor;
} else {
this.processor = new Processor();
}
}
// Getters/Setters
get processor() {
return this[processor_NAME];
}
set processor(newProcessor) {
this[processor_NAME] = newProcessor;
}
/**
* This method is called for each node in the XML Schema file being processed. It involks {@link ConverterDraft04#process|ConverterDraft04.process()}
* to effect the conversion of the current element in {@link XsdFile|xsd}.
*
* @param {Node} node - The current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - The JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - The XML schema file currently being converted.
*
* @returns {Boolean} - Returns the value of the current subclass of {@link Processor}, which is {@link ConverterDraft04#process|ConverterDraft04.process()} by default.
* @throws Will log any uncaught exception including the current parsing state within the {@link XsdFile|xsd} being processed and rethrow to cancel traversal.
*/
visit(node, jsonSchema, xsd) {
try {
return this.processor.process(node, jsonSchema, xsd);
} catch (err) {
debug(err.stack);
this.processor.parsingState.dumpStates(xsd.filename);
XsdFile.dumpNode(node);
throw err;
}
}
}
module.exports = Visitor;
},{"./../processor":109,"./../xmlschema/xsdFileXmlDom":122,"debug":3}],117:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:XmlUsageVisitor');
const BaseConvertionVisitor = require('./baseConversionVisitor');
const XsdAttributes = require('./../xmlschema/xsdAttributes');
const XsdFile = require('./../xmlschema/xsdFileXmlDom');
const uris_NAME = Symbol();
/**
* Class representing a custom visitor. This visitor lists the XML Schema elments used by the provided
* {@link XsdFile|XML Schema} files and displays element counts by file.
*/
class XmlUsageVisitor extends BaseConvertionVisitor {
/**
* Constructs an instance of XmlUsageVisitor without a converter because all processing will be done here in the
* visitor. Notice {@link BaseConversionVisitor#visit|BaseConversionVisitor.visit()} is overridden.
*
* @constructor
*/
constructor() {
super();
this.uris = {};
}
// Getters/Setters
get uris() {
return this[uris_NAME];
}
set uris(newUris) {
this[uris_NAME] = newUris;
}
addSchema(uri) {
if (this.uris[uri] === undefined) {
this.uris[uri] = { tagCounts: {} }
}
}
addTag(uri, xmlTag) {
if (this.uris[uri].tagCounts[xmlTag] === undefined) {
this.uris[uri].tagCounts[xmlTag] = 1;
} else {
this.uris[uri].tagCounts[xmlTag] += 1;
}
}
/**
* Overrides {@link BaseConversionVisitor#visit|BaseConversionVisitor.visit()} to do the work of calculating node counts by file.
*
* @param {Node} node - the current element in xsd being converted.
* @param {JsonSchemaFile} jsonSchema - the JSON Schema representing the current XML Schema file {@link XsdFile|xsd} being converted.
* @param {XsdFile} xsd - the XML schema file currently being converted.
*
* @returns {Boolean} True
*/
visit(node, jsonSchema, xsd) {
var uri = xsd.uri;
this.addSchema(uri);
this.addTag(uri, XsdFile.getAttrValue(node, XsdAttributes.NAME));
return true;
}
/**
* Overrides {@link BaseConversionVisitor#onBegin|BaseConversionVisitor.onBegin()} to ensure each file is only processed once. The
* counts would be off is one common file is included by several files and all files were processed.
*
* @param {JsonSchemaFile} jsonSchema - The JSON Schema file that will represent converted XML Schema file {@link XsdFile|xsd}.
* @param {XsdFile} xsd - The XML schema file about to be processed.
*
* @returns {Boolean} True If xsd has not already been processed. False otherwise.
*/
onBegin(jsonSchema, xsd) {
if (this.uris[xsd.uri] === undefined) {
return true;
} else {
return false;
}
}
dump() {
Object.keys(this.uris).sort().forEach(function (uri, index, array) {
debug(uri);
debug('-----------------');
Object.keys(this.uris[uri].tagCounts).sort().forEach(function (xmlTag, index, array) {
debug(xmlTag + ' = ' + this.uris[uri].tagCounts[xmlTag]);
}, this)
debug();
}, this);
}
}
module.exports = XmlUsageVisitor;
},{"./../xmlschema/xsdAttributes":120,"./../xmlschema/xsdFileXmlDom":122,"./baseConversionVisitor":114,"debug":3}],118:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:XmlUsageVisitorSum');
const BaseConvertionVisitor = require('./baseConversionVisitor');
const XsdAttributes = require('./../xmlschema/xsdAttributes');
const XsdFile = require('./../xmlschema/xsdFileXmlDom');
const uris_NAME = Symbol();
const tagCounts_NAME = Symbol();
/**
* Class representing a custom visitor. This visitor counts the XML Schema elments used by the provided
* {@link XsdFile|XML Schema} files and displays aggregate counts of elements used accross all scheam files.
*/
class XmlUsageVisitorSum extends BaseConvertionVisitor {
/**
* Constructs an instance of XmlUsageVisitor without a converter because all processing will be done here in the
* visitor. Notice {@link BaseConversionVisitor#visit|BaseConversionVisitor.visit()} is overridden.
*
* @constructor
*/
constructor() {
super();
this.uris = {};
this.tagCounts = {};
}
get uris() {
return this[uris_NAME];
}
set uris(newUris) {
this[uris_NAME] = newUris;
}
get tagCounts() {
return this[tagCounts_NAME];
}
set tagCounts(newTagCounts) {
this[tagCounts_NAME] = newTagCounts;
}
addSchema(uri) {
if (this.uris[uri] === undefined) {
this.uris[uri] = { tagCounts: {} }
}
}
addTag(xmlTag) {
if (this.tagCounts[xmlTag] === undefined) {
this.tagCounts[xmlTag] = 1;
} else {
this.tagCounts[xmlTag] += 1;
}
}
visit(node, jsonSchema, xsd) {
var uri = xsd.uri;
this.addSchema(uri);
this.addTag(XsdFile.getAttrValue(node, XsdAttributes.NAME));
return true;
}
onBegin(jsonSchema, xsd) {
if (this.uris[xsd.uri] === undefined) {
return true;
} else {
return false;
}
}
dump() {
debug('----------------------------');
debug('Overall XML Schema Tag Usage');
debug('----------------------------');
debug(Object.keys(this.uris));
debug('----------------------------');
Object.keys(this.tagCounts).sort().forEach(function (xmlTag, index, array) {
debug(xmlTag + ' = ' + this.tagCounts[xmlTag]);
}, this)
debug();
}
}
module.exports = XmlUsageVisitorSum;
},{"./../xmlschema/xsdAttributes":120,"./../xmlschema/xsdFileXmlDom":122,"./baseConversionVisitor":114,"debug":3}],119:[function(require,module,exports){
'use strict';
/**
* Defines constants for well known XML Schema Attribute Values
*
* @module XsdAttributeValues
*/
module.exports = {
UNBOUNDED: 'unbounded',
ZERO: '0',
XMLNS: 'xmlns',
OPTIONAL: 'optional',
PROHIBITED: 'prohibited',
REQUIRED: 'required'
}
},{}],120:[function(require,module,exports){
'use strict';
/**
* Defines constants for XML Schema Attribute Keywords
*
* @module XsdAttributes
*/
module.exports = {
ABSTRACT: 'abstract',
APPLIES_TO_EMPTY: 'appliesToEmpty',
ATTRIBUTE_FORM_DEFAULT: 'attributeFormDefault',
BASE: 'base',
BLOCK: 'block',
BLOCK_DEFAULT: 'blockDefaut',
DEFAULT: 'default',
DEFAULT_ATTRIBUTES: 'defaultAttributes',
ELEMENT_FORM_DEFAULT: 'elementFormDefault',
FACET_AVAILABLE: 'facetAvailable',
FACET_UNAVAILABLE: 'facetUnavailable',
FINAL: 'final',
FINAL_DEFAULT: 'finalDefault',
FIXED: 'fixed',
FORM: 'form',
ID: 'id',
INHERITABLE: 'inheritable',
ITEM_TYPE: 'itemType',
LANG: 'lang',
MAX_OCCURS: 'maxOccurs',
MAX_VERSION: 'maxVersion',
MEMBER_TYPES: 'memberTypes',
MIN_OCCURS: 'minOccurs',
MIN_VERSION: 'minVersion',
MIXED: 'mixed',
MODE: 'mode',
NAME: 'name',
NAMESPACE: 'namespace',
NIL: 'nil',
NILLABLE: 'nillable',
NO_NAMESPACE_SCHEMA_LOCATION: 'noNamespaceSchemaLocation',
NOT_NAMESPACE: 'notNamespace',
NOT_QNAME: 'notQName',
PROCESS_CONTENTS: 'processContents',
PUBLIC: 'public',
REF: 'ref',
REFER: 'refer',
SCHEMA_LOCATION: 'schemaLocation',
SOURCE: 'isourced',
SUBSTITUTION_GROUP: 'substitutionGroup',
SYSTEM: 'system',
TARGET_NAMESPACE: 'targetNamespace',
TEST: 'test',
TYPE: 'type',
TYPE_AVAILABLE: 'typeAvailable',
TYPE_UNAVAILABLE: 'typeUnavailable',
USE: 'use',
VALUE: 'value',
VERSION: 'version',
XPATH: 'xpath',
XPATH_DEFAULT_NAMESPACE: 'xpathDefaultNamespace'
}
},{}],121:[function(require,module,exports){
'use strict';
/**
* Defines constants for XML Schema Element Keywords
*
* @module XsdElements
*/
module.exports = {
ALL: 'all',
ALTERNATIVE: 'alternative',
ANNOTATION: 'annotation',
ANY: 'any',
ANY_ATTRIBUTE: 'anyAttribute',
APPINFO: 'appinfo',
ASSERT: 'assert',
ASSERTION: 'assertion',
ATTRIBUTE: 'attribute',
ATTRIBUTE_GROUP: 'attributeGroup',
CHOICE: 'choice',
COMPLEX_CONTENT: 'complexContent',
COMPLEX_TYPE: 'complexType',
DEFAULT_OPEN_CONTENT: 'defaultOpenContent',
DOCUMENTATION: 'documentation',
ELEMENT: 'element',
ENUMERATION: 'enumeration',
EXPLICIT_TIMEZONE: 'explicitTimezone',
EXTENSION: 'extension',
FIELD: 'field',
FRACTION_DIGITS: 'fractionDigits',
GROUP: 'group',
IMPORT: 'import',
INCLUDE: 'include',
KEY: 'key',
KEYREF: 'keyref',
LENGTH: 'length',
LIST: 'list',
MAX_EXCLUSIVE: 'maxExclusive',
MAX_INCLUSIVE: 'maxInclusive',
MAX_LENGTH: 'maxLength',
MIN_EXCLUSIVE: 'minExlusive',
MIN_INCLUSIVE: 'minInclusive',
MIN_LENGTH: 'minLength',
NOTATION: 'notation',
OPEN_CONTENT: 'openContent',
OVERRIDE: 'override',
PATTERN: 'pattern',
REDEFINE: 'redefine',
RESTRICTION: 'restriction',
SCHEMA: 'schema',
SELECTOR: 'selector',
SEQUENCE: 'sequence',
SIMPLE_CONTENT: 'simpleContent',
SIMPLE_TYPE: 'simpleType',
TOTAL_DIGITS: 'totalDigits',
UNION: 'union',
UNIQUE: 'unique',
WHITESPACE: 'whitespace'
}
},{}],122:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:XsdFile');
const DOMParser = require('xmldom').DOMParser;
const xpathProcessor = require('xpath');
const URI = require('urijs');
const XsdAttributes = require('./xsdAttributes');
const XsdElements = require('./xsdElements');
const XsdAttributeValues = require('./xsdAttributeValues');
const XsdNodeTypes = require('./xsdNodeTypes');
const Constants = require('../constants');
const uri_NAME = Symbol();
const xmlDoc_NAME = Symbol();
const includeUris_NAME = Symbol();
const importUris_NAME = Symbol();
const namespaces_NAME = Symbol();
const imports_NAME = Symbol();
/**
* XML Schema file operations
* https://www.w3.org/2001/xml.xsd
* TBD (xmldom)
*/
class XsdFile {
constructor(options) {
if (options == undefined || typeof options !== 'object') {
throw new Error('Parameter "options" is required');
}
if (options.uri == undefined) {
throw new Error('"options.uri" is required');
}
if (options.xml == undefined) {
throw new Error('"options.xml" is required');
}
// Instantiate the URL just in case a string was passed in.
this.uri = new URI(options.uri);
this.xmlDoc = new DOMParser().parseFromString(options.xml, 'text/xml');
this.namespaces = {};
this.imports = {};
this.initilizeNamespaces();
this.initializeIncludes();
this.initializeImports();
}
// Getters/Setters
get uri() {
return this[uri_NAME];
}
set uri(newUri) {
this[uri_NAME] = newUri;
}
get xmlDoc() {
return this[xmlDoc_NAME];
}
set xmlDoc(newDoc) {
this[xmlDoc_NAME] = newDoc;
}
get includeUris() {
return this[includeUris_NAME];
}
set includeUris(newIncludeUris) {
this[includeUris_NAME] = newIncludeUris;
}
get importUris() {
return this[importUris_NAME];
}
set importUris(newIncludeUris) {
this[importUris_NAME] = newIncludeUris;
}
get namespaces() {
return this[namespaces_NAME];
}
set namespaces(newNamespaces) {
this[namespaces_NAME] = newNamespaces;
}
get imports() {
return this[imports_NAME];
}
set imports(newImports) {
this[imports_NAME] = newImports;
}
// read-only properties
get filename() {
return this.uri.filename();
}
set filename(unused) {
throw new Error('Unsupported operation');
}
get directory() {
return this.uri.directory();
}
set directory(unused) {
throw new Error('Unsupported operation');
}
get schemaElement() {
return this.xmlDoc.documentElement;
}
set schemaElement(unused) {
throw new Error('Unsupported operation');
}
get targetNamespace() {
return this.xmlDoc.documentElement.getAttribute(
XsdAttributes.TARGET_NAMESPACE
);
}
set targetNamespace(unused) {
throw new Error('Unsupported operation');
}
addNamespace(key, value) {
this.namespaces[key] = value;
}
// 1 Map the XML Schmea Namespase to a prefix such as xsd or xs, and make the target namespace the default namespace.
// 2 Map a prefix to the target namespace, and make the XML Schema Namespase the default namespace.
// 3 Map prefixes to all the namespaces.
initilizeNamespaces() {
const attrs = XsdFile.getAttributes(this.schemaElement);
Object.keys(attrs).forEach(function (key, index, array) {
const attr = attrs[key];
if (attr.nodeType === XsdNodeTypes.ATTRIBUTE_NODE) {
const attrValue = attr.value;
switch (attr.localName) {
case XsdAttributes.TARGET_NAMESPACE:
this.namespaces[XsdAttributes.TARGET_NAMESPACE] = attrValue;
break;
case XsdAttributeValues.XMLNS:
this.namespaces[''] = attrValue;
break;
default:
if (attr.prefix === 'xmlns') {
const namespace = attr.localName;
this.namespaces[namespace] = attrValue;
}
break;
}
}
}, this);
// Ensure values are set for targetNamespace, the default namespace, and the XML Schema Namespace
if (
this.namespaces[XsdAttributes.TARGET_NAMESPACE] == undefined &&
this.namespaces[''] == undefined
) {
this.namespaces[XsdAttributes.TARGET_NAMESPACE] = Constants.NO_NAMESPACE;
this.namespaces[''] = Constants.NO_NAMESPACE;
} else if (
this.namespaces[XsdAttributes.TARGET_NAMESPACE] == undefined &&
this.namespaces[''] != undefined
) {
this.namespaces[XsdAttributes.TARGET_NAMESPACE] = this.namespaces[''];
} else if (
this.namespaces[XsdAttributes.TARGET_NAMESPACE] != undefined &&
this.namespaces[''] == undefined
) {
this.namespaces[''] = this.namespaces[XsdAttributes.TARGET_NAMESPACE];
}
// If the XML Schema Namespace is missing setup a couple of defaults so we can try to convert the schema. (not a good sign)
if (this.isMissingXmlSchemaNamespace()) {
this.namespaces[Constants.XML_SCHEMA_DEFAULT_NAMESPACE_NAME_XS] =
Constants.XML_SCHEMA_NAMESPACE;
this.namespaces[Constants.XML_SCHEMA_DEFAULT_NAMESPACE_NAME_XSD] =
Constants.XML_SCHEMA_NAMESPACE;
}
}
isMissingXmlSchemaNamespace() {
const keys = Object.keys(this.namespaces);
for (const key of keys) {
if (this.namespaces[key] == Constants.XML_SCHEMA_NAMESPACE) {
return false;
}
}
return true;
}
resolveNamespace(namespaceName) {
return this.namespaces[namespaceName];
}
hasIncludes() {
return this.includeUris.length > 0;
}
hasImports() {
return this.importUris.length > 0;
}
initializeIncludes() {
if (this.includeUris === undefined) {
var includeNodes = this.schemaElement.getElementsByTagName(
this.schemaElement.prefix + ':include'
);
this.includeUris = [];
for (let i = 0; i < includeNodes.length; i++) {
const includeNode = includeNodes.item(i);
this.includeUris.push(
includeNode.getAttribute(XsdAttributes.SCHEMA_LOCATION)
);
}
}
return this.includeUris;
}
initializeImports() {
if (this.importUris === undefined) {
var importNodes = this.schemaElement.getElementsByTagName(
this.schemaElement.prefix + ':import'
);
this.importUris = [];
for (let i = 0; i < importNodes.length; i++) {
const importNode = importNodes.item(i);
this.importUris.push(
importNode.getAttribute(XsdAttributes.SCHEMA_LOCATION)
);
}
}
return this.importUris;
}
select(xpath, ns, namespace) {
var nodes;
try {
const select = xpathProcessor.useNamespaces(this.namespaces);
nodes = select(xpath, this.xmlDoc);
} catch (error) {
debug(error);
throw error;
}
return nodes;
}
select1(xpath, ns, namespace) {
var node;
try {
const select = xpathProcessor.useNamespaces(this.namespaces);
node = select(xpath, this.xmlDoc, true);
} catch (error) {
debug(error);
throw error;
}
return node;
}
toString() {
const str = `baseFilename=${this.filename}
uri=${this.uri}
includeUris=${this.includeUris}
namespaces=${JSON.stringify(this.namespaces, null, '\t')}
xmlDoc=${this.xmlDoc}`;
return str;
}
/**
* xml interface
*
* 1) dumpAttrs
* 2) getAttrValue
* 3) hasAttr
* 4) getAttrValue
* 5) getValueAttr
* 6) dumpNode
* 7) getNodeName
* 8) isNamed
* 9) isReference
* 10) countChildren
* 11) buildAttributeMap
* 12) getChildNodes
* 13) getAttributes
*/
/* *********************************************************************************** */
static nodeQuickDumpStr(node) {
var retval = XsdFile.getNodeName(node) + ' [';
var attrs = node.attributes;
if (attrs != undefined) {
Object.keys(attrs).forEach(function (attr, index, array) {
if (attrs[attr].nodeType === XsdNodeTypes.ATTRIBUTE_NODE) {
retval += attrs[attr].localName + '=' + attrs[attr].value + ' ';
}
}, this);
}
return retval.trim() + ']';
}
static dumpAttrs(node) {
var attrs = node.attributes;
debug('XML-TAG-Attributes:');
if (attrs != undefined) {
Object.keys(attrs).forEach(function (attr, index, array) {
if (attrs[attr].nodeType === XsdNodeTypes.ATTRIBUTE_NODE) {
debug(
'\t' +
index +
') ' +
attrs[attr].localName +
'=' +
attrs[attr].value
);
}
}, this);
}
}
static convertToNumber(value) {
var retval = Number(value);
if (isNaN(retval)) {
return 0;
}
return retval;
}
static getAttrValueAsNumber(node, attrName) {
var value;
if (this.hasAttribute(node, attrName)) {
value = node.getAttribute(attrName);
}
return this.convertToNumber(value);
}
static getAttrValue(node, attrName) {
var retval;
const prefixedAttributes = node.attributes ?
Object.values(node.attributes).filter((attribute) => {
return attribute.nodeValue && attribute.nodeName.includes(`:${attrName}`);
}) :
[];
if (this.hasAttribute(node, attrName)) {
retval = node.getAttribute(attrName);
}
else if (prefixedAttributes.length > 0) {
let foundPrefixedAttribute = prefixedAttributes.find((attribute) => {
return attribute.localName == attrName;
});
retval = foundPrefixedAttribute ?
foundPrefixedAttribute.nodeValue :
retval;
}
return retval;
}
static getAttrValueByPrefix(node, attrPrefix) {
var retval;
var attrs = node.attributes;
var attLength = attrs.length;
for (var i = attLength - 1; i >= 0; i--) {
if (attrs[i].prefix && attrs[i].prefix === attrPrefix) {
retval = attrs[i];
}
}
return retval;
}
static hasAttribute(node, attrName) {
if (node.hasAttribute !== undefined) {
return node.hasAttribute(attrName);
} else {
return false;
}
}
static getNameAttrValue(node) {
return this.getAttrValue(node, XsdAttributes.NAME);
}
static getValueAttr(node) {
return this.getAttrValue(node, XsdAttributes.VALUE);
}
static getValueAttrAsNumber(node) {
if (node == XsdAttributeValues.UNBOUNDED) {
return undefined;
}
return this.getAttrValueAsNumber(node, XsdAttributes.VALUE);
}
static getTypeNode(node) {
let typeNode = node;
while (typeNode.parentNode.localName != XsdElements.SCHEMA) {
typeNode = typeNode.parentNode;
}
return typeNode;
}
static dumpNode(node) {
debug('XML-Type= ' + XsdNodeTypes.getTypeName(node.nodeType));
debug('XML-TAG-Name= ' + node.nodeName);
debug('XML-TAG-NameSpace= ' + node.namespaceURI + '=' + node.namespaceURI);
var text = node.textContent;
if (text != undefined) {
const trimmed = text.trim();
debug(
'XML-Text= [' +
(trimmed.length > 0 ? trimmed : 'it was all whitespace') +
']'
);
}
this.dumpAttrs(node);
debug('__________________________________________');
}
static getNodeName(node) {
var name;
switch (node.nodeType) {
case XsdNodeTypes.TEXT_NODE: // 3
name = 'text';
break;
case XsdNodeTypes.COMMENT_NODE: // 8
name = 'comment';
break;
default:
name = node.localName;
}
return name;
}
static isNamed(node) {
return this.hasAttribute(node, XsdAttributes.NAME);
}
static isReference(node) {
return this.hasAttribute(node, XsdAttributes.REF);
}
static isEmpty(node) {
return this.getChildNodes(node).length == 0;
}
static countChildren(node, tagName) {
// return node.childNodes.length;
const nodeName = node.prefix + ':' + tagName;
var len = node.getElementsByTagName(nodeName).length;
return len;
}
static buildAttributeMap(node) {
var map = {};
var attrs = node.attributes;
Object.keys(attrs).forEach(function (attr, index, array) {
if (attrs[attr].nodeType === XsdNodeTypes.ATTRIBUTE_NODE) {
map[attrs[attr].nodeName] = attrs[attr].value;
}
}, this);
return map;
}
static getChildNodes(node) {
var retval = [];
var nodelist = node.childNodes;
if (nodelist != undefined) {
for (let i = 0; i < nodelist.length; i++) {
retval.push(nodelist.item(i));
}
}
return retval;
}
static getAttributes(node) {
return node.attributes;
}
static getFirstParentWithNameAttribute(node) {
if (!this.hasAttribute(node.parentNode, XsdAttributes.NAME)) {
return this.getFirstParentWithNameAttribute(node.parentNode);
}
return node.parentNode;
}
static getNameOfFirstParentWithNameAttribute(node) {
const firstParentWithName = this.getFirstParentWithNameAttribute(node);
return this.getAttrValue(firstParentWithName, XsdAttributes.NAME);
}
}
module.exports = XsdFile;
},{"../constants":91,"./xsdAttributeValues":119,"./xsdAttributes":120,"./xsdElements":121,"./xsdNodeTypes":123,"debug":3,"urijs":11,"xmldom":84,"xpath":88}],123:[function(require,module,exports){
'use strict';
/**
* Defines constants for XML Schema Node Types. Please see {@link https://www.w3.org/TR/DOM-Level-2-Core/core.html | Document Object Model Core}
*
* @module XsdNodeTypes
*/
module.exports = {
ELEMENT_NODE : 1,
ATTRIBUTE_NODE : 2,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
ENTITY_REFERENCE_NODE : 5,
ENTITY_NODE : 6,
PROCESSING_INSTRUCTION_NODE : 7,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9,
DOCUMENT_TYPE_NODE : 10,
DOCUMENT_FRAGMENT_NODE : 11,
NOTATION_NODE : 12,
getTypeName(value) {
const obj=this;
return Object.keys(obj).find((key) => obj[key] === value);
}
}
},{}],124:[function(require,module,exports){
'use strict';
const debug = require('debug')('xsd2jsonschema:Xsd2JsonSchema');
const URI = require('urijs');
const XsdFile = require('./xmlschema/xsdFileXmlDom');
const BaseConversionVisitor = require('./visitors/baseConversionVisitor');
const DepthFirstTraversal = require('./depthFirstTraversal');
const BaseSpecialCaseIdentifier = require('./baseSpecialCaseIdentifier');
const NamespaceManager = require('./namespaceManager');
const ConverterDraft04 = require('./converterDraft04');
const ConverterDraft06 = require('./converterDraft06');
const ConverterDraft07 = require('./converterDraft07');
const BuiltInTypeConverter = require('./builtInTypeConverter');
const CONSTANTS = require('./constants');
const baseId_NAME = Symbol();
const namespaceManager_NAME = Symbol();
const visitor_NAME = Symbol();
const generateTitle_NAME = Symbol();
const defaultXsd2JsonSchemaOptions = {
baseId: undefined,
namespaceMode: undefined,
jsonSchemaVersion: CONSTANTS.DRAFT_07,
uriStandard: CONSTANTS.RFC_3986,
generateTitle: true
}
/**
* Class prepresenting an instance of the Xsd2JsonSchema library.
*
*/
class Xsd2JsonSchema {
/**
*
* @param {Object} options - An object used to override default options.
* @param {string} options.baseId - The base value for the 'id' in any generated JSON Schema files. The default value is undefined.
* @param {string} options.builtInTypeConverter - An instance of a subclass of {@link BuiltInTypeConverter|BuiltInTypeConverter}.
* @param {string} options.converter - An intance of a subclass of {@link ConverterDraft04|ConverterDraft04}.
* @param {string} options.visitor - A instance of a subclass of {@link BaseConversionVisitor|BaseConversionVisitor}.
* @param {string} options.namespaceMode - The method of handling namespaces. Must be one of: undefined, SUBSCHEMA, or FILENAME. The default value is undefined.
* @param {boolean} options.generateTitle - If true a default title will be generated for top level JSON Schemas. If false it will not be generated. Default: true.
*/
constructor(options) {
var builtInTypeConverter;
var converter;
var jsonSchemaVersion;
if (options != undefined) {
this.baseId = options.baseId != undefined ? options.baseId : defaultXsd2JsonSchemaOptions.baseId;
jsonSchemaVersion = options.jsonSchemaVersion != undefined ? options.jsonSchemaVersion : defaultXsd2JsonSchemaOptions.jsonSchemaVersion;
// BuiltInTypeConverter
builtInTypeConverter = this.getBuiltInTypeConverter(jsonSchemaVersion, options.builtInTypeConverter);
// NamespaceManager
this.namespaceManager = new NamespaceManager({
jsonSchemaVersion: jsonSchemaVersion
});
this.namespaceManager.builtInTypeConverter = builtInTypeConverter;
// Converter
converter = this.getConverter(jsonSchemaVersion, options.converter);
converter.namespaceManager = this.namespaceManager;
converter.specialCaseIdentifier = new BaseSpecialCaseIdentifier();
// Visitor
this.visitor = this.getVisitor(jsonSchemaVersion, options.visitor);
this.visitor.processor = converter;
// Generate Title
this.generateTitle = options.generateTitle == undefined ? defaultXsd2JsonSchemaOptions.generateTitle : options.generateTitle;
} else {
this.baseId = defaultXsd2JsonSchemaOptions.baseId;
// BuiltInTypeConverter
builtInTypeConverter = this.getBuiltInTypeConverter(defaultXsd2JsonSchemaOptions.jsonSchemaVersion);
// NamespaceManager
this.namespaceManager = new NamespaceManager({
jsonSchemaVersion: defaultXsd2JsonSchemaOptions.jsonSchemaVersion
});
this.namespaceManager.builtInTypeConverter = builtInTypeConverter;
// Converter
converter = this.getConverter(defaultXsd2JsonSchemaOptions.jsonSchemaVersion);
converter.namespaceManager = this.namespaceManager;
converter.specialCaseIdentifier = new BaseSpecialCaseIdentifier();
// visitor
this.visitor = new BaseConversionVisitor(converter);
//JsonSchemaFile.setVersion(defaultXsd2JsonSchemaOptions.jsonSchemaVersion);
// Generate Title
this.generateTitle = defaultXsd2JsonSchemaOptions.generateTitle;
}
}
// Getters/Setters
get baseId() {
return this[baseId_NAME];
}
set baseId(newBaseId) {
this[baseId_NAME] = newBaseId;
}
get generateTitle() {
return this[generateTitle_NAME];
}
set generateTitle(newGenerateTitle) {
this[generateTitle_NAME] = newGenerateTitle;
}
// BuiltInTypeConverter
// NamespaceManager
// Converter
// visitor
get namespaceManager() {
return this[namespaceManager_NAME];
}
set namespaceManager(newNamespaceManager) {
this[namespaceManager_NAME] = newNamespaceManager;
}
get visitor() {
return this[visitor_NAME];
}
set visitor(newVisitor) {
this[visitor_NAME] = newVisitor;
}
get jsonSchemas() {
throw new Error('Unsupported operation');
}
set jsonSchemas(newJsonSchema) {
throw new Error('Unsupported operation');
}
get xmlSchemas() {
throw new Error('Unsupported operation');
}
set xmlSchemas(newXmlSchemas) {
throw new Error('Unsupported operation');
}
getBuiltInTypeConverter(jsonSchemaVersion, builtInTypeConverter) {
switch (jsonSchemaVersion) {
case CONSTANTS.DRAFT_04:
case CONSTANTS.DRAFT_06:
case CONSTANTS.DRAFT_07:
if (builtInTypeConverter != undefined) {
return builtInTypeConverter;
} else {
return new BuiltInTypeConverter();
}
break;
default: throw new Error(`Unknown JSON Schema Version supplied [${jsonSchemaVersion}]`);
}
}
validateConverter(jsonSchemaVersion, converterForJsonSchemaVersion, converter) {
if (converter == undefined) {
return false;
}
if (converterForJsonSchemaVersion === converter) {
return true;
}
if (converterForJsonSchemaVersion.prototype.isPrototypeOf(converter)) {
return true;
} else {
throw new Error(`JSON Schema converter version missmatch. The provided converter [${converter.constructor.name}] does not extend the proper converter [${converterForJsonSchemaVersion.name}] for the version of JSON Schema specified [${jsonSchemaVersion}]`);
}
}
getConverter(jsonSchemaVersion, converter) {
var customConverterMsg = 'Converting XML Schema to JSON Schema using custom converter';
var defaultConverterMsg = 'Convertering XML Schema to JSON Schema using default converter for';
var conv;
switch (jsonSchemaVersion) {
case CONSTANTS.DRAFT_04:
if (this.validateConverter(CONSTANTS.DRAFT_04, ConverterDraft04, converter)) {
debug(`${customConverterMsg} [${converter.constructor.name}] for ${CONSTANTS.DRAFT_04}`);
conv = converter;
} else {
debug(`${defaultConverterMsg} ${CONSTANTS.DRAFT_04}`);
conv = new ConverterDraft04();
}
break;
case CONSTANTS.DRAFT_06:
if (this.validateConverter(CONSTANTS.DRAFT_06, ConverterDraft06, converter)) {
debug(`${customConverterMsg} [${converter.constructor.name}] for ${CONSTANTS.DRAFT_06}`);
conv = converter;
} else {
debug(`${defaultConverterMsg} ${CONSTANTS.DRAFT_06}`);
conv = new ConverterDraft06();
}
break;
case CONSTANTS.DRAFT_07:
if (this.validateConverter(CONSTANTS.DRAFT_07, ConverterDraft07, converter)) {
debug(`${customConverterMsg} [${converter.constructor.name}] for ${CONSTANTS.DRAFT_07}`);
conv = converter;
} else {
debug(`${defaultConverterMsg} ${CONSTANTS.DRAFT_07}`);
conv = new ConverterDraft07();
}
break;
default: throw new Error(`Unknown JSON Schema Version supplied [${jsonSchemaVersion}]`);
}
return conv;
}
getVisitor(jsonSchemaVersion, visitor) {
var vis;
switch (jsonSchemaVersion) {
case CONSTANTS.DRAFT_04:
case CONSTANTS.DRAFT_06:
case CONSTANTS.DRAFT_07:
if (visitor != undefined) {
vis = visitor;
} else {
vis = new BaseConversionVisitor();
}
break;
default: throw new Error(`Unknown JSON Schema Version supplied [${jsonSchemaVersion}]`);
}
return vis;
}
loadSchema(uri, xml) {
if (this.namespaceManager.xmlSchemas[uri.toString()] !== undefined) {
return;
}
var xsd = new XsdFile({
xml: xml,
uri: uri
});
this.namespaceManager.xmlSchemas[uri.toString()] = xsd;
}
loadSchemas(schemas) {
const uris = Object.keys(schemas);
uris.forEach(function (uri, index, array) {
this.loadSchema(uri, schemas[uri]);
}, this);
return this.namespaceManager.xmlSchemas;
}
processSchema(uri) {
debug(`Processing XML [${uri.filename()}]`);
const xsd = this.namespaceManager.xmlSchemas[uri.toString()];
const traversal = new DepthFirstTraversal();
var anotherPass = true;
while (anotherPass) {
var jsonSchema = this.namespaceManager.jsonSchemas[uri.toString()];
debug(`About to traverse XML [${xsd.uri.filename()}]`);
// This is a future I hope never comes. For now anotherPass will always come back as false
// because nothing in ConverterDraft04 is setting it otherwise.
anotherPass = traversal.traverse(this.visitor, jsonSchema, xsd);
}
}
processSchemas() {
const filenames = Object.keys(this.namespaceManager.xmlSchemas);
// prime the jsoonSchema map to support forward references in namespaceManager.
filenames.forEach(function (filename, index, array) {
const xsd = this.namespaceManager.xmlSchemas[filename];
const uri = new URI(filename);
this.namespaceManager.addNewJsonSchema({
uri: uri,
namespaceMode: this.namespaceMode,
baseFilename: filename,
targetNamespace: xsd.targetNamespace,
baseId: this.baseId,
title: this.generateTitle ? undefined : ''
});
}, this);
// process each schema
filenames.forEach(function (filename, index, array) {
this.processSchema(new URI(filename));
}, this);
}
processAllSchemas(parms) {
if (parms == undefined) {
throw new Error('The parameter "parms" is required');
}
if (parms.schemas == undefined) {
throw new Error('"parms.schemas" is required');
}
if (parms.visitor != undefined) {
this.visitor = parms.visitor;
}
this.namespaceManager.reset();
this.loadSchemas(parms.schemas);
this.processSchemas();
this.namespaceManager.resolveForwardReferences();
return this.namespaceManager.jsonSchemas;
}
getMaskedFileName(unmaskedFilename) {
if (unmaskedFilename == undefined) {
throw new Error('The parameter unmaskedFilename is required');
}
return (this.mask === undefined) ? unmaskedFilename : unmaskedFilename.replace(this.mask, '');
}
dump() {
debug('\n*** XML Schemas ***');
Object.keys(this.namespaceManager.xmlSchemas).forEach(function (uri, index, array) {
debug(index + ') ' + uri);
debug(this.namespaceManager.xmlSchemas[uri].includeUris);
}, this);
debug('\n*** Namespaces and Types ***');
debug(this.namespaceManager.namespaces);
}
dumpSchemas() {
debug('\n*** JSON Schemas ***');
Object.keys(this.namespaceManager.jsonSchemas).forEach(function (uri, index, array) {
debug(index + ') ' + uri);
var log = JSON.stringify(this.namespaceManager.jsonSchemas[uri].getJsonSchema(), null, 2);
debug(log);
}, this);
}
}
module.exports = Xsd2JsonSchema;
},{"./baseSpecialCaseIdentifier":89,"./builtInTypeConverter":90,"./constants":91,"./converterDraft04":92,"./converterDraft06":93,"./converterDraft07":94,"./depthFirstTraversal":95,"./namespaceManager":107,"./visitors/baseConversionVisitor":114,"./xmlschema/xsdFileXmlDom":122,"debug":3,"urijs":11}],125:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],126:[function(require,module,exports){
(function (Buffer){(function (){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
return arr.foo() === 42
} catch (e) {
return false
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.buffer
}
})
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function () {
if (!Buffer.isBuffer(this)) return undefined
return this.byteOffset
}
})
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError(
'The "string" argument must be of type string. Received type number'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species != null &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
if (ArrayBuffer.isView(value)) {
return fromArrayLike(value)
}
if (value == null) {
throw TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
if (isInstance(value, ArrayBuffer) ||
(value && isInstance(value.buffer, ArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'number') {
throw new TypeError(
'The "value" argument must not be of type number. Received type number'
)
}
var valueOf = value.valueOf && value.valueOf()
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length)
}
var b = fromObject(value)
if (b) return b
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(
value[Symbol.toPrimitive]('string'), encodingOrOffset, length
)
}
throw new TypeError(
'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
'or Array-like Object. Received type ' + (typeof value)
)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number')
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true &&
b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
}
Buffer.compare = function compare (a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError(
'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
)
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (isInstance(buf, Uint8Array)) {
buf = Buffer.from(buf)
}
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
throw new TypeError(
'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
'Received type ' + typeof string
)
}
var len = string.length
var mustMatch = (arguments.length > 2 && arguments[2] === true)
if (!mustMatch && len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
}
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.toLocaleString = Buffer.prototype.toString
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
if (this.length > max) str += ' ... '
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength)
}
if (!Buffer.isBuffer(target)) {
throw new TypeError(
'The "target" argument must be one of type Buffer or Uint8Array. ' +
'Received type ' + (typeof target)
)
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
var strLen = string.length
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end)
} else if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (var i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, end),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if ((encoding === 'utf8' && code < 128) ||
encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code
}
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: Buffer.from(val, encoding)
var len = bytes.length
if (len === 0) {
throw new TypeError('The value "' + val +
'" is invalid for argument "value"')
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0]
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance (obj, type) {
return obj instanceof type ||
(obj != null && obj.constructor != null && obj.constructor.name != null &&
obj.constructor.name === type.name)
}
function numberIsNaN (obj) {
// For IE11 support
return obj !== obj // eslint-disable-line no-self-compare
}
}).call(this)}).call(this,require("buffer").Buffer)
},{"base64-js":125,"buffer":126,"ieee754":127}],127:[function(require,module,exports){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],128:[function(require,module,exports){
arguments[4][7][0].apply(exports,arguments)
},{"_process":129,"dup":7}],129:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],130:[function(require,module,exports){
(function (global){(function (){
/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],131:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
},{}],132:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
},{}],133:[function(require,module,exports){
'use strict';
exports.decode = exports.parse = require('./decode');
exports.encode = exports.stringify = require('./encode');
},{"./decode":131,"./encode":132}],134:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var punycode = require('punycode');
var util = require('./util');
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = require('querystring');
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
},{"./util":135,"punycode":130,"querystring":133}],135:[function(require,module,exports){
'use strict';
module.exports = {
isString: function(arg) {
return typeof(arg) === 'string';
},
isObject: function(arg) {
return typeof(arg) === 'object' && arg !== null;
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
}
};
},{}]},{},[1])(1)
});