castelog
Version:
Programación JavaScript en castellano.
29,177 lines • 1.32 MB
JavaScript
//Included:lib/000.inicializacion.part.js
// CASTELOG@0.0.1
/***************************************************************************************
***[ Manifiesto de Castelog v.0.0.1 ]**********************************[ 2022/08 ]*****
***************************************************************************************
*** ***
*** Castelog es un software construido por «allnulled» o «Carlos Jimeno Hernández». ***
*** ***
*** No tiene licencia, haz lo que quieras con él. ***
*** ***
*************************************************[ Carlos J. / +34 619 98 26 22 ]******
******************************************************************************[ ]******
***************************************************[ Licencia gratis siempre ya ]******
******************************************************************************[ ]******
******************************************************************************[ ]******/
////////////////////////////////////////////////////////////////////////////////
// Aquí empieza el script de Castelog //////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//Included:lib/001.01.xhr2-v.part.js
/*lib:xhr2 v0.2.1 + modifications*/
// Generated by CoffeeScript 2.5.1
(function () {
const is_nodejs_environment = (typeof global !== "undefined") && (typeof require !== "undefined");
if(!is_nodejs_environment) return;
// This file's name is set up in such a way that it will always show up first in
// the list of files given to coffee --join, so that the other files can assume
// that XMLHttpRequestEventTarget was already defined.
// The DOM EventTarget subclass used by XMLHttpRequest.
// @see http://xhr.spec.whatwg.org/#interface-xmlhttprequest
var InvalidStateError, NetworkError, ProgressEvent, SecurityError, SyntaxError, XMLHttpRequest, XMLHttpRequestEventTarget, XMLHttpRequestUpload, http, https, os, url;
XMLHttpRequestEventTarget = (function () {
class XMLHttpRequestEventTarget {
// @private
// This is an abstract class and should not be instantiated directly.
constructor() {
this.onloadstart = null;
this.onprogress = null;
this.onabort = null;
this.onerror = null;
this.onload = null;
this.ontimeout = null;
this.onloadend = null;
this._listeners = {};
}
// Adds a new-style listener for one of the XHR events.
// @see http://www.w3.org/TR/XMLHttpRequest/#events
// @param {String} eventType an XHR event type, such as 'readystatechange'
// @param {function(ProgressEvent)} listener function that will be called when
// the event fires
// @return {undefined} undefined
addEventListener(eventType, listener) {
var base;
eventType = eventType.toLowerCase();
(base = this._listeners)[eventType] || (base[eventType] = []);
this._listeners[eventType].push(listener);
return void 0;
}
// Removes an event listener added by calling addEventListener.
// @param {String} eventType an XHR event type, such as 'readystatechange'
// @param {function(ProgressEvent)} listener the value passed in a previous
// call to addEventListener.
// @return {undefined} undefined
removeEventListener(eventType, listener) {
var index;
eventType = eventType.toLowerCase();
if (this._listeners[eventType]) {
index = this._listeners[eventType].indexOf(listener);
if (index !== -1) {
this._listeners[eventType].splice(index, 1);
}
}
return void 0;
}
// Calls all the listeners for an event.
// @param {ProgressEvent} event the event to be dispatched
// @return {undefined} undefined
dispatchEvent(event) {
var eventType, j, len, listener, listeners;
event.currentTarget = event.target = this;
eventType = event.type;
if (listeners = this._listeners[eventType]) {
for (j = 0, len = listeners.length; j < len; j++) {
listener = listeners[j];
listener.call(this, event);
}
}
if (listener = this[`on${eventType}`]) {
listener.call(this, event);
}
return void 0;
}
};
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'loadstart' event
XMLHttpRequestEventTarget.prototype.onloadstart = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'progress' event
XMLHttpRequestEventTarget.prototype.onprogress = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'abort' event
XMLHttpRequestEventTarget.prototype.onabort = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'error' event
XMLHttpRequestEventTarget.prototype.onerror = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'load' event
XMLHttpRequestEventTarget.prototype.onload = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'timeout' event
XMLHttpRequestEventTarget.prototype.ontimeout = null;
// @property {function(ProgressEvent)} DOM level 0-style handler
// for the 'loadend' event
XMLHttpRequestEventTarget.prototype.onloadend = null;
return XMLHttpRequestEventTarget;
}).call(this);
// This file's name is set up in such a way that it will always show up second
// in the list of files given to coffee --join, so it can use the
// XMLHttpRequestEventTarget definition and so that the other files can assume
// that XMLHttpRequest was already defined.
http = require('http');
https = require('https');
os = require('os');
url = require('url');
XMLHttpRequest = (function () {
// The ECMAScript HTTP API.
// @see http://www.w3.org/TR/XMLHttpRequest/#introduction
class XMLHttpRequest extends XMLHttpRequestEventTarget {
// Creates a new request.
// @param {Object} options one or more of the options below
// @option options {Boolean} anon if true, the request's anonymous flag
// will be set
// @see http://www.w3.org/TR/XMLHttpRequest/#constructors
// @see http://www.w3.org/TR/XMLHttpRequest/#anonymous-flag
constructor(options) {
super();
this.onreadystatechange = null;
this._anonymous = options && options.anon;
this.readyState = XMLHttpRequest.UNSENT;
this.response = null;
this.responseText = '';
this.responseType = '';
this.responseURL = '';
this.status = 0;
this.statusText = '';
this.timeout = 0;
this.upload = new XMLHttpRequestUpload(this);
this._method = null; // String
this._url = null; // Return value of url.parse()
this._sync = false;
this._headers = null; // Object<String, String>
this._loweredHeaders = null; // Object<lowercase String, String>
this._mimeOverride = null;
this._request = null; // http.ClientRequest
this._response = null; // http.ClientResponse
this._responseParts = null; // Array<Buffer, String>
this._responseHeaders = null; // Object<lowercase String, String>
this._aborting = null;
this._error = null;
this._loadedBytes = 0;
this._totalBytes = 0;
this._lengthComputable = false;
}
// Sets the XHR's method, URL, synchronous flag, and authentication params.
// @param {String} method the HTTP method to be used
// @param {String} url the URL that the request will be made to
// @param {?Boolean} async if false, the XHR should be processed
// synchronously; true by default
// @param {?String} user the user credential to be used in HTTP basic
// authentication
// @param {?String} password the password credential to be used in HTTP basic
// authentication
// @return {undefined} undefined
// @throw {SecurityError} method is not one of the allowed methods
// @throw {SyntaxError} urlString is not a valid URL
// @throw {Error} the URL contains an unsupported protocol; the supported
// protocols are file, http and https
// @see http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
open(method, url, async, user, password) {
var xhrUrl;
method = method.toUpperCase();
if (method in this._restrictedMethods) {
throw new SecurityError(`HTTP method ${method} is not allowed in XHR`);
}
xhrUrl = this._parseUrl(url);
if (async === void 0) {
async = true;
}
switch (this.readyState) {
case XMLHttpRequest.UNSENT:
case XMLHttpRequest.OPENED:
case XMLHttpRequest.DONE:
// Nothing to do here.
null;
break;
case XMLHttpRequest.HEADERS_RECEIVED:
case XMLHttpRequest.LOADING:
// TODO(pwnall): terminate abort(), terminate send()
null;
}
this._method = method;
this._url = xhrUrl;
this._sync = !async;
this._headers = {};
this._loweredHeaders = {};
this._mimeOverride = null;
this._setReadyState(XMLHttpRequest.OPENED);
this._request = null;
this._response = null;
this.status = 0;
this.statusText = '';
this._responseParts = [];
this._responseHeaders = null;
this._loadedBytes = 0;
this._totalBytes = 0;
this._lengthComputable = false;
return void 0;
}
// Appends a header to the list of author request headers.
// @param {String} name the HTTP header name
// @param {String} value the HTTP header value
// @return {undefined} undefined
// @throw {InvalidStateError} readyState is not OPENED
// @throw {SyntaxError} name is not a valid HTTP header name or value is not
// a valid HTTP header value
// @see http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
setRequestHeader(name, value) {
var loweredName;
if (this.readyState !== XMLHttpRequest.OPENED) {
throw new InvalidStateError("XHR readyState must be OPENED");
}
loweredName = name.toLowerCase();
if (this._restrictedHeaders[loweredName] || /^sec\-/.test(loweredName) || /^proxy-/.test(loweredName)) {
console.warn(`Refused to set unsafe header \"${name}\"`);
return void 0;
}
value = value.toString();
if (loweredName in this._loweredHeaders) {
// Combine value with the existing header value.
name = this._loweredHeaders[loweredName];
this._headers[name] = this._headers[name] + ', ' + value;
} else {
// New header.
this._loweredHeaders[loweredName] = name;
this._headers[name] = value;
}
return void 0;
}
// Initiates the request.
// @param {?String, ?ArrayBufferView} data the data to be sent; ignored for
// GET and HEAD requests
// @return {undefined} undefined
// @throw {InvalidStateError} readyState is not OPENED
// @see http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
send(data) {
if (this.readyState !== XMLHttpRequest.OPENED) {
throw new InvalidStateError("XHR readyState must be OPENED");
}
if (this._request) {
throw new InvalidStateError("send() already called");
}
switch (this._url.protocol) {
case 'file:':
this._sendFile(data);
break;
case 'http:':
case 'https:':
this._sendHttp(data);
break;
default:
throw new NetworkError(`Unsupported protocol ${this._url.protocol}`);
}
return void 0;
}
// Cancels the network activity performed by this request.
// @return {undefined} undefined
// @see http://www.w3.org/TR/XMLHttpRequest/#the-abort()-method
abort() {
if (!this._request) {
return;
}
this._request.abort();
this._setError();
this._dispatchProgress('abort');
this._dispatchProgress('loadend');
return void 0;
}
// Returns a header value in the HTTP response for this XHR.
// @param {String} name case-insensitive HTTP header name
// @return {?String} value the value of the header whose name matches the
// given name, or null if there is no such header
// @see http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
getResponseHeader(name) {
var loweredName;
if (!this._responseHeaders) {
return null;
}
loweredName = name.toLowerCase();
if (loweredName in this._responseHeaders) {
return this._responseHeaders[loweredName];
} else {
return null;
}
}
// Returns all the HTTP headers in this XHR's response.
// @return {String} header lines separated by CR LF, where each header line
// has the name and value separated by a ": " (colon, space); the empty
// string is returned if the headers are not available
// @see http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
getAllResponseHeaders() {
var lines, name, value;
if (!this._responseHeaders) {
return '';
}
lines = (function () {
var ref, results;
ref = this._responseHeaders;
results = [];
for (name in ref) {
value = ref[name];
results.push(`${name}: ${value}`);
}
return results;
}).call(this);
return lines.join("\r\n");
}
// Overrides the Content-Type
// @return {undefined} undefined
// @see http://www.w3.org/TR/XMLHttpRequest/#the-overridemimetype()-method
overrideMimeType(newMimeType) {
if (this.readyState === XMLHttpRequest.LOADING || this.readyState === XMLHttpRequest.DONE) {
throw new InvalidStateError("overrideMimeType() not allowed in LOADING or DONE");
}
this._mimeOverride = newMimeType.toLowerCase();
return void 0;
}
// Network configuration not exposed in the XHR API.
// Although the XMLHttpRequest specification calls itself "ECMAScript HTTP",
// it assumes that requests are always performed in the context of a browser
// application, where some network parameters are set by the browser user and
// should not be modified by Web applications. This API provides access to
// these network parameters.
// NOTE: this is not in the XMLHttpRequest API, and will not work in
// browsers. It is a stable node-xhr2 API.
// @param {Object} options one or more of the options below
// @option options {?http.Agent} httpAgent the value for the nodejsHttpAgent
// property (the agent used for HTTP requests)
// @option options {?https.Agent} httpsAgent the value for the
// nodejsHttpsAgent property (the agent used for HTTPS requests)
// @return {undefined} undefined
nodejsSet(options) {
var baseUrl, parsedUrl;
if ('httpAgent' in options) {
this.nodejsHttpAgent = options.httpAgent;
}
if ('httpsAgent' in options) {
this.nodejsHttpsAgent = options.httpsAgent;
}
if ('baseUrl' in options) {
baseUrl = options.baseUrl;
if (baseUrl !== null) {
parsedUrl = url.parse(baseUrl, false, true);
if (!parsedUrl.protocol) {
throw new SyntaxError("baseUrl must be an absolute URL");
}
}
this.nodejsBaseUrl = baseUrl;
}
return void 0;
}
// Default settings for the network configuration not exposed in the XHR API.
// NOTE: this is not in the XMLHttpRequest API, and will not work in
// browsers. It is a stable node-xhr2 API.
// @param {Object} options one or more of the options below
// @option options {?http.Agent} httpAgent the default value for the
// nodejsHttpAgent property (the agent used for HTTP requests)
// @option options {https.Agent} httpsAgent the default value for the
// nodejsHttpsAgent property (the agent used for HTTPS requests)
// @return {undefined} undefined
// @see XMLHttpRequest.nodejsSet
static nodejsSet(options) {
// "this" will be set to XMLHttpRequest.prototype, so the instance nodejsSet
// operates on default property values.
XMLHttpRequest.prototype.nodejsSet(options);
return void 0;
}
// Sets the readyState property and fires the readystatechange event.
// @private
// @param {Number} newReadyState the new value of readyState
// @return {undefined} undefined
_setReadyState(newReadyState) {
var event;
this.readyState = newReadyState;
event = new ProgressEvent('readystatechange');
this.dispatchEvent(event);
return void 0;
}
// XMLHttpRequest#send() implementation for the file: protocol.
// @private
_sendFile() {
if (this._url.method !== 'GET') {
throw new NetworkError('The file protocol only supports GET');
}
throw new Error("Protocol file: not implemented");
}
// XMLHttpRequest#send() implementation for the http: and https: protocols.
// @private
// This method sets the instance variables and calls _sendHxxpRequest(), which
// is responsible for building a node.js request and firing it off. The code
// in _sendHxxpRequest() is separated off so it can be reused when handling
// redirects.
// @see http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send()-method
_sendHttp(data) {
if (this._sync) {
throw new Error("Synchronous XHR processing not implemented");
}
if ((data != null) && (this._method === 'GET' || this._method === 'HEAD')) {
console.warn(`Discarding entity body for ${this._method} requests`);
data = null;
} else {
// Send Content-Length: 0
data || (data = '');
}
// NOTE: this is called before finalizeHeaders so that the uploader can
// figure out Content-Length and Content-Type.
this.upload._setData(data);
this._finalizeHeaders();
this._sendHxxpRequest();
return void 0;
}
// Sets up and fires off a HTTP/HTTPS request using the node.js API.
// @private
// This method contains the bulk of the XMLHttpRequest#send() implementation,
// and is also used to issue new HTTP requests when handling HTTP redirects.
// @see http://www.w3.org/TR/XMLHttpRequest/#infrastructure-for-the-send()-method
_sendHxxpRequest() {
var agent, hxxp, request;
if (this._url.protocol === 'http:') {
hxxp = http;
agent = this.nodejsHttpAgent;
} else {
hxxp = https;
agent = this.nodejsHttpsAgent;
}
request = hxxp.request({
hostname: this._url.hostname,
port: this._url.port,
path: this._url.path,
auth: this._url.auth,
method: this._method,
headers: this._headers,
agent: agent
});
this._request = request;
if (this.timeout) {
request.setTimeout(this.timeout, () => {
return this._onHttpTimeout(request);
});
}
request.on('response', (response) => {
return this._onHttpResponse(request, response);
});
request.on('error', (error) => {
return this._onHttpRequestError(request, error);
});
this.upload._startUpload(request);
if (this._request === request) { // An http error might have already fired.
this._dispatchProgress('loadstart');
}
return void 0;
}
// Fills in the restricted HTTP headers with default values.
// This is called right before the HTTP request is sent off.
// @private
// @return {undefined} undefined
_finalizeHeaders() {
var base;
this._headers['Connection'] = 'keep-alive';
this._headers['Host'] = this._url.host;
if (this._anonymous) {
this._headers['Referer'] = 'about:blank';
}
(base = this._headers)['User-Agent'] || (base['User-Agent'] = this._userAgent);
this.upload._finalizeHeaders(this._headers, this._loweredHeaders);
return void 0;
}
// Called when the headers of an HTTP response have been received.
// @private
// @param {http.ClientRequest} request the node.js ClientRequest instance that
// produced this response
// @param {http.ClientResponse} response the node.js ClientResponse instance
// passed to
_onHttpResponse(request, response) {
var lengthString;
if (this._request !== request) {
return;
}
// Transparent redirection handling.
switch (response.statusCode) {
case 301:
case 302:
case 303:
case 307:
case 308:
this._url = this._parseUrl(response.headers['location']);
this._method = 'GET';
if ('content-type' in this._loweredHeaders) {
delete this._headers[this._loweredHeaders['content-type']];
delete this._loweredHeaders['content-type'];
}
// XMLHttpRequestUpload#_finalizeHeaders() sets Content-Type directly.
if ('Content-Type' in this._headers) {
delete this._headers['Content-Type'];
}
// Restricted headers can't be set by the user, no need to check
// loweredHeaders.
delete this._headers['Content-Length'];
this.upload._reset();
this._finalizeHeaders();
this._sendHxxpRequest();
return;
}
this._response = response;
this._response.on('data', (data) => {
return this._onHttpResponseData(response, data);
});
this._response.on('end', () => {
return this._onHttpResponseEnd(response);
});
this._response.on('close', () => {
return this._onHttpResponseClose(response);
});
this.responseURL = this._url.href.split('#')[0];
this.status = this._response.statusCode;
this.statusText = http.STATUS_CODES[this.status];
this._parseResponseHeaders(response);
if (lengthString = this._responseHeaders['content-length']) {
this._totalBytes = parseInt(lengthString);
this._lengthComputable = true;
} else {
this._lengthComputable = false;
}
return this._setReadyState(XMLHttpRequest.HEADERS_RECEIVED);
}
// Called when some data has been received on a HTTP connection.
// @private
// @param {http.ClientResponse} response the node.js ClientResponse instance
// that fired this event
// @param {String, Buffer} data the data that has been received
_onHttpResponseData(response, data) {
if (this._response !== response) {
return;
}
this._responseParts.push(data);
this._loadedBytes += data.length;
if (this.readyState !== XMLHttpRequest.LOADING) {
this._setReadyState(XMLHttpRequest.LOADING);
}
return this._dispatchProgress('progress');
}
// Called when the HTTP request finished processing.
// @private
// @param {http.ClientResponse} response the node.js ClientResponse instance
// that fired this event
_onHttpResponseEnd(response) {
if (this._response !== response) {
return;
}
this._parseResponse();
this._request = null;
this._response = null;
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('load');
return this._dispatchProgress('loadend');
}
// Called when the underlying HTTP connection was closed prematurely.
// If this method is called, it will be called after or instead of
// onHttpResponseEnd.
// @private
// @param {http.ClientResponse} response the node.js ClientResponse instance
// that fired this event
_onHttpResponseClose(response) {
var request;
if (this._response !== response) {
return;
}
request = this._request;
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('error');
return this._dispatchProgress('loadend');
}
// Called when the timeout set on the HTTP socket expires.
// @private
// @param {http.ClientRequest} request the node.js ClientRequest instance that
// fired this event
_onHttpTimeout(request) {
if (this._request !== request) {
return;
}
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('timeout');
return this._dispatchProgress('loadend');
}
// Called when something wrong happens on the HTTP socket
// @private
// @param {http.ClientRequest} request the node.js ClientRequest instance that
// fired this event
// @param {Error} error emitted exception
_onHttpRequestError(request, error) {
if (this._request !== request) {
return;
}
this._setError();
request.abort();
this._setReadyState(XMLHttpRequest.DONE);
this._dispatchProgress('error');
return this._dispatchProgress('loadend');
}
// Fires an XHR progress event.
// @private
// @param {String} eventType one of the XHR progress event types, such as
// 'load' and 'progress'
_dispatchProgress(eventType) {
var event;
event = new ProgressEvent(eventType);
event.lengthComputable = this._lengthComputable;
event.loaded = this._loadedBytes;
event.total = this._totalBytes;
this.dispatchEvent(event);
return void 0;
}
// Sets up the XHR to reflect the fact that an error has occurred.
// The possible errors are a network error, a timeout, or an abort.
// @private
_setError() {
this._request = null;
this._response = null;
this._responseHeaders = null;
this._responseParts = null;
return void 0;
}
// Parses a request URL string.
// @private
// This method is a thin wrapper around url.parse() that normalizes HTTP
// user/password credentials. It is used to parse the URL string passed to
// XMLHttpRequest#open() and the URLs in the Location headers of HTTP redirect
// responses.
// @param {String} urlString the URL to be parsed
// @return {Object} parsed URL
_parseUrl(urlString) {
var absoluteUrlString, index, password, user, xhrUrl;
if (this.nodejsBaseUrl === null) {
absoluteUrlString = urlString;
} else {
absoluteUrlString = url.resolve(this.nodejsBaseUrl, urlString);
}
xhrUrl = url.parse(absoluteUrlString, false, true);
xhrUrl.hash = null;
if (xhrUrl.auth && ((typeof user !== "undefined" && user !== null) || (typeof password !== "undefined" && password !== null))) {
index = xhrUrl.auth.indexOf(':');
if (index === -1) {
if (!user) {
user = xhrUrl.auth;
}
} else {
if (!user) {
user = xhrUrl.substring(0, index);
}
if (!password) {
password = xhrUrl.substring(index + 1);
}
}
}
if (user || password) {
xhrUrl.auth = `${user}:${password}`;
}
return xhrUrl;
}
// Reads the headers from a node.js ClientResponse instance.
// @private
// @param {http.ClientResponse} response the response whose headers will be
// imported into this XMLHttpRequest's state
// @return {undefined} undefined
// @see http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
// @see http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
_parseResponseHeaders(response) {
var loweredName, name, ref, value;
this._responseHeaders = {};
ref = response.headers;
for (name in ref) {
value = ref[name];
loweredName = name.toLowerCase();
if (this._privateHeaders[loweredName]) {
continue;
}
if (this._mimeOverride !== null && loweredName === 'content-type') {
value = this._mimeOverride;
}
this._responseHeaders[loweredName] = value;
}
if (this._mimeOverride !== null && !('content-type' in this._responseHeaders)) {
this._responseHeaders['content-type'] = this._mimeOverride;
}
return void 0;
}
// Sets the response and responseText properties when an XHR completes.
// @private
// @return {undefined} undefined
_parseResponse() {
var arrayBuffer, buffer, i, j, jsonError, ref, view;
if (Buffer.concat) {
buffer = Buffer.concat(this._responseParts);
} else {
// node 0.6
buffer = this._concatBuffers(this._responseParts);
}
this._responseParts = null;
switch (this.responseType) {
case 'text':
this._parseTextResponse(buffer);
break;
case 'json':
this.responseText = null;
try {
this.response = JSON.parse(buffer.toString('utf-8'));
} catch (error1) {
jsonError = error1;
this.response = null;
}
break;
case 'buffer':
this.responseText = null;
this.response = buffer;
break;
case 'arraybuffer':
this.responseText = null;
arrayBuffer = new ArrayBuffer(buffer.length);
view = new Uint8Array(arrayBuffer);
for (i = j = 0, ref = buffer.length; (0 <= ref ? j < ref : j > ref); i = 0 <= ref ? ++j : --j) {
view[i] = buffer[i];
}
this.response = arrayBuffer;
break;
default:
// TODO(pwnall): content-base detection
this._parseTextResponse(buffer);
}
return void 0;
}
// Sets response and responseText for a 'text' response type.
// @private
// @param {Buffer} buffer the node.js Buffer containing the binary response
// @return {undefined} undefined
_parseTextResponse(buffer) {
var e;
try {
this.responseText = buffer.toString(this._parseResponseEncoding());
} catch (error1) {
e = error1;
// Unknown encoding.
this.responseText = buffer.toString('binary');
}
this.response = this.responseText;
return void 0;
}
// Figures out the string encoding of the XHR's response.
// This is called to determine the encoding when responseText is set.
// @private
// @return {String} a string encoding, e.g. 'utf-8'
_parseResponseEncoding() {
var contentType, encoding, match;
encoding = null;
if (contentType = this._responseHeaders['content-type']) {
if (match = /\;\s*charset\=(.*)$/.exec(contentType)) {
return match[1];
}
}
return 'utf-8';
}
// Buffer.concat implementation for node 0.6.
// @private
// @param {Array<Buffer>} buffers the buffers whose contents will be merged
// @return {Buffer} same as Buffer.concat(buffers) in node 0.8 and above
_concatBuffers(buffers) {
var buffer, j, k, len, len1, length, target;
if (buffers.length === 0) {
return Buffer.alloc(0);
}
if (buffers.length === 1) {
return buffers[0];
}
length = 0;
for (j = 0, len = buffers.length; j < len; j++) {
buffer = buffers[j];
length += buffer.length;
}
target = Buffer.alloc(length);
length = 0;
for (k = 0, len1 = buffers.length; k < len1; k++) {
buffer = buffers[k];
buffer.copy(target, length);
length += buffer.length;
}
return target;
}
};
// @property {function(ProgressEvent)} DOM level 0-style handler for the
// 'readystatechange' event
XMLHttpRequest.prototype.onreadystatechange = null;
// @property {Number} the current state of the XHR object
// @see http://www.w3.org/TR/XMLHttpRequest/#states
XMLHttpRequest.prototype.readyState = null;
// @property {String, ArrayBuffer, Buffer, Object} processed XHR response
// @see http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
XMLHttpRequest.prototype.response = null;
// @property {String} response string, if responseType is '' or 'text'
// @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
XMLHttpRequest.prototype.responseText = null;
// @property {String} sets the parsing method for the XHR response
// @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
XMLHttpRequest.prototype.responseType = null;
// @property {Number} the HTTP
// @see http://www.w3.org/TR/XMLHttpRequest/#the-status-attribute
XMLHttpRequest.prototype.status = null;
// @property {Number} milliseconds to wait for the request to complete
// @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
XMLHttpRequest.prototype.timeout = null;
// @property {XMLHttpRequestUpload} the associated upload information
// @see http://www.w3.org/TR/XMLHttpRequest/#the-upload-attribute
XMLHttpRequest.prototype.upload = null;
// readyState value before XMLHttpRequest#open() is called
XMLHttpRequest.prototype.UNSENT = 0;
// readyState value before XMLHttpRequest#open() is called
XMLHttpRequest.UNSENT = 0;
// readyState value after XMLHttpRequest#open() is called, and before
// XMLHttpRequest#send() is called; XMLHttpRequest#setRequestHeader() can be
// called in this state
XMLHttpRequest.prototype.OPENED = 1;
// readyState value after XMLHttpRequest#open() is called, and before
// XMLHttpRequest#send() is called; XMLHttpRequest#setRequestHeader() can be
// called in this state
XMLHttpRequest.OPENED = 1;
// readyState value after redirects have been followed and the HTTP headers of
// the final response have been received
XMLHttpRequest.prototype.HEADERS_RECEIVED = 2;
// readyState value after redirects have been followed and the HTTP headers of
// the final response have been received
XMLHttpRequest.HEADERS_RECEIVED = 2;
// readyState value when the response entity body is being received
XMLHttpRequest.prototype.LOADING = 3;
// readyState value when the response entity body is being received
XMLHttpRequest.LOADING = 3;
// readyState value after the request has been completely processed
XMLHttpRequest.prototype.DONE = 4;
// readyState value after the request has been completely processed
XMLHttpRequest.DONE = 4;
// @property {http.Agent} the agent option passed to HTTP requests
// NOTE: this is not in the XMLHttpRequest API, and will not work in browsers.
// It is a stable node-xhr2 API that is useful for testing & going through
// web-proxies.
XMLHttpRequest.prototype.nodejsHttpAgent = http.globalAgent;
// @property {https.Agent} the agent option passed to HTTPS requests
// NOTE: this is not in the XMLHttpRequest API, and will not work in browsers.
// It is a stable node-xhr2 API that is useful for testing & going through
// web-proxies.
XMLHttpRequest.prototype.nodejsHttpsAgent = https.globalAgent;
// @property {String} the base URL that relative URLs get resolved to
// NOTE: this is not in the XMLHttpRequest API, and will not work in browsers.
// Its browser equivalent is the base URL of the document associated with the
// Window object. It is a stable node-xhr2 API provided for libraries such as
// Angular Universal.
XMLHttpRequest.prototype.nodejsBaseUrl = null;
// HTTP methods that are disallowed in the XHR spec.
// @private
// @see Step 6 in http://www.w3.org/TR/XMLHttpRequest/#the-open()-method
XMLHttpRequest.prototype._restrictedMethods = {
CONNECT: true,
TRACE: true,
TRACK: true
};
// HTTP request headers that are disallowed in the XHR spec.
// @private
// @see Step 5 in
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader()-method
XMLHttpRequest.prototype._restrictedHeaders = {
'accept-charset': true,
'accept-encoding': true,
'access-control-request-headers': true,
'access-control-request-method': true,
connection: true,
'content-length': true,
cookie: true,
cookie2: true,
date: true,
dnt: true,
expect: true,
host: true,
'keep-alive': true,
origin: true,
referer: true,
te: true,
trailer: true,
'transfer-encoding': true,
upgrade: true,
via: true
};
// HTTP response headers that should not be exposed according to the XHR spec.
// @private
// @see Step 3 in
// http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
XMLHttpRequest.prototype._privateHeaders = {
'set-cookie': true,
'set-cookie2': true
};
// The default value of the User-Agent header.
XMLHttpRequest.prototype._userAgent = `Mozilla/5.0 (${os.type()} ${os.arch()}) ` + `node.js/${process.versions.node} v8/${process.versions.v8}`;
return XMLHttpRequest;
}).call(this);
// XMLHttpRequest is the result of require('node-xhr2').
module.exports = XMLHttpRequest;
// Make node-xhr2 work as a drop-in replacement for libraries that promote the
// following usage pattern:
// var XMLHttpRequest = require('xhr-library-name').XMLHttpRequest
XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
// This file defines the custom errors used in the XMLHttpRequest specification.
// Thrown if the XHR security policy is violated.
SecurityError = class SecurityError extends Error {
// @private
constructor() {
super();
}
};
// Thrown if the XHR security policy is violated.
XMLHttpRequest.SecurityError = SecurityError;
// Usually thrown if the XHR is in the wrong readyState for an operation.
InvalidStateError = class InvalidStateError extends Error {
// @private
constructor() {
super();
}
};
// Usually thrown if the XHR is in the wrong readyState for an operation.
InvalidStateError = class InvalidStateError extends Error { };
XMLHttpRequest.InvalidStateError = InvalidStateError;
// Thrown if there is a problem with the URL passed to the XHR.
NetworkError = class NetworkError extends Error {
// @private
constructor() {
super();
}
};
// Thrown if parsing URLs errors out.
XMLHttpRequest.SyntaxError = SyntaxError;
SyntaxError = class SyntaxError extends Error {
// @private:
constructor() {
super();
}
};
ProgressEvent = (function () {
// http://xhr.spec.whatwg.org/#interface-progressevent
class ProgressEvent {
// Creates a new event.
// @param {String} type the event type, e.g. 'readystatechange'; must be
// lowercased
constructor(type) {
this.type = type;
this.target = null;
this.currentTarget = null;
this.lengthComputable = false;
this.loaded = 0;
this.total = 0;
}
};
// Getting the time from the OS is expensive, skip on that for now.
// @timeStamp = Date.now()
// @property {Boolean} for compatibility with DOM events
ProgressEvent.prototype.bubbles = false;
// @property {Boolean} for fompatibility with DOM events
ProgressEvent.prototype.cancelable = false;
// @property {XMLHttpRequest} the request that caused this event
ProgressEvent.prototype.target = null;
// @property {Number} number of bytes that have already been downloaded or
// uploaded
ProgressEvent.prototype.loaded = null;
// @property {Boolean} true if the Content-Length response header is available
// and the value of the event's total property is meaningful
ProgressEvent.prototype.lengthComputable = null;
// @property {Number} number of bytes that will be downloaded or uploaded by
// the request that fired the event
ProgressEvent.prototype.total = null;
return ProgressEvent;
}).call(this);
// The XHR spec exports the ProgressEvent constructor.
XMLHttpRequest.ProgressEvent = ProgressEvent;
// @see http://xhr.spec.whatwg.org/#interface-xmlhttprequest
XMLHttpRequestUpload = class XMLHttpRequestUpload extends XMLHttpRequestEventTarget {
// @private
// @param {XMLHttpRequest} the XMLHttpRequest that this upload object is
// associated with
constructor(request) {
super();
this._request = request;
this._reset();
}
// Sets up this Upload to handle a new request.
// @private
// @return {undefined} undefined
_reset() {
this._contentType = null;
this._body = null;
return void 0;
}
// Implements the upload-related part of the send() XHR specification.
// @private
// @param {?String, ?Buffer, ?ArrayBufferView} data the argument passed to
// XMLHttpRequest#send()
// @return {undefined} undefined
// @see step 4 of http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
_setData(data) {
var body, i, j, k, offset, ref, ref1, view;
if (typeof data === 'undefined' || data === null) {
return;
}
if (typeof data === 'string') {
// DOMString
if (data.length !== 0) {
this._contentType = 'text/plain;charset=UTF-8';
}
this._body = Buffer.from(data, 'utf8');
} else if (Buffer.isBuffer(data)) {
// node.js Buffer
this._body = data;
} else if (data instanceof ArrayBuffer) {
// ArrayBuffer arguments were supported in an old revision of the spec.
body = Buffer.alloc(data.byteLength);
view = new Uint8Array(data);
for (i = j = 0, ref = data.byteLength; (0 <= ref ? j < ref : j > ref); i = 0 <= ref ? ++j : --j) {
body[i] = view[i];
}
this._body = body;
} else if (data.buffer && data.buffer instanceof ArrayBuffer) {
// ArrayBufferView
body = Buffer.alloc(data.byteLength);
offset = data.byteOffset;
view = new Uint8Array(data.buffer);
for (i = k = 0, ref1 = data.byteLength; (0 <= ref1 ? k < ref1 : k > ref1); i = 0 <= ref1 ? ++k : --k) {
body[i] = view[i + offset];
}
this._body = body;
} else {
// NOTE: diverging from the XHR specification of coercing everything else
// to Strings via toString() because that behavior masks bugs and is
// rarely useful
throw new Error(`Unsupported send() data ${data}`);
}
return void 0;
}
// Updates the HTTP headers right before the request is sent.
// This is used to set data-dependent headers such as Content-Length and
// Content-Type.
// @private
// @param {Object<String, String>} headers the HTTP headers to be sent
// @param {Object<String, String>} loweredHeaders maps lowercased HTTP header
// names (e.g., 'content-type') to the actual names used in the headers
// parameter (e.g., 'Content-Type')
// @return {undefined} undefined
_finalizeHeaders(headers, loweredHeaders) {
if (this._contentType) {
if (!('content-type' in loweredHeaders)) {
headers['Content-Type'] = this._contentType;
}
}
if (this._body) {
// Restricted headers can't be set by the user, no need to check
// loweredHeaders.
headers['Content-Length'] = this._body.length.toString();
}
return void 0;
}
// Starts sending the HTTP request data.
// @private
// @param {http.ClientRequest} request the HTTP request
// @return {undefined} undefined
_startUpload(request) {
if (this._body) {
request.write(this._body);
}
request.end();
return void 0;
}
};
// Export the XMLHttpRequestUpload constructor.
XMLHttpRequest.XMLHttpRequestUpload = XMLHttpRequestUpload;
if(typeof global !== "undefined") {
global.XMLHttpRequest = XMLHttpRequest;
}
}).call(this);
//Included:lib/001.02.axios-v0.27.2.part.js
/*lib:axios v0.27.2 + modifications*/
/*(c) 2022 by Matt Zabriskie*/
(function webpackUniversalModuleDefinition(factory) {
const axios_module = factory();
if (typeof exports === 'object' && typeof module === 'object') {
module.exports = axios_module;
} else if (typeof exports === 'object') {
exports["axios"] = axios_module;
}
if(typeof window !== "undefined") {
window.axios = axios_module;
}
if(typeof global !== "undefined") {
global.axios = axios_module;
}
})(function () {
return /******/ (function (modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if (installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/
}
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/
};
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/
}
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function (exports, name, getter) {
/******/ if (!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/
}
/******/
};
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function (exports) {
/******/ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/
}
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/
};
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function (value, mode) {
/******/ if (mode & 1) value = __webpack_require__(value);
/******/ if (mode & 8) return value;
/******/ if ((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if (mode & 2 && typeof value != 'string') for (var key in value) __webpack_require__.d(ns, key, function (key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/
};
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function (module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/
};
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./index.js");
/******/
})
/************************************************************************/
/******/({
/***/ "./index.js":
/*!******************!*\
!*** ./index.js ***!
\******************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./lib/axios */ "./lib/axios.js");
/***/
}),
/***/ "./lib/adapters/xhr.js":
/*!*****************************!*\
!*** ./lib/adapters/xhr.js ***!
\*****************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
var settle = __webpack_require__(/*! ./../core/settle */ "./lib/core/settle.js");
var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./lib/helpers/cookies.js");
var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./lib/helpers/buildURL.js");
var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./lib/core/buildFullPath.js");
var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./lib/helpers/parseHeaders.js");
var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./lib/helpers/isURLSameOrigin.js");
var transitionalDefaults = __webpack_require__(/*! ../defaults/transitional */ "./lib/defaults/transitional.js");
var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
var CanceledError = __webpack_require__(/*! ../cancel/CanceledError */ "./lib/cancel/CanceledError.js");
var parseProtocol = __webpack_require__(/*! ../helpers/parseProtocol */ "./lib/helpers/parseProtocol.js");
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function (cancel) {
if (!request) {
return;
}
reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
if (!requestData) {
requestData = null;
}
var protocol = parseProtocol(fullPath);
if (protocol && ['http', 'https', 'file'].indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData);
});
};
/***/
}),
/***/ "./lib/axios.js":
/*!**********************!*\
!*** ./lib/axios.js ***!
\**********************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./utils */ "./lib/utils.js");
var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js");
var Axios = __webpack_require__(/*! ./core/Axios */ "./lib/core/Axios.js");
var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./lib/core/mergeConfig.js");
var defaults = __webpack_require__(/*! ./defaults */ "./lib/defaults/index.js");
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = __webpack_require__(/*! ./cancel/CanceledError */ "./lib/cancel/CanceledError.js");
axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./lib/cancel/CancelToken.js");
axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./lib/cancel/isCancel.js");
axios.VERSION = __webpack_require__(/*! ./env/data */ "./lib/env/data.js").version;
axios.toFormData = __webpack_require__(/*! ./helpers/toFormData */ "./lib/helpers/toFormData.js");
// Expose AxiosError class
axios.AxiosError = __webpack_require__(/*! ../lib/core/AxiosError */ "./lib/core/AxiosError.js");
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(/*! ./helpers/spread */ "./lib/helpers/spread.js");
// Expose isAxiosError
axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./lib/helpers/isAxiosError.js");
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/
}),
/***/ "./lib/cancel/CancelToken.js":
/*!***********************************!*\
!*** ./lib/cancel/CancelToken.js ***!
\***********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var CanceledError = __webpack_require__(/*! ./CanceledError */ "./lib/cancel/CanceledError.js");
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function (cancel) {
if (!token._listeners) return;
var i;
var l = token._listeners.length;
for (i = 0; i < l; i++) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function (onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function (resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/
}),
/***/ "./lib/cancel/CanceledError.js":
/*!*************************************!*\
!*** ./lib/cancel/CanceledError.js ***!
\*************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function CanceledError(message) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);
this.name = 'CanceledError';
}
utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
module.exports = CanceledError;
/***/
}),
/***/ "./lib/cancel/isCancel.js":
/*!********************************!*\
!*** ./lib/cancel/isCancel.js ***!
\********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/
}),
/***/ "./lib/core/Axios.js":
/*!***************************!*\
!*** ./lib/core/Axios.js ***!
\***************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./lib/helpers/buildURL.js");
var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./lib/core/InterceptorManager.js");
var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./lib/core/dispatchRequest.js");
var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./lib/core/mergeConfig.js");
var buildFullPath = __webpack_require__(/*! ./buildFullPath */ "./lib/core/buildFullPath.js");
var validator = __webpack_require__(/*! ../helpers/validator */ "./lib/helpers/validator.js");
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
var fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function (url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url: url,
data: data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
module.exports = Axios;
/***/
}),
/***/ "./lib/core/AxiosError.js":
/*!********************************!*\
!*** ./lib/core/AxiosError.js ***!
\********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED'
// eslint-disable-next-line func-names
].forEach(function (code) {
descriptors[code] = { value: code };
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', { value: true });
// eslint-disable-next-line func-names
AxiosError.from = function (error, code, config, request, response, customProps) {
var axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
module.exports = AxiosError;
/***/
}),
/***/ "./lib/core/InterceptorManager.js":
/*!****************************************!*\
!*** ./lib/core/InterceptorManager.js ***!
\****************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/
}),
/***/ "./lib/core/buildFullPath.js":
/*!***********************************!*\
!*** ./lib/core/buildFullPath.js ***!
\***********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./lib/helpers/isAbsoluteURL.js");
var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./lib/helpers/combineURLs.js");
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/
}),
/***/ "./lib/core/dispatchRequest.js":
/*!*************************************!*\
!*** ./lib/core/dispatchRequest.js ***!
\*************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
var transformData = __webpack_require__(/*! ./transformData */ "./lib/core/transformData.js");
var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./lib/cancel/isCancel.js");
var defaults = __webpack_require__(/*! ../defaults */ "./lib/defaults/index.js");
var CanceledError = __webpack_require__(/*! ../cancel/CanceledError */ "./lib/cancel/CanceledError.js");
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/
}),
/***/ "./lib/core/mergeConfig.js":
/*!*********************************!*\
!*** ./lib/core/mergeConfig.js ***!
\*********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(prop) {
if (prop in config2) {
return getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
return getMergedValue(undefined, config1[prop]);
}
}
var mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
'baseURL': defaultToConfig2,
'transformRequest': defaultToConfig2,
'transformResponse': defaultToConfig2,
'paramsSerializer': defaultToConfig2,
'timeout': defaultToConfig2,
'timeoutMessage': defaultToConfig2,
'withCredentials': defaultToConfig2,
'adapter': defaultToConfig2,
'responseType': defaultToConfig2,
'xsrfCookieName': defaultToConfig2,
'xsrfHeaderName': defaultToConfig2,
'onUploadProgress': defaultToConfig2,
'onDownloadProgress': defaultToConfig2,
'decompress': defaultToConfig2,
'maxContentLength': defaultToConfig2,
'maxBodyLength': defaultToConfig2,
'beforeRedirect': defaultToConfig2,
'transport': defaultToConfig2,
'httpAgent': defaultToConfig2,
'httpsAgent': defaultToConfig2,
'cancelToken': defaultToConfig2,
'socketPath': defaultToConfig2,
'responseEncoding': defaultToConfig2,
'validateStatus': mergeDirectKeys
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
/***/
}),
/***/ "./lib/core/settle.js":
/*!****************************!*\
!*** ./lib/core/settle.js ***!
\****************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var AxiosError = __webpack_require__(/*! ./AxiosError */ "./lib/core/AxiosError.js");
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
response.request,
response
));
}
};
/***/
}),
/***/ "./lib/core/transformData.js":
/*!***********************************!*\
!*** ./lib/core/transformData.js ***!
\***********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
var defaults = __webpack_require__(/*! ../defaults */ "./lib/defaults/index.js");
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers);
});
return data;
};
/***/
}),
/***/ "./lib/defaults/index.js":
/*!*******************************!*\
!*** ./lib/defaults/index.js ***!
\*******************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
var normalizeHeaderName = __webpack_require__(/*! ../helpers/normalizeHeaderName */ "./lib/helpers/normalizeHeaderName.js");
var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
var transitionalDefaults = __webpack_require__(/*! ./transitional */ "./lib/defaults/transitional.js");
var toFormData = __webpack_require__(/*! ../helpers/toFormData */ "./lib/helpers/toFormData.js");
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(/*! ../adapters/xhr */ "./lib/adapters/xhr.js");
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(/*! ../adapters/http */ "./lib/adapters/xhr.js");
}
return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: transitionalDefaults,
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
var isObjectPayload = utils.isObject(data);
var contentType = headers && headers['Content-Type'];
var isFileList;
if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {
var _FormData = this.env && this.env.FormData;
return toFormData(isFileList ? { 'files[]': data } : data, _FormData && new _FormData());
} else if (isObjectPayload || contentType === 'application/json') {
setContentTypeIfUnset(headers, 'application/json');
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: __webpack_require__(/*! ./env/FormData */ "./lib/helpers/null.js")
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
}
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/***/
}),
/***/ "./lib/defaults/transitional.js":
/*!**************************************!*\
!*** ./lib/defaults/transitional.js ***!
\**************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
module.exports = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};
/***/
}),
/***/ "./lib/env/data.js":
/*!*************************!*\
!*** ./lib/env/data.js ***!
\*************************/
/*! no static exports found */
/***/ (function (module, exports) {
module.exports = {
"version": "0.27.2"
};
/***/
}),
/***/ "./lib/helpers/bind.js":
/*!*****************************!*\
!*** ./lib/helpers/bind.js ***!
\*****************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/
}),
/***/ "./lib/helpers/buildURL.js":
/*!*********************************!*\
!*** ./lib/helpers/buildURL.js ***!
\*********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/
}),
/***/ "./lib/helpers/combineURLs.js":
/*!************************************!*\
!*** ./lib/helpers/combineURLs.js ***!
\************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/
}),
/***/ "./lib/helpers/cookies.js":
/*!********************************!*\
!*** ./lib/helpers/cookies.js ***!
\********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() { },
read: function read() { return null; },
remove: function remove() { }
};
})()
);
/***/
}),
/***/ "./lib/helpers/isAbsoluteURL.js":
/*!**************************************!*\
!*** ./lib/helpers/isAbsoluteURL.js ***!
\**************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
/***/
}),
/***/ "./lib/helpers/isAxiosError.js":
/*!*************************************!*\
!*** ./lib/helpers/isAxiosError.js ***!
\*************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
/***/
}),
/***/ "./lib/helpers/isURLSameOrigin.js":
/*!****************************************!*\
!*** ./lib/helpers/isURLSameOrigin.js ***!
\****************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/
}),
/***/ "./lib/helpers/normalizeHeaderName.js":
/*!********************************************!*\
!*** ./lib/helpers/normalizeHeaderName.js ***!
\********************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/
}),
/***/ "./lib/helpers/null.js":
/*!*****************************!*\
!*** ./lib/helpers/null.js ***!
\*****************************/
/*! no static exports found */
/***/ (function (module, exports) {
// eslint-disable-next-line strict
module.exports = null;
/***/
}),
/***/ "./lib/helpers/parseHeaders.js":
/*!*************************************!*\
!*** ./lib/helpers/parseHeaders.js ***!
\*************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./lib/utils.js");
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/
}),
/***/ "./lib/helpers/parseProtocol.js":
/*!**************************************!*\
!*** ./lib/helpers/parseProtocol.js ***!
\**************************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
module.exports = function parseProtocol(url) {
var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
};
/***/
}),
/***/ "./lib/helpers/spread.js":
/*!*******************************!*\
!*** ./lib/helpers/spread.js ***!
\*******************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/
}),
/***/ "./lib/helpers/toFormData.js":
/*!***********************************!*\
!*** ./lib/helpers/toFormData.js ***!
\***********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./lib/utils.js");
/**
* Convert a data object to FormData
* @param {Object} obj
* @param {?Object} [formData]
* @returns {Object}
**/
function toFormData(obj, formData) {
// eslint-disable-next-line no-param-reassign
formData = formData || new FormData();
var stack = [];
function convertValue(value) {
if (value === null) return '';
if (utils.isDate(value)) {
return value.toISOString();
}
if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
}
return value;
}
function build(data, parentKey) {
if (utils.isPlainObject(data) || utils.isArray(data)) {
if (stack.indexOf(data) !== -1) {
throw Error('Circular reference detected in ' + parentKey);
}
stack.push(data);
utils.forEach(data, function each(value, key) {
if (utils.isUndefined(value)) return;
var fullKey = parentKey ? parentKey + '.' + key : key;
var arr;
if (value && !parentKey && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
value = JSON.stringify(value);
} else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
// eslint-disable-next-line func-names
arr.forEach(function (el) {
!utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
});
return;
}
}
build(value, fullKey);
});
stack.pop();
} else {
formData.append(parentKey, convertValue(data));
}
}
build(obj);
return formData;
}
module.exports = toFormData;
/***/
}),
/***/ "./lib/helpers/validator.js":
/*!**********************************!*\
!*** ./lib/helpers/validator.js ***!
\**********************************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var VERSION = __webpack_require__(/*! ../env/data */ "./lib/env/data.js").version;
var AxiosError = __webpack_require__(/*! ../core/AxiosError */ "./lib/core/AxiosError.js");
var validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
/**
* Transitional option validator
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function (value, opt, opts) {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
module.exports = {
assertOptions: assertOptions,
validators: validators
};
/***/
}),
/***/ "./lib/utils.js":
/*!**********************!*\
!*** ./lib/utils.js ***!
\**********************/
/*! no static exports found */
/***/ (function (module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(/*! ./helpers/bind */ "./lib/helpers/bind.js");
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
// eslint-disable-next-line func-names
var kindOf = (function (cache) {
// eslint-disable-next-line func-names
return function (thing) {
var str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
};
})(Object.create(null));
function kindOfTest(type) {
type = type.toLowerCase();
return function isKindOf(thing) {
return kindOf(thing) === type;
};
}
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return Array.isArray(val);
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
var isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (kindOf(val) !== 'object') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
var isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
var isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
var isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
var isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a FormData
*
* @param {Object} thing The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(thing) {
var pattern = '[object FormData]';
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) ||
toString.call(thing) === pattern ||
(isFunction(thing.toString) && thing.toString() === pattern)
);
}
/**
* Determine if a value is a URLSearchParams object
* @function
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
var isURLSearchParams = kindOfTest('URLSearchParams');
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*/
function inherits(constructor, superConstructor, props, descriptors) {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
props && Object.assign(constructor.prototype, props);
}
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function} [filter]
* @returns {Object}
*/
function toFlatObject(sourceObj, destObj, filter) {
var props;
var i;
var prop;
var merged = {};
destObj = destObj || {};
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if (!merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = Object.getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
}
/*
* determines whether a string ends with the characters of a specified string
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
* @returns {boolean}
*/
function endsWith(str, searchString, position) {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
/**
* Returns new array from array like object
* @param {*} [thing]
* @returns {Array}
*/
function toArray(thing) {
if (!thing) return null;
var i = thing.length;
if (isUndefined(i)) return null;
var arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
}
// eslint-disable-next-line func-names
var isTypedArray = (function (TypedArray) {
// eslint-disable-next-line func-names
return function (thing) {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM,
inherits: inherits,
toFlatObject: toFlatObject,
kindOf: kindOf,
kindOfTest: kindOfTest,
endsWith: endsWith,
toArray: toArray,
isTypedArray: isTypedArray,
isFileList: isFileList
};
/***/
})
/******/
});
});
//Included:lib/002.vue-v2.6.14.part.js
/*lib:vue@2.6.14 + modifications*/
/*!
* Vue.js v2.6.14
* (c) 2014-2021 Evan You
* Released under the MIT License.
*/
(function (root, factory) {
const scope = (typeof window === 'object') ? window : undefined;
if(typeof scope === "undefined") return;
if("vue" in scope) return scope.vue;
const output = factory();
if(typeof module === 'object' && typeof module.exports === 'object')
module.exports = output;
if(typeof define === 'function' && define.amd)
define([], factory);
if(typeof exports === 'object')
exports["vue"] = output;
scope["vue"] = output;
scope["Vue"] = output;
})(this, function() {
var emptyObject = Object.freeze({});
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
function isUndef (v) {
return v === undefined || v === null
}
function isDef (v) {
return v !== undefined && v !== null
}
function isTrue (v) {
return v === true
}
function isFalse (v) {
return v === false
}
/**
* Check if value is primitive.
*/
function isPrimitive (value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Get the raw type string of a value, e.g., [object Object].
*/
var _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
var n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
function isPromise (val) {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
/**
* Convert a value to a string that is actually rendered.
*/
function toString (val) {
return val == null
? ''
: Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert an input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Check if an attribute is a reserved attribute.
*/
var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Remove an item from an array.
*/
function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether an object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cached(function (str) {
return str.replace(hyphenateRE, '-$1').toLowerCase()
});
/**
* Simple bind polyfill for environments that do not support it,
* e.g., PhantomJS 1.x. Technically, we don't need this anymore
* since native bind is now performant enough in most browsers.
* But removing it would mean breaking code that was able to run in
* PhantomJS 1.x, so this must be kept for backward compatibility.
*/
/* istanbul ignore next */
function polyfillBind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length;
return boundFn
}
function nativeBind (fn, ctx) {
return fn.bind(ctx)
}
var bind = Function.prototype.bind
? nativeBind
: polyfillBind;
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/* eslint-disable no-unused-vars */
/**
* Perform no operation.
* Stubbing args to make Flow happy without leaving useless transpiled code
* with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
*/
function noop (a, b, c) {}
/**
* Always return false.
*/
var no = function (a, b, c) { return false; };
/* eslint-enable no-unused-vars */
/**
* Return the same value.
*/
var identity = function (_) { return _; };
/**
* Generate a string containing static keys from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
if (a === b) { return true }
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
var isArrayA = Array.isArray(a);
var isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return a.length === b.length && a.every(function (e, i) {
return looseEqual(e, b[i])
})
} else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
} else if (!isArrayA && !isArrayB) {
var keysA = Object.keys(a);
var keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function (key) {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
/**
* Return the first index at which a loosely equal value can be
* found in the array (if value is a plain object, the array must
* contain an object of the same shape), or -1 if it is not present.
*/
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/**
* Ensure a function is called only once.
*/
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
var SSR_ATTR = 'data-server-rendered';
var ASSET_TYPES = [
'component',
'directive',
'filter'
];
var LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated',
'errorCaptured',
'serverPrefetch'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
// $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: "development" !== 'production',
/**
* Whether to enable devtools
*/
devtools: "development" !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Warn handler for watcher warns
*/
warnHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
// $flow-disable-line
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Perform updates asynchronously. Intended to be used by Vue Test Utils
* This will significantly reduce performance if set to false.
*/
async: true,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
/**
* unicode letters used for parsing html tags, component names and property paths.
* using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname
* skipping \u10000-\uEFFFF due to it freezing up PhantomJS
*/
var unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/;
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = new RegExp(("[^" + (unicodeRegExp.source) + ".$_\\d]"));
function parsePath (path) {
if (bailRE.test(path)) {
return
}
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
/* */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
var isPhantomJS = UA && /phantomjs/.test(UA);
var isFF = UA && UA.match(/firefox\/(\d+)/);
// Firefox has a "watch" function on Object.prototype...
var nativeWatch = ({}).watch;
var supportsPassive = false;
if (inBrowser) {
try {
var opts = {};
Object.defineProperty(opts, 'passive', ({
get: function get () {
/* istanbul ignore next */
supportsPassive = true;
}
})); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
}
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && !inWeex && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'] && global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
var hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
var _Set;
/* istanbul ignore if */ // $flow-disable-line
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = /*@__PURE__*/(function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* */
var warn = noop;
var tip = noop;
var generateComponentTrace = (noop); // work around flow check
var formatComponentName = (noop);
{
var hasConsole = typeof console !== 'undefined';
var classifyRE = /(?:^|[-_])(\w)/g;
var classify = function (str) { return str
.replace(classifyRE, function (c) { return c.toUpperCase(); })
.replace(/[-_]/g, ''); };
warn = function (msg, vm) {
var trace = vm ? generateComponentTrace(vm) : '';
if (config.warnHandler) {
config.warnHandler.call(null, msg, vm, trace);
} else if (hasConsole && (!config.silent)) {
console.error(("[Vue warn]: " + msg + trace));
}
};
tip = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.warn("[Vue tip]: " + msg + (
vm ? generateComponentTrace(vm) : ''
));
}
};
formatComponentName = function (vm, includeFile) {
if (vm.$root === vm) {
return '<Root>'
}
var options = typeof vm === 'function' && vm.cid != null
? vm.options
: vm._isVue
? vm.$options || vm.constructor.options
: vm;
var name = options.name || options._componentTag;
var file = options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? ("<" + (classify(name)) + ">") : "<Anonymous>") +
(file && includeFile !== false ? (" at " + file) : '')
)
};
var repeat = function (str, n) {
var res = '';
while (n) {
if (n % 2 === 1) { res += str; }
if (n > 1) { str += str; }
n >>= 1;
}
return res
};
generateComponentTrace = function (vm) {
if (vm._isVue && vm.$parent) {
var tree = [];
var currentRecursiveSequence = 0;
while (vm) {
if (tree.length > 0) {
var last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++;
vm = vm.$parent;
continue
} else if (currentRecursiveSequence > 0) {
tree[tree.length - 1] = [last, currentRecursiveSequence];
currentRecursiveSequence = 0;
}
}
tree.push(vm);
vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree
.map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm)
? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)")
: formatComponentName(vm))); })
.join('\n')
} else {
return ("\n\n(found in " + (formatComponentName(vm)) + ")")
}
};
}
/* */
var uid = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stabilize the subscriber list first
var subs = this.subs.slice();
if (!config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort(function (a, b) { return a.id - b.id; });
}
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
Dep.target = null;
var targetStack = [];
function pushTarget (target) {
targetStack.push(target);
Dep.target = target;
}
function popTarget () {
targetStack.pop();
Dep.target = targetStack[targetStack.length - 1];
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions,
asyncFactory
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.fnContext = undefined;
this.fnOptions = undefined;
this.fnScopeId = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
this.asyncFactory = asyncFactory;
this.asyncMeta = undefined;
this.isAsyncPlaceholder = false;
};
var prototypeAccessors = { child: { configurable: true } };
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
return this.componentInstance
};
Object.defineProperties( VNode.prototype, prototypeAccessors );
var createEmptyVNode = function (text) {
if ( text === void 0 ) text = '';
var node = new VNode();
node.text = text;
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
// #7975
// clone children array to avoid mutating original in case of cloning
// a child.
vnode.children && vnode.children.slice(),
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions,
vnode.asyncFactory
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.fnContext = vnode.fnContext;
cloned.fnOptions = vnode.fnOptions;
cloned.fnScopeId = vnode.fnScopeId;
cloned.asyncMeta = vnode.asyncMeta;
cloned.isCloned = true;
return cloned
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);
var methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
];
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* In some cases we may want to disable observation inside a component's
* update computation.
*/
var shouldObserve = true;
function toggleObserving (value) {
shouldObserve = value;
}
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods);
} else {
copyAugment(value, arrayMethods, arrayKeys);
}
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment a target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment a target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value) || value instanceof VNode) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter,
shallow
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
if ((!getter || setter) && arguments.length === 2) {
val = obj[key];
}
var childOb = !shallow && observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
if (Array.isArray(value)) {
dependArray(value);
}
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (customSetter) {
customSetter();
}
// #7981: for accessor properties without setter
if (getter && !setter) { return }
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = !shallow && observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
if (isUndef(target) || isPrimitive(target)
) {
warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target))));
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (target, key) {
if (isUndef(target) || isPrimitive(target)
) {
warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target))));
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1);
return
}
var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
{
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = hasSymbol
? Reflect.ownKeys(from)
: Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
// in case the object is already observed...
if (key === '__ob__') { continue }
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (
toVal !== fromVal &&
isPlainObject(toVal) &&
isPlainObject(fromVal)
) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
function mergeDataOrFn (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
typeof childVal === 'function' ? childVal.call(this, this) : childVal,
typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
)
}
} else {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm, vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm, vm)
: parentVal;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
return mergeDataOrFn(parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
var res = childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal;
return res
? dedupeHooks(res)
: res
}
function dedupeHooks (hooks) {
var res = [];
for (var i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res
}
LIFECYCLE_HOOKS.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (
parentVal,
childVal,
vm,
key
) {
var res = Object.create(parentVal || null);
if (childVal) {
assertObjectType(key, childVal, vm);
return extend(res, childVal)
} else {
return res
}
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (
parentVal,
childVal,
vm,
key
) {
// work around Firefox's Object.prototype.watch...
if (parentVal === nativeWatch) { parentVal = undefined; }
if (childVal === nativeWatch) { childVal = undefined; }
/* istanbul ignore if */
if (!childVal) { return Object.create(parentVal || null) }
{
assertObjectType(key, childVal, vm);
}
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key$1 in childVal) {
var parent = ret[key$1];
var child = childVal[key$1];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key$1] = parent
? parent.concat(child)
: Array.isArray(child) ? child : [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.inject =
strats.computed = function (
parentVal,
childVal,
vm,
key
) {
if (childVal && "development" !== 'production') {
assertObjectType(key, childVal, vm);
}
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
if (childVal) { extend(ret, childVal); }
return ret
};
strats.provide = mergeDataOrFn;
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
validateComponentName(key);
}
}
function validateComponentName (name) {
if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + (unicodeRegExp.source) + "]*$")).test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'should conform to valid custom element name in html5 specification.'
);
}
if (isBuiltInTag(name) || config.isReservedTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + name
);
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options, vm) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
} else {
warn(
"Invalid value for option \"props\": expected an Array or an Object, " +
"but got " + (toRawType(props)) + ".",
vm
);
}
options.props = res;
}
/**
* Normalize all injections into Object-based format
*/
function normalizeInject (options, vm) {
var inject = options.inject;
if (!inject) { return }
var normalized = options.inject = {};
if (Array.isArray(inject)) {
for (var i = 0; i < inject.length; i++) {
normalized[inject[i]] = { from: inject[i] };
}
} else if (isPlainObject(inject)) {
for (var key in inject) {
var val = inject[key];
normalized[key] = isPlainObject(val)
? extend({ from: key }, val)
: { from: val };
}
} else {
warn(
"Invalid value for option \"inject\": expected an Array or an Object, " +
"but got " + (toRawType(inject)) + ".",
vm
);
}
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def$$1 = dirs[key];
if (typeof def$$1 === 'function') {
dirs[key] = { bind: def$$1, update: def$$1 };
}
}
}
}
function assertObjectType (name, value, vm) {
if (!isPlainObject(value)) {
warn(
"Invalid value for option \"" + name + "\": expected an Object, " +
"but got " + (toRawType(value)) + ".",
vm
);
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
{
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child, vm);
normalizeInject(child, vm);
normalizeDirectives(child);
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!child._base) {
if (child.extends) {
parent = mergeOptions(parent, child.extends, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm);
}
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if (warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// boolean casting
var booleanIndex = getTypeIndex(Boolean, prop.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
// only cast empty string / same name to boolean if
// boolean has higher priority
var stringIndex = getTypeIndex(String, prop.type);
if (stringIndex < 0 || booleanIndex < stringIndex) {
value = true;
}
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldObserve = shouldObserve;
toggleObserving(true);
observe(value);
toggleObserving(prevShouldObserve);
}
{
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined
) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i], vm);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
var haveExpectedTypes = expectedTypes.some(function (t) { return t; });
if (!valid && haveExpectedTypes) {
warn(
getInvalidTypeMessage(name, value, expectedTypes),
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol|BigInt)$/;
function assertType (value, type, vm) {
var valid;
var expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
var t = typeof value;
valid = t === expectedType.toLowerCase();
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
try {
valid = value instanceof type;
} catch (e) {
warn('Invalid prop type: "' + String(type) + '" is not a constructor', vm);
valid = false;
}
}
return {
valid: valid,
expectedType: expectedType
}
}
var functionTypeCheckRE = /^\s*function (\w+)/;
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(functionTypeCheckRE);
return match ? match[1] : ''
}
function isSameType (a, b) {
return getType(a) === getType(b)
}
function getTypeIndex (type, expectedTypes) {
if (!Array.isArray(expectedTypes)) {
return isSameType(expectedTypes, type) ? 0 : -1
}
for (var i = 0, len = expectedTypes.length; i < len; i++) {
if (isSameType(expectedTypes[i], type)) {
return i
}
}
return -1
}
function getInvalidTypeMessage (name, value, expectedTypes) {
var message = "Invalid prop: type check failed for prop \"" + name + "\"." +
" Expected " + (expectedTypes.map(capitalize).join(', '));
var expectedType = expectedTypes[0];
var receivedType = toRawType(value);
// check if we need to specify expected value
if (
expectedTypes.length === 1 &&
isExplicable(expectedType) &&
isExplicable(typeof value) &&
!isBoolean(expectedType, receivedType)
) {
message += " with value " + (styleValue(value, expectedType));
}
message += ", got " + receivedType + " ";
// check if we need to specify received value
if (isExplicable(receivedType)) {
message += "with value " + (styleValue(value, receivedType)) + ".";
}
return message
}
function styleValue (value, type) {
if (type === 'String') {
return ("\"" + value + "\"")
} else if (type === 'Number') {
return ("" + (Number(value)))
} else {
return ("" + value)
}
}
var EXPLICABLE_TYPES = ['string', 'number', 'boolean'];
function isExplicable (value) {
return EXPLICABLE_TYPES.some(function (elem) { return value.toLowerCase() === elem; })
}
function isBoolean () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; })
}
/* */
function handleError (err, vm, info) {
// Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
// See: https://github.com/vuejs/vuex/issues/1505
pushTarget();
try {
if (vm) {
var cur = vm;
while ((cur = cur.$parent)) {
var hooks = cur.$options.errorCaptured;
if (hooks) {
for (var i = 0; i < hooks.length; i++) {
try {
var capture = hooks[i].call(cur, err, vm, info) === false;
if (capture) { return }
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook');
}
}
}
}
}
globalHandleError(err, vm, info);
} finally {
popTarget();
}
}
function invokeWithErrorHandling (
handler,
context,
args,
vm,
info
) {
var res;
try {
res = args ? handler.apply(context, args) : handler.call(context);
if (res && !res._isVue && isPromise(res) && !res._handled) {
res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); });
// issue #9511
// avoid catch triggering multiple times when nested calls
res._handled = true;
}
} catch (e) {
handleError(e, vm, info);
}
return res
}
function globalHandleError (err, vm, info) {
if (config.errorHandler) {
try {
return config.errorHandler.call(null, err, vm, info)
} catch (e) {
// if the user intentionally throws the original error in the handler,
// do not log it twice
if (e !== err) {
logError(e, null, 'config.errorHandler');
}
}
}
logError(err, vm, info);
}
function logError (err, vm, info) {
{
warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm);
}
/* istanbul ignore else */
if ((inBrowser || inWeex) && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
/* */
var isUsingMicroTask = false;
var callbacks = [];
var pending = false;
function flushCallbacks () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
var timerFunc;
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
timerFunc = function () {
p.then(flushCallbacks);
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
isUsingMicroTask = true;
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
var counter = 1;
var observer = new MutationObserver(flushCallbacks);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
isUsingMicroTask = true;
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = function () {
setImmediate(flushCallbacks);
};
} else {
// Fallback to setTimeout.
timerFunc = function () {
setTimeout(flushCallbacks, 0);
};
}
function nextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
timerFunc();
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
/* */
var mark;
var measure;
{
var perf = inBrowser && window.performance;
/* istanbul ignore if */
if (
perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures
) {
mark = function (tag) { return perf.mark(tag); };
measure = function (name, startTag, endTag) {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
// perf.clearMeasures(name)
};
}
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
{
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
'referenced during render. Make sure that this property is reactive, ' +
'either in the data option, or for class-based components, by ' +
'initializing the property. ' +
'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
target
);
};
var warnReservedPrefix = function (target, key) {
warn(
"Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " +
'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
'prevent conflicts with Vue internals. ' +
'See: https://vuejs.org/v2/api/#data',
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' && isNative(Proxy);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) ||
(typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));
if (!has && !isAllowed) {
if (key in target.$data) { warnReservedPrefix(target, key); }
else { warnNonPresent(target, key); }
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
if (key in target.$data) { warnReservedPrefix(target, key); }
else { warnNonPresent(target, key); }
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var seenObjects = new _Set();
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
function traverse (val) {
_traverse(val, seenObjects);
seenObjects.clear();
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/* */
var normalizeEvent = cached(function (name) {
var passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
name = once$$1 ? name.slice(1) : name;
var capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name: name,
once: once$$1,
capture: capture,
passive: passive
}
});
function createFnInvoker (fns, vm) {
function invoker () {
var arguments$1 = arguments;
var fns = invoker.fns;
if (Array.isArray(fns)) {
var cloned = fns.slice();
for (var i = 0; i < cloned.length; i++) {
invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler");
}
} else {
// return handler return value for single handlers
return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler")
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
createOnceHandler,
vm
) {
var name, def$$1, cur, old, event;
for (name in on) {
def$$1 = cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur, vm);
}
if (isTrue(event.once)) {
cur = on[name] = createOnceHandler(event.name, cur, event.capture);
}
add(event.name, cur, event.capture, event.passive, event.params);
} else if (cur !== old) {
old.fns = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name], event.capture);
}
}
}
/* */
function mergeVNodeHook (def, hookKey, hook) {
if (def instanceof VNode) {
def = def.data.hook || (def.data.hook = {});
}
var invoker;
var oldHook = def[hookKey];
function wrappedHook () {
hook.apply(this, arguments);
// important: remove merged hook to ensure it's called only once
// and prevent memory leak
remove(invoker.fns, wrappedHook);
}
if (isUndef(oldHook)) {
// no existing hook
invoker = createFnInvoker([wrappedHook]);
} else {
/* istanbul ignore if */
if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {
// already a merged invoker
invoker = oldHook;
invoker.fns.push(wrappedHook);
} else {
// existing plain hook
invoker = createFnInvoker([oldHook, wrappedHook]);
}
}
invoker.merged = true;
def[hookKey] = invoker;
}
/* */
function extractPropsFromVNodeData (
data,
Ctor,
tag
) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (isUndef(propOptions)) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
if (isDef(attrs) || isDef(props)) {
for (var key in propOptions) {
var altKey = hyphenate(key);
{
var keyInLowerCase = key.toLowerCase();
if (
key !== keyInLowerCase &&
attrs && hasOwn(attrs, keyInLowerCase)
) {
tip(
"Prop \"" + keyInLowerCase + "\" is passed to component " +
(formatComponentName(tag || Ctor)) + ", but the declared prop name is" +
" \"" + key + "\". " +
"Note that HTML attributes are case-insensitive and camelCased " +
"props need to use their kebab-case equivalents when using in-DOM " +
"templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"."
);
}
}
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (isDef(hash)) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function isTextNode (node) {
return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, lastIndex, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') { continue }
lastIndex = res.length - 1;
last = res[lastIndex];
// nested
if (Array.isArray(c)) {
if (c.length > 0) {
c = normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i));
// merge adjacent text nodes
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]).text);
c.shift();
}
res.push.apply(res, c);
}
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function initProvide (vm) {
var provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
function initInjections (vm) {
var result = resolveInject(vm.$options.inject, vm);
if (result) {
toggleObserving(false);
Object.keys(result).forEach(function (key) {
/* istanbul ignore else */
{
defineReactive$$1(vm, key, result[key], function () {
warn(
"Avoid mutating an injected value directly since the changes will be " +
"overwritten whenever the provided component re-renders. " +
"injection being mutated: \"" + key + "\"",
vm
);
});
}
});
toggleObserving(true);
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
var result = Object.create(null);
var keys = hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
// #6574 in case the inject object is observed...
if (key === '__ob__') { continue }
var provideKey = inject[key].from;
var source = vm;
while (source) {
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
if (!source) {
if ('default' in inject[key]) {
var provideDefault = inject[key].default;
result[key] = typeof provideDefault === 'function'
? provideDefault.call(vm)
: provideDefault;
} else {
warn(("Injection \"" + key + "\" not found"), vm);
}
}
}
return result
}
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
if (!children || !children.length) {
return {}
}
var slots = {};
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
var data = child.data;
// remove slot attribute if the node is resolved as a Vue slot node
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot;
}
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
var name = data.slot;
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children || []);
} else {
slot.push(child);
}
} else {
(slots.default || (slots.default = [])).push(child);
}
}
// ignore slots that contains only whitespace
for (var name$1 in slots) {
if (slots[name$1].every(isWhitespace)) {
delete slots[name$1];
}
}
return slots
}
function isWhitespace (node) {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
/* */
function isAsyncPlaceholder (node) {
return node.isComment && node.asyncFactory
}
/* */
function normalizeScopedSlots (
slots,
normalSlots,
prevSlots
) {
var res;
var hasNormalSlots = Object.keys(normalSlots).length > 0;
var isStable = slots ? !!slots.$stable : !hasNormalSlots;
var key = slots && slots.$key;
if (!slots) {
res = {};
} else if (slots._normalized) {
// fast path 1: child component re-render only, parent did not change
return slots._normalized
} else if (
isStable &&
prevSlots &&
prevSlots !== emptyObject &&
key === prevSlots.$key &&
!hasNormalSlots &&
!prevSlots.$hasNormal
) {
// fast path 2: stable scoped slots w/ no normal slots to proxy,
// only need to normalize once
return prevSlots
} else {
res = {};
for (var key$1 in slots) {
if (slots[key$1] && key$1[0] !== '$') {
res[key$1] = normalizeScopedSlot(normalSlots, key$1, slots[key$1]);
}
}
}
// expose normal slots on scopedSlots
for (var key$2 in normalSlots) {
if (!(key$2 in res)) {
res[key$2] = proxyNormalSlot(normalSlots, key$2);
}
}
// avoriaz seems to mock a non-extensible $scopedSlots object
// and when that is passed down this would cause an error
if (slots && Object.isExtensible(slots)) {
(slots)._normalized = res;
}
def(res, '$stable', isStable);
def(res, '$key', key);
def(res, '$hasNormal', hasNormalSlots);
return res
}
function normalizeScopedSlot(normalSlots, key, fn) {
var normalized = function () {
var res = arguments.length ? fn.apply(null, arguments) : fn({});
res = res && typeof res === 'object' && !Array.isArray(res)
? [res] // single vnode
: normalizeChildren(res);
var vnode = res && res[0];
return res && (
!vnode ||
(res.length === 1 && vnode.isComment && !isAsyncPlaceholder(vnode)) // #9658, #10391
) ? undefined
: res
};
// this is a slot using the new v-slot syntax without scope. although it is
// compiled as a scoped slot, render fn users would expect it to be present
// on this.$slots because the usage is semantically a normal slot.
if (fn.proxy) {
Object.defineProperty(normalSlots, key, {
get: normalized,
enumerable: true,
configurable: true
});
}
return normalized
}
function proxyNormalSlot(slots, key) {
return function () { return slots[key]; }
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
if (hasSymbol && val[Symbol.iterator]) {
ret = [];
var iterator = val[Symbol.iterator]();
var result = iterator.next();
while (!result.done) {
ret.push(render(result.value, ret.length));
result = iterator.next();
}
} else {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
}
if (!isDef(ret)) {
ret = [];
}
(ret)._isVList = true;
return ret
}
/* */
/**
* Runtime helper for rendering <slot>
*/
function renderSlot (
name,
fallbackRender,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
var nodes;
if (scopedSlotFn) {
// scoped slot
props = props || {};
if (bindObject) {
if (!isObject(bindObject)) {
warn('slot v-bind without argument expects an Object', this);
}
props = extend(extend({}, bindObject), props);
}
nodes =
scopedSlotFn(props) ||
(typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);
} else {
nodes =
this.$slots[name] ||
(typeof fallbackRender === 'function' ? fallbackRender() : fallbackRender);
}
var target = props && props.slot;
if (target) {
return this.$createElement('template', { slot: target }, nodes)
} else {
return nodes
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
function isKeyNotMatch (expect, actual) {
if (Array.isArray(expect)) {
return expect.indexOf(actual) === -1
} else {
return expect !== actual
}
}
/**
* Runtime helper for checking keyCodes from config.
* exposed as Vue.prototype._k
* passing in eventKeyName as last argument separately for backwards compat
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInKeyCode,
eventKeyName,
builtInKeyName
) {
var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
return isKeyNotMatch(builtInKeyName, eventKeyName)
} else if (mappedKeyCode) {
return isKeyNotMatch(mappedKeyCode, eventKeyCode)
} else if (eventKeyName) {
return hyphenate(eventKeyName) !== key
}
return eventKeyCode === undefined
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp,
isSync
) {
if (value) {
if (!isObject(value)) {
warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
var hash;
var loop = function ( key ) {
if (
key === 'class' ||
key === 'style' ||
isReservedAttribute(key)
) {
hash = data;
} else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
var camelizedKey = camelize(key);
var hyphenatedKey = hyphenate(key);
if (!(camelizedKey in hash) && !(hyphenatedKey in hash)) {
hash[key] = value[key];
if (isSync) {
var on = data.on || (data.on = {});
on[("update:" + key)] = function ($event) {
value[key] = $event;
};
}
}
};
for (var key in value) loop( key );
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
var cached = this._staticTrees || (this._staticTrees = []);
var tree = cached[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree.
if (tree && !isInFor) {
return tree
}
// otherwise, render a fresh tree.
tree = cached[index] = this.$options.staticRenderFns[index].call(
this._renderProxy,
null,
this // for render fns generated for functional component templates
);
markStatic(tree, ("__static__" + index), false);
return tree
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
}
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* */
function bindObjectListeners (data, value) {
if (value) {
if (!isPlainObject(value)) {
warn(
'v-on without argument expects an Object value',
this
);
} else {
var on = data.on = data.on ? extend({}, data.on) : {};
for (var key in value) {
var existing = on[key];
var ours = value[key];
on[key] = existing ? [].concat(existing, ours) : ours;
}
}
}
return data
}
/* */
function resolveScopedSlots (
fns, // see flow/vnode
res,
// the following are added in 2.6
hasDynamicKeys,
contentHashKey
) {
res = res || { $stable: !hasDynamicKeys };
for (var i = 0; i < fns.length; i++) {
var slot = fns[i];
if (Array.isArray(slot)) {
resolveScopedSlots(slot, res, hasDynamicKeys);
} else if (slot) {
// marker for reverse proxying v-slot without scope on this.$slots
if (slot.proxy) {
slot.fn.proxy = true;
}
res[slot.key] = slot.fn;
}
}
if (contentHashKey) {
(res).$key = contentHashKey;
}
return res
}
/* */
function bindDynamicKeys (baseObj, values) {
for (var i = 0; i < values.length; i += 2) {
var key = values[i];
if (typeof key === 'string' && key) {
baseObj[values[i]] = values[i + 1];
} else if (key !== '' && key !== null) {
// null is a special value for explicitly removing a binding
warn(
("Invalid value for dynamic directive argument (expected string or null): " + key),
this
);
}
}
return baseObj
}
// helper to dynamically append modifier runtime markers to event names.
// ensure only append when value is already string, otherwise it will be cast
// to string and cause the type check to miss.
function prependModifier (value, symbol) {
return typeof value === 'string' ? symbol + value : value
}
/* */
function installRenderHelpers (target) {
target._o = markOnce;
target._n = toNumber;
target._s = toString;
target._l = renderList;
target._t = renderSlot;
target._q = looseEqual;
target._i = looseIndexOf;
target._m = renderStatic;
target._f = resolveFilter;
target._k = checkKeyCodes;
target._b = bindObjectProps;
target._v = createTextVNode;
target._e = createEmptyVNode;
target._u = resolveScopedSlots;
target._g = bindObjectListeners;
target._d = bindDynamicKeys;
target._p = prependModifier;
}
/* */
function FunctionalRenderContext (
data,
props,
children,
parent,
Ctor
) {
var this$1 = this;
var options = Ctor.options;
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var contextVm;
if (hasOwn(parent, '_uid')) {
contextVm = Object.create(parent);
// $flow-disable-line
contextVm._original = parent;
} else {
// the context vm passed in is a functional context as well.
// in this case we want to make sure we are able to get a hold to the
// real context instance.
contextVm = parent;
// $flow-disable-line
parent = parent._original;
}
var isCompiled = isTrue(options._compiled);
var needNormalization = !isCompiled;
this.data = data;
this.props = props;
this.children = children;
this.parent = parent;
this.listeners = data.on || emptyObject;
this.injections = resolveInject(options.inject, parent);
this.slots = function () {
if (!this$1.$slots) {
normalizeScopedSlots(
data.scopedSlots,
this$1.$slots = resolveSlots(children, parent)
);
}
return this$1.$slots
};
Object.defineProperty(this, 'scopedSlots', ({
enumerable: true,
get: function get () {
return normalizeScopedSlots(data.scopedSlots, this.slots())
}
}));
// support for compiled functional template
if (isCompiled) {
// exposing $options for renderStatic()
this.$options = options;
// pre-resolve slots for renderSlot()
this.$slots = this.slots();
this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);
}
if (options._scopeId) {
this._c = function (a, b, c, d) {
var vnode = createElement(contextVm, a, b, c, d, needNormalization);
if (vnode && !Array.isArray(vnode)) {
vnode.fnScopeId = options._scopeId;
vnode.fnContext = parent;
}
return vnode
};
} else {
this._c = function (a, b, c, d) { return createElement(contextVm, a, b, c, d, needNormalization); };
}
}
installRenderHelpers(FunctionalRenderContext.prototype);
function createFunctionalComponent (
Ctor,
propsData,
data,
contextVm,
children
) {
var options = Ctor.options;
var props = {};
var propOptions = options.props;
if (isDef(propOptions)) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || emptyObject);
}
} else {
if (isDef(data.attrs)) { mergeProps(props, data.attrs); }
if (isDef(data.props)) { mergeProps(props, data.props); }
}
var renderContext = new FunctionalRenderContext(
data,
props,
children,
contextVm,
Ctor
);
var vnode = options.render.call(null, renderContext._c, renderContext);
if (vnode instanceof VNode) {
return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)
} else if (Array.isArray(vnode)) {
var vnodes = normalizeChildren(vnode) || [];
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
}
return res
}
}
function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {
// #7817 clone node before setting fnContext, otherwise if the node is reused
// (e.g. it was from a cached normal slot) the fnContext causes named slots
// that should not be matched to match.
var clone = cloneVNode(vnode);
clone.fnContext = contextVm;
clone.fnOptions = options;
{
(clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;
}
if (data.slot) {
(clone.data || (clone.data = {})).slot = data.slot;
}
return clone
}
function mergeProps (to, from) {
for (var key in from) {
to[camelize(key)] = from[key];
}
}
/* */
/* */
/* */
/* */
// inline hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function init (vnode, hydrating) {
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
} else {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
}
},
prepatch: function prepatch (oldVnode, vnode) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
},
insert: function insert (vnode) {
var context = vnode.context;
var componentInstance = vnode.componentInstance;
if (!componentInstance._isMounted) {
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
// vue-router#1212
// During updates, a kept-alive component's child components may
// change, so directly walking the tree here may call activated hooks
// on incorrect children. Instead we push them into a queue which will
// be processed after the whole patch process ended.
queueActivatedComponent(componentInstance);
} else {
activateChildComponent(componentInstance, true /* direct */);
}
}
},
destroy: function destroy (vnode) {
var componentInstance = vnode.componentInstance;
if (!componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
var hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
var baseCtor = context.$options._base;
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
{
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
var asyncFactory;
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor;
Ctor = resolveAsyncComponent(asyncFactory, baseCtor);
if (Ctor === undefined) {
// return a placeholder node for async component, which is rendered
// as a comment node but preserves all the raw information for the node.
// the information will be used for async server-rendering and hydration.
return createAsyncPlaceholder(
asyncFactory,
data,
context,
children,
tag
)
}
}
data = data || {};
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
// extract props
var propsData = extractPropsFromVNodeData(data, Ctor, tag);
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
// so it gets processed during parent component patch.
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners & slot
// work around flow
var slot = data.slot;
data = {};
if (slot) {
data.slot = slot;
}
}
// install component management hooks onto the placeholder node
installComponentHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children },
asyncFactory
);
return vnode
}
function createComponentInstanceForVnode (
// we know it's MountedComponentVNode but flow doesn't
vnode,
// activeInstance in lifecycle state
parent
) {
var options = {
_isComponent: true,
_parentVnode: vnode,
parent: parent
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnode.componentOptions.Ctor(options)
}
function installComponentHooks (data) {
var hooks = data.hook || (data.hook = {});
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var existing = hooks[key];
var toMerge = componentVNodeHooks[key];
if (existing !== toMerge && !(existing && existing._merged)) {
hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;
}
}
}
function mergeHook$1 (f1, f2) {
var merged = function (a, b) {
// flow complains about extra args which is why we use any
f1(a, b);
f2(a, b);
};
merged._merged = true;
return merged
}
// transform component v-model info (value and callback) into
// prop and event handler respectively.
function transformModel (options, data) {
var prop = (options.model && options.model.prop) || 'value';
var event = (options.model && options.model.event) || 'input'
;(data.attrs || (data.attrs = {}))[prop] = data.model.value;
var on = data.on || (data.on = {});
var existing = on[event];
var callback = data.model.callback;
if (isDef(existing)) {
if (
Array.isArray(existing)
? existing.indexOf(callback) === -1
: existing !== callback
) {
on[event] = [callback].concat(existing);
}
} else {
on[event] = callback;
}
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (isDef(data) && isDef((data).__ob__)) {
warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is;
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
if (isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
{
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
);
}
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
if (isDef(data) && isDef(data.nativeOn) && data.tag !== 'component') {
warn(
("The .native modifier for v-on is only valid on components but it was used on <" + tag + ">."),
context
);
}
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
if (isDef(ns)) { applyNS(vnode, ns); }
if (isDef(data)) { registerDeepBindings(data); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns, force) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
ns = undefined;
force = true;
}
if (isDef(vnode.children)) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (isDef(child.tag) && (
isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
applyNS(child, ns, force);
}
}
}
}
// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
function registerDeepBindings (data) {
if (isObject(data.style)) {
traverse(data.style);
}
if (isObject(data.class)) {
traverse(data.class);
}
}
/* */
function initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null; // v-once cached trees
var options = vm.$options;
var parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
// $attrs & $listeners are exposed for easier HOC creation.
// they need to be reactive so that HOCs using them are always updated
var parentData = parentVnode && parentVnode.data;
/* istanbul ignore else */
{
defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, function () {
!isUpdatingChildComponent && warn("$attrs is readonly.", vm);
}, true);
defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, function () {
!isUpdatingChildComponent && warn("$listeners is readonly.", vm);
}, true);
}
}
var currentRenderingInstance = null;
function renderMixin (Vue) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype);
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var _parentVnode = ref._parentVnode;
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
);
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm;
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, "render");
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);
} catch (e) {
handleError(e, vm, "renderError");
vnode = vm._vnode;
}
} else {
vnode = vm._vnode;
}
} finally {
currentRenderingInstance = null;
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0];
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
}
/* */
function ensureCtor (comp, base) {
if (
comp.__esModule ||
(hasSymbol && comp[Symbol.toStringTag] === 'Module')
) {
comp = comp.default;
}
return isObject(comp)
? base.extend(comp)
: comp
}
function createAsyncPlaceholder (
factory,
data,
context,
children,
tag
) {
var node = createEmptyVNode();
node.asyncFactory = factory;
node.asyncMeta = { data: data, context: context, children: children, tag: tag };
return node
}
function resolveAsyncComponent (
factory,
baseCtor
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
var owner = currentRenderingInstance;
if (owner && isDef(factory.owners) && factory.owners.indexOf(owner) === -1) {
// already pending
factory.owners.push(owner);
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (owner && !isDef(factory.owners)) {
var owners = factory.owners = [owner];
var sync = true;
var timerLoading = null;
var timerTimeout = null
;(owner).$on('hook:destroyed', function () { return remove(owners, owner); });
var forceRender = function (renderCompleted) {
for (var i = 0, l = owners.length; i < l; i++) {
(owners[i]).$forceUpdate();
}
if (renderCompleted) {
owners.length = 0;
if (timerLoading !== null) {
clearTimeout(timerLoading);
timerLoading = null;
}
if (timerTimeout !== null) {
clearTimeout(timerTimeout);
timerTimeout = null;
}
}
};
var resolve = once(function (res) {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor);
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender(true);
} else {
owners.length = 0;
}
});
var reject = once(function (reason) {
warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender(true);
}
});
var res = factory(resolve, reject);
if (isObject(res)) {
if (isPromise(res)) {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isPromise(res.component)) {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
timerLoading = setTimeout(function () {
timerLoading = null;
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender(false);
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
timerTimeout = setTimeout(function () {
timerTimeout = null;
if (isUndef(factory.resolved)) {
reject(
"timeout (" + (res.timeout) + "ms)"
);
}
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
function getFirstComponentChild (children) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
return c
}
}
}
}
/* */
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add (event, fn) {
target.$on(event, fn);
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function createOnceHandler (event, fn) {
var _target = target;
return function onceHandler () {
var res = fn.apply(null, arguments);
if (res !== null) {
_target.$off(event, onceHandler);
}
}
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);
target = undefined;
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var vm = this;
if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// array of events
if (Array.isArray(event)) {
for (var i$1 = 0, l = event.length; i$1 < l; i$1++) {
vm.$off(event[i$1], fn);
}
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (!fn) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
{
var lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
"Event \"" + lowerCaseEvent + "\" is emitted in component " +
(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
"Note that HTML attributes are case-insensitive and you cannot use " +
"v-on to listen to camelCase events when using in-DOM templates. " +
"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
);
}
}
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
var info = "event handler for \"" + event + "\"";
for (var i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info);
}
}
return vm
};
}
/* */
var activeInstance = null;
var isUpdatingChildComponent = false;
function setActiveInstance(vm) {
var prevActiveInstance = activeInstance;
activeInstance = vm;
return function () {
activeInstance = prevActiveInstance;
}
}
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = null;
vm._directInactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var restoreActiveInstance = setActiveInstance(vm);
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
restoreActiveInstance();
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
// fire destroyed hook
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// release circular reference (#6759)
if (vm.$vnode) {
vm.$vnode.parent = null;
}
};
}
function mountComponent (
vm,
el,
hydrating
) {
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
{
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
var updateComponent;
/* istanbul ignore if */
if (config.performance && mark) {
updateComponent = function () {
var name = vm._name;
var id = vm._uid;
var startTag = "vue-perf-start:" + id;
var endTag = "vue-perf-end:" + id;
mark(startTag);
var vnode = vm._render();
mark(endTag);
measure(("vue " + name + " render"), startTag, endTag);
mark(startTag);
vm._update(vnode, hydrating);
mark(endTag);
measure(("vue " + name + " patch"), startTag, endTag);
};
} else {
updateComponent = function () {
vm._update(vm._render(), hydrating);
};
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, {
before: function before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate');
}
}
}, true /* isRenderWatcher */);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
}
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
{
isUpdatingChildComponent = true;
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren.
// check if there are dynamic scopedSlots (hand-written or compiled but with
// dynamic slot names). Static scoped slots compiled from template has the
// "$stable" marker.
var newScopedSlots = parentVnode.data.scopedSlots;
var oldScopedSlots = vm.$scopedSlots;
var hasDynamicScopedSlot = !!(
(newScopedSlots && !newScopedSlots.$stable) ||
(oldScopedSlots !== emptyObject && !oldScopedSlots.$stable) ||
(newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key) ||
(!newScopedSlots && vm.$scopedSlots.$key)
);
// Any static slot children from the parent may have changed during parent's
// update. Dynamic scoped slots may also have changed. In such cases, a forced
// update is necessary to ensure correctness.
var needsForceUpdate = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
hasDynamicScopedSlot
);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update $attrs and $listeners hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data.attrs || emptyObject;
vm.$listeners = listeners || emptyObject;
// update props
if (propsData && vm.$options.props) {
toggleObserving(false);
var props = vm._props;
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
var propOptions = vm.$options.props; // wtf flow?
props[key] = validateProp(key, propOptions, propsData, vm);
}
toggleObserving(true);
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
listeners = listeners || emptyObject;
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
// resolve slots + force update if has children
if (needsForceUpdate) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
{
isUpdatingChildComponent = false;
}
}
function isInInactiveTree (vm) {
while (vm && (vm = vm.$parent)) {
if (vm._inactive) { return true }
}
return false
}
function activateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = false;
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false;
for (var i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i]);
}
callHook(vm, 'activated');
}
}
function deactivateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = true;
if (isInInactiveTree(vm)) {
return
}
}
if (!vm._inactive) {
vm._inactive = true;
for (var i = 0; i < vm.$children.length; i++) {
deactivateChildComponent(vm.$children[i]);
}
callHook(vm, 'deactivated');
}
}
function callHook (vm, hook) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
var handlers = vm.$options[hook];
var info = hook + " hook";
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
popTarget();
}
/* */
var MAX_UPDATE_COUNT = 100;
var queue = [];
var activatedChildren = [];
var has = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0;
has = {};
{
circular = {};
}
waiting = flushing = false;
}
// Async edge case #6566 requires saving the timestamp when event listeners are
// attached. However, calling performance.now() has a perf overhead especially
// if the page has thousands of event listeners. Instead, we take a timestamp
// every time the scheduler flushes and use that for all event listeners
// attached during that flush.
var currentFlushTimestamp = 0;
// Async edge case fix requires storing an event listener's attach timestamp.
var getNow = Date.now;
// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res (relative to page load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
// All IE versions use low-res event timestamps, and have problematic clock
// implementations (#9632)
if (inBrowser && !isIE) {
var performance = window.performance;
if (
performance &&
typeof performance.now === 'function' &&
getNow() > document.createEvent('Event').timeStamp
) {
// if the event timestamp, although evaluated AFTER the Date.now(), is
// smaller than it, it means the event is using a hi-res timestamp,
// and we need to use the hi-res version for event listener timestamps as
// well.
getNow = function () { return performance.now(); };
}
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
currentFlushTimestamp = getNow();
flushing = true;
var watcher, id;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
if (watcher.before) {
watcher.before();
}
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (has[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// keep copies of post queues before resetting state
var activatedQueue = activatedChildren.slice();
var updatedQueue = queue.slice();
resetSchedulerState();
// call component updated and activated hooks
callActivatedHooks(activatedQueue);
callUpdatedHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdatedHooks (queue) {
var i = queue.length;
while (i--) {
var watcher = queue[i];
var vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'updated');
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
*/
function queueActivatedComponent (vm) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
vm._inactive = false;
activatedChildren.push(vm);
}
function callActivatedHooks (queue) {
for (var i = 0; i < queue.length; i++) {
queue[i]._inactive = true;
activateChildComponent(queue[i], true /* true */);
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i > index && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
if (!config.async) {
flushSchedulerQueue();
return
}
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options,
isRenderWatcher
) {
this.vm = vm;
if (isRenderWatcher) {
vm._watcher = this;
}
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
this.before = options.before;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = expOrFn.toString();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = noop;
warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value;
var vm = this.vm;
try {
value = this.getter.call(vm, vm);
} catch (e) {
if (this.user) {
handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
}
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var i = this.deps.length;
while (i--) {
var dep = this.deps[i];
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
var info = "callback for watcher \"" + (this.expression) + "\"";
invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info);
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var i = this.deps.length;
while (i--) {
this.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this.deps[i].removeSub(this);
}
this.active = false;
}
};
/* */
var sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function proxy (target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
};
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val;
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch);
}
}
function initProps (vm, propsOptions) {
var propsData = vm.$options.propsData || {};
var props = vm._props = {};
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
var keys = vm.$options._propKeys = [];
var isRoot = !vm.$parent;
// root instance props should be converted
if (!isRoot) {
toggleObserving(false);
}
var loop = function ( key ) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
{
var hyphenatedKey = hyphenate(key);
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(props, key, value, function () {
if (!isRoot && !isUpdatingChildComponent) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, "_props", key);
}
};
for (var key in propsOptions) loop( key );
toggleObserving(true);
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var methods = vm.$options.methods;
var i = keys.length;
while (i--) {
var key = keys[i];
{
if (methods && hasOwn(methods, key)) {
warn(
("Method \"" + key + "\" has already been defined as a data property."),
vm
);
}
}
if (props && hasOwn(props, key)) {
warn(
"The data property \"" + key + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else if (!isReserved(key)) {
proxy(vm, "_data", key);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
// #7573 disable dep collection when invoking data getters
pushTarget();
try {
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, "data()");
return {}
} finally {
popTarget();
}
}
var computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
// $flow-disable-line
var watchers = vm._computedWatchers = Object.create(null);
// computed properties are just getters during SSR
var isSSR = isServerRendering();
for (var key in computed) {
var userDef = computed[key];
var getter = typeof userDef === 'function' ? userDef : userDef.get;
if (getter == null) {
warn(
("Getter is missing for computed property \"" + key + "\"."),
vm
);
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
);
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef);
} else {
if (key in vm.$data) {
warn(("The computed property \"" + key + "\" is already defined in data."), vm);
} else if (vm.$options.props && key in vm.$options.props) {
warn(("The computed property \"" + key + "\" is already defined as a prop."), vm);
} else if (vm.$options.methods && key in vm.$options.methods) {
warn(("The computed property \"" + key + "\" is already defined as a method."), vm);
}
}
}
}
function defineComputed (
target,
key,
userDef
) {
var shouldCache = !isServerRendering();
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop;
sharedPropertyDefinition.set = userDef.set || noop;
}
if (sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
("Computed property \"" + key + "\" was assigned to but it has no setter."),
this
);
};
}
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter (key) {
return function computedGetter () {
var watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter () {
return fn.call(this, this)
}
}
function initMethods (vm, methods) {
var props = vm.$options.props;
for (var key in methods) {
{
if (typeof methods[key] !== 'function') {
warn(
"Method \"" + key + "\" has type \"" + (typeof methods[key]) + "\" in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
if (props && hasOwn(props, key)) {
warn(
("Method \"" + key + "\" has already been defined as a prop."),
vm
);
}
if ((key in vm) && isReserved(key)) {
warn(
"Method \"" + key + "\" conflicts with an existing Vue instance method. " +
"Avoid defining component methods that start with _ or $."
);
}
}
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (
vm,
expOrFn,
handler,
options
) {
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
return vm.$watch(expOrFn, handler, options)
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () { return this._data };
var propsDef = {};
propsDef.get = function () { return this._props };
{
dataDef.set = function () {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
propsDef.set = function () {
warn("$props is readonly.", this);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Object.defineProperty(Vue.prototype, '$props', propsDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
var info = "callback for immediate watcher \"" + (watcher.expression) + "\"";
pushTarget();
invokeWithErrorHandling(cb, vm, [watcher.value], vm, info);
popTarget();
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
var uid$3 = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid$3++;
var startTag, endTag;
/* istanbul ignore if */
if (config.performance && mark) {
startTag = "vue-perf-start:" + (vm._uid);
endTag = "vue-perf-end:" + (vm._uid);
mark(startTag);
}
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
{
initProxy(vm);
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created');
/* istanbul ignore if */
if (config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(("vue " + (vm._name) + " init"), startTag, endTag);
}
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
var parentVnode = options._parentVnode;
opts.parent = options.parent;
opts._parentVnode = parentVnode;
var vnodeComponentOptions = parentVnode.componentOptions;
opts.propsData = vnodeComponentOptions.propsData;
opts._parentListeners = vnodeComponentOptions.listeners;
opts._renderChildren = vnodeComponentOptions.children;
opts._componentTag = vnodeComponentOptions.tag;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = resolveConstructorOptions(Ctor.super);
var cachedSuperOptions = Ctor.superOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
var modifiedOptions = resolveModifiedOptions(Ctor);
// update base extend options
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions);
}
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function resolveModifiedOptions (Ctor) {
var modified;
var latest = Ctor.options;
var sealed = Ctor.sealedOptions;
for (var key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) { modified = {}; }
modified[key] = latest[key];
}
}
return modified
}
function Vue (options) {
if (!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue);
stateMixin(Vue);
eventsMixin(Vue);
lifecycleMixin(Vue);
renderMixin(Vue);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
return this
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
if (name) {
validateComponentName(name);
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
function initProps$1 (Comp) {
var props = Comp.options.props;
for (var key in props) {
proxy(Comp.prototype, "_props", key);
}
}
function initComputed$1 (Comp) {
var computed = Comp.options.computed;
for (var key in computed) {
defineComputed(Comp.prototype, key, computed[key]);
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (type === 'component') {
validateComponentName(id);
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (Array.isArray(pattern)) {
return pattern.indexOf(name) > -1
} else if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
function pruneCache (keepAliveInstance, filter) {
var cache = keepAliveInstance.cache;
var keys = keepAliveInstance.keys;
var _vnode = keepAliveInstance._vnode;
for (var key in cache) {
var entry = cache[key];
if (entry) {
var name = entry.name;
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode);
}
}
}
}
function pruneCacheEntry (
cache,
key,
keys,
current
) {
var entry = cache[key];
if (entry && (!current || entry.tag !== current.tag)) {
entry.componentInstance.$destroy();
}
cache[key] = null;
remove(keys, key);
}
var patternTypes = [String, RegExp, Array];
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
methods: {
cacheVNode: function cacheVNode() {
var ref = this;
var cache = ref.cache;
var keys = ref.keys;
var vnodeToCache = ref.vnodeToCache;
var keyToCache = ref.keyToCache;
if (vnodeToCache) {
var tag = vnodeToCache.tag;
var componentInstance = vnodeToCache.componentInstance;
var componentOptions = vnodeToCache.componentOptions;
cache[keyToCache] = {
name: getComponentName(componentOptions),
tag: tag,
componentInstance: componentInstance,
};
keys.push(keyToCache);
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode);
}
this.vnodeToCache = null;
}
}
},
created: function created () {
this.cache = Object.create(null);
this.keys = [];
},
destroyed: function destroyed () {
for (var key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys);
}
},
mounted: function mounted () {
var this$1 = this;
this.cacheVNode();
this.$watch('include', function (val) {
pruneCache(this$1, function (name) { return matches(val, name); });
});
this.$watch('exclude', function (val) {
pruneCache(this$1, function (name) { return !matches(val, name); });
});
},
updated: function updated () {
this.cacheVNode();
},
render: function render () {
var slot = this.$slots.default;
var vnode = getFirstComponentChild(slot);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
var ref = this;
var include = ref.include;
var exclude = ref.exclude;
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
var ref$1 = this;
var cache = ref$1.cache;
var keys = ref$1.keys;
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
: vnode.key;
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance;
// make current key freshest
remove(keys, key);
keys.push(key);
} else {
// delay setting the cache until update
this.vnodeToCache = vnode;
this.keyToCache = key;
}
vnode.data.keepAlive = true;
}
return vnode || (slot && slot[0])
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
{
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
// exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn: warn,
extend: extend,
mergeOptions: mergeOptions,
defineReactive: defineReactive$$1
};
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
// 2.6 explicit observable API
Vue.observable = function (obj) {
observe(obj);
return obj
};
Vue.options = Object.create(null);
ASSET_TYPES.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue);
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
});
Object.defineProperty(Vue.prototype, '$ssrContext', {
get: function get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
});
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
});
Vue.version = '2.6.14';
/* */
// these are reserved for web because they are directly compiled away
// during template compilation
var isReservedAttr = makeMap('style,class');
// attributes that should be using props for binding
var acceptValue = makeMap('input,textarea,option,select,progress');
var mustUseProp = function (tag, type, attr) {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only');
var convertEnumeratedValue = function (key, value) {
return isFalsyAttrValue(value) || value === 'false'
? 'false'
// allow arbitrary string value for contenteditable
: key === 'contenteditable' && isValidContentEditableValue(value)
? value
: 'true'
};
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,' +
'truespeed,typemustmatch,visible'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (isDef(childNode.componentInstance)) {
childNode = childNode.componentInstance._vnode;
if (childNode && childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while (isDef(parentNode = parentNode.parent)) {
if (parentNode && parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return renderClass(data.staticClass, data.class)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: isDef(child.class)
? [child.class, parent.class]
: parent.class
}
}
function renderClass (
staticClass,
dynamicClass
) {
if (isDef(staticClass) || isDef(dynamicClass)) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
if (Array.isArray(value)) {
return stringifyArray(value)
}
if (isObject(value)) {
return stringifyObject(value)
}
if (typeof value === 'string') {
return value
}
/* istanbul ignore next */
return ''
}
function stringifyArray (value) {
var res = '';
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
if (res) { res += ' '; }
res += stringified;
}
}
return res
}
function stringifyObject (value) {
var res = '';
for (var key in value) {
if (value[key]) {
if (res) { res += ' '; }
res += key;
}
}
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template,blockquote,iframe,tfoot'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
'foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isPreTag = function (tag) { return tag === 'pre'; };
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
var isTextInputType = makeMap('text,number,password,search,email,tel,url');
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selected = document.querySelector(el);
if (!selected) {
warn(
'Cannot find element: ' + el
);
return document.createElement('div')
}
return selected
} else {
return el
}
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
// false or null will remove the attribute but undefined will not
if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setStyleScope (node, scopeId) {
node.setAttribute(scopeId, '');
}
var nodeOps = /*#__PURE__*/Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setStyleScope: setStyleScope
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!isDef(key)) { return }
var vm = vnode.context;
var ref = vnode.componentInstance || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (!Array.isArray(refs[key])) {
refs[key] = [ref];
} else if (refs[key].indexOf(ref) < 0) {
// $flow-disable-line
refs[key].push(ref);
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks = ['create', 'activate', 'update', 'remove', 'destroy'];
function sameVnode (a, b) {
return (
a.key === b.key &&
a.asyncFactory === b.asyncFactory && (
(
a.tag === b.tag &&
a.isComment === b.isComment &&
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b)
) || (
isTrue(a.isAsyncPlaceholder) &&
isUndef(b.asyncFactory.error)
)
)
)
}
function sameInputType (a, b) {
if (a.tag !== 'input') { return true }
var i;
var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;
var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeNode(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeNode (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
if (isDef(parent)) {
nodeOps.removeChild(parent, el);
}
}
function isUnknownElement$$1 (vnode, inVPre) {
return (
!inVPre &&
!vnode.ns &&
!(
config.ignoredElements.length &&
config.ignoredElements.some(function (ignore) {
return isRegExp(ignore)
? ignore.test(vnode.tag)
: ignore === vnode.tag
})
) &&
config.isUnknownElement(vnode.tag)
)
}
var creatingElmInVPre = 0;
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
if (isDef(vnode.elm) && isDef(ownerArray)) {
// This vnode was used in a previous render!
// now it's used as a new node, overwriting its elm would cause
// potential patch errors down the road when it's used as an insertion
// reference node. Instead, we clone the node on-demand before creating
// associated DOM element for it.
vnode = ownerArray[index] = cloneVNode(vnode);
}
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
var data = vnode.data;
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
{
if (data && data.pre) {
creatingElmInVPre++;
}
if (isUnknownElement$$1(vnode, creatingElmInVPre)) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if (data && data.pre) {
creatingElmInVPre--;
}
} else if (isTrue(vnode.isComment)) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue);
insert(parentElm, vnode.elm, refElm);
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (isDef(vnode.data.pendingInsert)) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
vnode.data.pendingInsert = null;
}
vnode.elm = vnode.componentInstance.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var innerNode = vnode;
while (innerNode.componentInstance) {
innerNode = innerNode.componentInstance._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref$$1) {
if (isDef(parent)) {
if (isDef(ref$$1)) {
if (nodeOps.parentNode(ref$$1) === parent) {
nodeOps.insertBefore(parent, elm, ref$$1);
}
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
{
checkDuplicateKeys(children);
}
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));
}
}
function isPatchable (vnode) {
while (vnode.componentInstance) {
vnode = vnode.componentInstance._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (isDef(i.create)) { i.create(emptyNode, vnode); }
if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); }
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
if (isDef(i = vnode.fnScopeId)) {
nodeOps.setStyleScope(vnode.elm, i);
} else {
var ancestor = vnode;
while (ancestor) {
if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setStyleScope(vnode.elm, i);
}
ancestor = ancestor.parent;
}
}
// for slot content they should also get the scopeId from the host instance.
if (isDef(i = activeInstance) &&
i !== vnode.context &&
i !== vnode.fnContext &&
isDef(i = i.$options._scopeId)
) {
nodeOps.setStyleScope(vnode.elm, i);
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
removeNode(ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
var i;
var listeners = cbs.remove.length + 1;
if (isDef(rm)) {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
} else {
// directly removing
rm = createRmCb(vnode.elm, listeners);
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeNode(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, vnodeToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
{
checkDuplicateKeys(newCh);
}
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx);
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
} else {
vnodeToMove = oldCh[idxInOld];
if (sameVnode(vnodeToMove, newStartVnode)) {
patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm);
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
}
}
newStartVnode = newCh[++newStartIdx];
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(oldCh, oldStartIdx, oldEndIdx);
}
}
function checkDuplicateKeys (children) {
var seenKeys = {};
for (var i = 0; i < children.length; i++) {
var vnode = children[i];
var key = vnode.key;
if (isDef(key)) {
if (seenKeys[key]) {
warn(
("Duplicate keys detected: '" + key + "'. This may cause an update error."),
vnode.context
);
} else {
seenKeys[key] = true;
}
}
}
}
function findIdxInOld (node, oldCh, start, end) {
for (var i = start; i < end; i++) {
var c = oldCh[i];
if (isDef(c) && sameVnode(node, c)) { return i }
}
}
function patchVnode (
oldVnode,
vnode,
insertedVnodeQueue,
ownerArray,
index,
removeOnly
) {
if (oldVnode === vnode) {
return
}
if (isDef(vnode.elm) && isDef(ownerArray)) {
// clone reused vnode
vnode = ownerArray[index] = cloneVNode(vnode);
}
var elm = vnode.elm = oldVnode.elm;
if (isTrue(oldVnode.isAsyncPlaceholder)) {
if (isDef(vnode.asyncFactory.resolved)) {
hydrate(oldVnode.elm, vnode, insertedVnodeQueue);
} else {
vnode.isAsyncPlaceholder = true;
}
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
) {
vnode.componentInstance = oldVnode.componentInstance;
return
}
var i;
var data = vnode.data;
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var oldCh = oldVnode.children;
var ch = vnode.children;
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
{
checkDuplicateKeys(ch);
}
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var hydrationBailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
// Note: style is excluded because it relies on initial clone for future
// deep updates (#7063).
var isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {
var i;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
inVPre = inVPre || (data && data.pre);
vnode.elm = elm;
if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {
vnode.isAsyncPlaceholder = true;
return true
}
// assert node match
{
if (!assertNodeMatch(elm, vnode, inVPre)) {
return false
}
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.componentInstance)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
// v-html and domProps: innerHTML
if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {
if (i !== elm.innerHTML) {
/* istanbul ignore if */
if (typeof console !== 'undefined' &&
!hydrationBailed
) {
hydrationBailed = true;
console.warn('Parent: ', elm);
console.warn('server innerHTML: ', i);
console.warn('client innerHTML: ', elm.innerHTML);
}
return false
}
} else {
// iterate and compare children lists
var childrenMatch = true;
var childNode = elm.firstChild;
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
/* istanbul ignore if */
if (typeof console !== 'undefined' &&
!hydrationBailed
) {
hydrationBailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
}
if (isDef(data)) {
var fullInvoke = false;
for (var key in data) {
if (!isRenderedModule(key)) {
fullInvoke = true;
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
if (!fullInvoke && data['class']) {
// ensure collecting deps for deep class bindings for future updates
traverse(data['class']);
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode, inVPre) {
if (isDef(vnode.tag)) {
return vnode.tag.indexOf('vue-component') === 0 || (
!isUnknownElement$$1(vnode, inVPre) &&
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); }
return
}
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR);
hydrating = true;
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
var oldElm = oldVnode.elm;
var parentElm = nodeOps.parentNode(oldElm);
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
);
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
var ancestor = vnode.parent;
var patchable = isPatchable(vnode);
while (ancestor) {
for (var i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor);
}
ancestor.elm = vnode.elm;
if (patchable) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, ancestor);
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
var insert = ancestor.data.hook.insert;
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (var i$2 = 1; i$2 < insert.fns.length; i$2++) {
insert.fns[i$2]();
}
}
} else {
registerRef(ancestor);
}
ancestor = ancestor.parent;
}
}
// destroy old node
if (isDef(parentElm)) {
removeVnodes([oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
var isCreate = oldVnode === emptyNode;
var isDestroy = vnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
dir.oldArg = oldDir.arg;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
for (var i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode, 'insert', callInsert);
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode, 'postpatch', function () {
for (var i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
});
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
// $flow-disable-line
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
// $flow-disable-line
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
// $flow-disable-line
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
var fn = dir.def && dir.def[hook];
if (fn) {
try {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
} catch (e) {
handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook"));
}
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
var opts = vnode.componentOptions;
if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) {
return
}
if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(attrs.__ob__)) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur, vnode.data.pre);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
// #6666: IE/Edge forces progress value down to 1 before setting a max
/* istanbul ignore if */
if ((isIE || isEdge) && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (isUndef(attrs[key])) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value, isInPre) {
if (isInPre || el.tagName.indexOf('-') > -1) {
baseSetAttr(el, key, value);
} else if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// technically allowfullscreen is a boolean attribute for <iframe>,
// but Flash expects a value of "true" when used on <embed> tag
value = key === 'allowfullscreen' && el.tagName === 'EMBED'
? 'true'
: key;
el.setAttribute(key, value);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, convertEnumeratedValue(key, value));
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
baseSetAttr(el, key, value);
}
}
function baseSetAttr (el, key, value) {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// #7138: IE10 & 11 fires input event when setting placeholder on
// <textarea>... block the first input event and remove the blocker
// immediately.
/* istanbul ignore if */
if (
isIE && !isIE9 &&
el.tagName === 'TEXTAREA' &&
key === 'placeholder' && value !== '' && !el.__ieph
) {
var blocker = function (e) {
e.stopImmediatePropagation();
el.removeEventListener('input', blocker);
};
el.addEventListener('input', blocker);
// $flow-disable-line
el.__ieph = true; /* IE placeholder patched */
}
el.setAttribute(key, value);
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (
isUndef(data.staticClass) &&
isUndef(data.class) && (
isUndef(oldData) || (
isUndef(oldData.staticClass) &&
isUndef(oldData.class)
)
)
) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (isDef(transitionClass)) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
var validDivisionCharRE = /[\w).+\-_$\]]/;
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
var j = i - 1;
var p = (void 0);
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') { break }
}
if (!p || !validDivisionCharRE.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + (args !== ')' ? ',' + args : args))
}
}
/* */
/* eslint-disable no-unused-vars */
function baseWarn (msg, range) {
console.error(("[Vue compiler]: " + msg));
}
/* eslint-enable no-unused-vars */
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value, range, dynamic) {
(el.props || (el.props = [])).push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range));
el.plain = false;
}
function addAttr (el, name, value, range, dynamic) {
var attrs = dynamic
? (el.dynamicAttrs || (el.dynamicAttrs = []))
: (el.attrs || (el.attrs = []));
attrs.push(rangeSetItem({ name: name, value: value, dynamic: dynamic }, range));
el.plain = false;
}
// add a raw attr (use this in preTransforms)
function addRawAttr (el, name, value, range) {
el.attrsMap[name] = value;
el.attrsList.push(rangeSetItem({ name: name, value: value }, range));
}
function addDirective (
el,
name,
rawName,
value,
arg,
isDynamicArg,
modifiers,
range
) {
(el.directives || (el.directives = [])).push(rangeSetItem({
name: name,
rawName: rawName,
value: value,
arg: arg,
isDynamicArg: isDynamicArg,
modifiers: modifiers
}, range));
el.plain = false;
}
function prependModifierMarker (symbol, name, dynamic) {
return dynamic
? ("_p(" + name + ",\"" + symbol + "\")")
: symbol + name // mark the event as captured
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn,
range,
dynamic
) {
modifiers = modifiers || emptyObject;
// warn prevent and passive modifier
/* istanbul ignore if */
if (
warn &&
modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.',
range
);
}
// normalize click.right and click.middle since they don't actually fire
// this is technically browser-specific, but at least for now browsers are
// the only target envs that have right/middle clicks.
if (modifiers.right) {
if (dynamic) {
name = "(" + name + ")==='click'?'contextmenu':(" + name + ")";
} else if (name === 'click') {
name = 'contextmenu';
delete modifiers.right;
}
} else if (modifiers.middle) {
if (dynamic) {
name = "(" + name + ")==='click'?'mouseup':(" + name + ")";
} else if (name === 'click') {
name = 'mouseup';
}
}
// check capture modifier
if (modifiers.capture) {
delete modifiers.capture;
name = prependModifierMarker('!', name, dynamic);
}
if (modifiers.once) {
delete modifiers.once;
name = prependModifierMarker('~', name, dynamic);
}
/* istanbul ignore if */
if (modifiers.passive) {
delete modifiers.passive;
name = prependModifierMarker('&', name, dynamic);
}
var events;
if (modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = rangeSetItem({ value: value.trim(), dynamic: dynamic }, range);
if (modifiers !== emptyObject) {
newHandler.modifiers = modifiers;
}
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
el.plain = false;
}
function getRawBindingAttr (
el,
name
) {
return el.rawAttrsMap[':' + name] ||
el.rawAttrsMap['v-bind:' + name] ||
el.rawAttrsMap[name]
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
// note: this only removes the attr from the Array (attrsList) so that it
// doesn't get processed by processAttrs.
// By default it does NOT remove it from the map (attrsMap) because the map is
// needed during codegen.
function getAndRemoveAttr (
el,
name,
removeFromMap
) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
if (removeFromMap) {
delete el.attrsMap[name];
}
return val
}
function getAndRemoveAttrByRegex (
el,
name
) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
var attr = list[i];
if (name.test(attr.name)) {
list.splice(i, 1);
return attr
}
}
}
function rangeSetItem (
item,
range
) {
if (range) {
if (range.start != null) {
item.start = range.start;
}
if (range.end != null) {
item.end = range.end;
}
}
return item
}
/* */
/**
* Cross-platform code generation for component v-model
*/
function genComponentModel (
el,
value,
modifiers
) {
var ref = modifiers || {};
var number = ref.number;
var trim = ref.trim;
var baseValueExpression = '$$v';
var valueExpression = baseValueExpression;
if (trim) {
valueExpression =
"(typeof " + baseValueExpression + " === 'string'" +
"? " + baseValueExpression + ".trim()" +
": " + baseValueExpression + ")";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var assignment = genAssignmentCode(value, valueExpression);
el.model = {
value: ("(" + value + ")"),
expression: JSON.stringify(value),
callback: ("function (" + baseValueExpression + ") {" + assignment + "}")
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
var res = parseModel(value);
if (res.key === null) {
return (value + "=" + assignment)
} else {
return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")")
}
}
/**
* Parse a v-model expression into a base path and a final key segment.
* Handles both dot-path and possible square brackets.
*
* Possible cases:
*
* - test
* - test[key]
* - test[test1[key]]
* - test["a"][key]
* - xxx.test[a[a].test1[key]]
* - test.xxx.a["asa"][test1[key]]
*
*/
var len, str, chr, index$1, expressionPos, expressionEndPos;
function parseModel (val) {
// Fix https://github.com/vuejs/vue/pull/7730
// allow v-model="obj.val " (trailing whitespace)
val = val.trim();
len = val.length;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
index$1 = val.lastIndexOf('.');
if (index$1 > -1) {
return {
exp: val.slice(0, index$1),
key: '"' + val.slice(index$1 + 1) + '"'
}
} else {
return {
exp: val,
key: null
}
}
}
str = val;
index$1 = expressionPos = expressionEndPos = 0;
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.slice(0, expressionPos),
key: val.slice(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var warn$1;
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
var RANGE_TOKEN = '__r';
var CHECKBOX_RADIO_TOKEN = '__c';
function model (
el,
dir,
_warn
) {
warn$1 = _warn;
var value = dir.value;
var modifiers = dir.modifiers;
var tag = el.tag;
var type = el.attrsMap.type;
{
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" +
"File inputs are read only. Use a v-on:change listener instead.",
el.rawAttrsMap['v-model']
);
}
}
if (el.component) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers);
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"v-model is not supported on this element type. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
el.rawAttrsMap['v-model']
);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?_i(" + value + "," + valueBinding + ")>-1" + (
trueValueBinding === 'true'
? (":(" + value + ")")
: (":_q(" + value + "," + trueValueBinding + ")")
)
);
addHandler(el, 'change',
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," +
'$$i=_i($$a,$$v);' +
"if($$el.checked){$$i<0&&(" + (genAssignmentCode(value, '$$a.concat([$$v])')) + ")}" +
"else{$$i>-1&&(" + (genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')) + ")}" +
"}else{" + (genAssignmentCode(value, '$$c')) + "}",
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding;
addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")"));
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true);
}
function genSelect (
el,
value,
modifiers
) {
var number = modifiers && modifiers.number;
var selectedVal = "Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){var val = \"_value\" in o ? o._value : o.value;" +
"return " + (number ? '_n(val)' : 'val') + "})";
var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';
var code = "var $$selectedVal = " + selectedVal + ";";
code = code + " " + (genAssignmentCode(value, assignment));
addHandler(el, 'change', code, null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
var type = el.attrsMap.type;
// warn if v-bind:value conflicts with v-model
// except for inputs with v-bind:type
{
var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value'];
var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (value$1 && !typeBinding) {
var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value';
warn$1(
binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " +
'because the latter already expands to a value binding internally',
el.rawAttrsMap[binding]
);
}
}
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var needCompositionGuard = !lazy && type !== 'range';
var event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input';
var valueExpression = '$event.target.value';
if (trim) {
valueExpression = "$event.target.value.trim()";
}
if (number) {
valueExpression = "_n(" + valueExpression + ")";
}
var code = genAssignmentCode(value, valueExpression);
if (needCompositionGuard) {
code = "if($event.target.composing)return;" + code;
}
addProp(el, 'value', ("(" + value + ")"));
addHandler(el, event, code, null, true);
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()');
}
}
/* */
// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
/* istanbul ignore if */
if (isDef(on[RANGE_TOKEN])) {
// IE input[type=range] only supports `change` event
var event = isIE ? 'change' : 'input';
on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);
delete on[RANGE_TOKEN];
}
// This was originally intended to fix #4521 but no longer necessary
// after 2.5. Keeping it for backwards compat with generated code from < 2.4
/* istanbul ignore if */
if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []);
delete on[CHECKBOX_RADIO_TOKEN];
}
}
var target$1;
function createOnceHandler$1 (event, handler, capture) {
var _target = target$1; // save current target element in closure
return function onceHandler () {
var res = handler.apply(null, arguments);
if (res !== null) {
remove$2(event, onceHandler, capture, _target);
}
}
}
// #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp
// implementation and does not fire microtasks in between event propagation, so
// safe to exclude.
var useMicrotaskFix = isUsingMicroTask && !(isFF && Number(isFF[1]) <= 53);
function add$1 (
name,
handler,
capture,
passive
) {
// async edge case #6566: inner click event triggers patch, event handler
// attached to outer element during patch, and triggered again. This
// happens because browsers fire microtask ticks between event propagation.
// the solution is simple: we save the timestamp when a handler is attached,
// and the handler would only fire if the event passed to it was fired
// AFTER it was attached.
if (useMicrotaskFix) {
var attachedTimestamp = currentFlushTimestamp;
var original = handler;
handler = original._wrapper = function (e) {
if (
// no bubbling, should always fire.
// this is just a safety net in case event.timeStamp is unreliable in
// certain weird environments...
e.target === e.currentTarget ||
// event is fired after handler attachment
e.timeStamp >= attachedTimestamp ||
// bail for environments that have buggy event.timeStamp implementations
// #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState
// #9681 QtWebEngine event.timeStamp is negative value
e.timeStamp <= 0 ||
// #9448 bail if event is fired in another document in a multi-page
// electron/nw.js app, since event.timeStamp will be using a different
// starting reference
e.target.ownerDocument !== document
) {
return original.apply(this, arguments)
}
};
}
target$1.addEventListener(
name,
handler,
supportsPassive
? { capture: capture, passive: passive }
: capture
);
}
function remove$2 (
name,
handler,
capture,
_target
) {
(_target || target$1).removeEventListener(
name,
handler._wrapper || handler,
capture
);
}
function updateDOMListeners (oldVnode, vnode) {
if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
normalizeEvents(on);
updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context);
target$1 = undefined;
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
var svgContainer;
function updateDOMProps (oldVnode, vnode) {
if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(props.__ob__)) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (!(key in props)) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) { vnode.children.length = 0; }
if (cur === oldProps[key]) { continue }
// #6601 work around Chrome version <= 55 bug where single textNode
// replaced by innerHTML/textContent retains its parentNode property
if (elm.childNodes.length === 1) {
elm.removeChild(elm.childNodes[0]);
}
}
if (key === 'value' && elm.tagName !== 'PROGRESS') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = isUndef(cur) ? '' : String(cur);
if (shouldUpdateValue(elm, strCur)) {
elm.value = strCur;
}
} else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) {
// IE doesn't support innerHTML for SVG elements
svgContainer = svgContainer || document.createElement('div');
svgContainer.innerHTML = "<svg>" + cur + "</svg>";
var svg = svgContainer.firstChild;
while (elm.firstChild) {
elm.removeChild(elm.firstChild);
}
while (svg.firstChild) {
elm.appendChild(svg.firstChild);
}
} else if (
// skip the update if old and new VDOM state is the same.
// `value` is handled separately because the DOM value may be temporarily
// out of sync with VDOM state due to focus, composition and modifiers.
// This #4521 by skipping the unnecessary `checked` update.
cur !== oldProps[key]
) {
// some property updates can throw
// e.g. `value` on <progress> w/ non-finite value
try {
elm[key] = cur;
} catch (e) {}
}
}
}
// check platforms/web/util/attrs.js acceptValue
function shouldUpdateValue (elm, checkVal) {
return (!elm.composing && (
elm.tagName === 'OPTION' ||
isNotInFocusAndDirty(elm, checkVal) ||
isDirtyWithModifiers(elm, checkVal)
))
}
function isNotInFocusAndDirty (elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is
// not equal to the updated value
var notInFocus = true;
// #6157
// work around IE bug when accessing document.activeElement in an iframe
try { notInFocus = document.activeElement !== elm; } catch (e) {}
return notInFocus && elm.value !== checkVal
}
function isDirtyWithModifiers (elm, newVal) {
var value = elm.value;
var modifiers = elm._vModifiers; // injected by v-model runtime
if (isDef(modifiers)) {
if (modifiers.number) {
return toNumber(value) !== toNumber(newVal)
}
if (modifiers.trim) {
return value.trim() !== newVal.trim()
}
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (
childNode && childNode.data &&
(styleData = normalizeStyleData(childNode.data))
) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
var cssVarRE = /^--/;
var importantRE = /\s*!important$/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important');
} else {
var normalizedName = normalize(name);
if (Array.isArray(val)) {
// Support values array created by autoprefixer, e.g.
// {display: ["-webkit-box", "-ms-flexbox", "flex"]}
// Set them one by one, and the browser will only set those it can recognize
for (var i = 0, len = val.length; i < len; i++) {
el.style[normalizedName] = val[i];
}
} else {
el.style[normalizedName] = val;
}
}
};
var vendorNames = ['Webkit', 'Moz', 'ms'];
var emptyStyle;
var normalize = cached(function (prop) {
emptyStyle = emptyStyle || document.createElement('div').style;
prop = camelize(prop);
if (prop !== 'filter' && (prop in emptyStyle)) {
return prop
}
var capName = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < vendorNames.length; i++) {
var name = vendorNames[i] + capName;
if (name in emptyStyle) {
return name
}
}
});
function updateStyle (oldVnode, vnode) {
var data = vnode.data;
var oldData = oldVnode.data;
if (isUndef(data.staticStyle) && isUndef(data.style) &&
isUndef(oldData.staticStyle) && isUndef(oldData.style)
) {
return
}
var cur, name;
var el = vnode.elm;
var oldStaticStyle = oldData.staticStyle;
var oldStyleBinding = oldData.normalizedStyle || oldData.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
var oldStyle = oldStaticStyle || oldStyleBinding;
var style = normalizeStyleBinding(vnode.data.style) || {};
// store normalized style under a different key for next diff
// make sure to clone it if it's reactive, since the user likely wants
// to mutate it.
vnode.data.normalizedStyle = isDef(style.__ob__)
? extend({}, style)
: style;
var newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (isUndef(newStyle[name])) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
var whitespaceRE = /\s+/;
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
if (!el.classList.length) {
el.removeAttribute('class');
}
} else {
var cur = " " + (el.getAttribute('class') || '') + " ";
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
cur = cur.trim();
if (cur) {
el.setAttribute('class', cur);
} else {
el.removeAttribute('class');
}
}
}
/* */
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
enterToClass: (name + "-enter-to"),
enterActiveClass: (name + "-enter-active"),
leaveClass: (name + "-leave"),
leaveToClass: (name + "-leave-to"),
leaveActiveClass: (name + "-leave-active")
}
});
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined
) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined
) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
// binding to window is necessary to make hot reload work in IE in strict mode
var raf = inBrowser
? window.requestAnimationFrame
? window.requestAnimationFrame.bind(window)
: setTimeout
: /* istanbul ignore next */ function (fn) { return fn(); };
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
var transitionClasses = el._transitionClasses || (el._transitionClasses = []);
if (transitionClasses.indexOf(cls) < 0) {
transitionClasses.push(cls);
addClass(el, cls);
}
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
// JSDOM may return undefined for transition properties
var transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', ');
var transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', ');
var transitionTimeout = getTimeout(transitionDelays, transitionDurations);
var animationDelays = (styles[animationProp + 'Delay'] || '').split(', ');
var animationDurations = (styles[animationProp + 'Duration'] || '').split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
// in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
// as a floor function) causing unexpected behaviors
function toMs (s) {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
var el = vnode.elm;
// call leave callback now
if (isDef(el._leaveCb)) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return
}
/* istanbul ignore if */
if (isDef(el._enterCb) || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterToClass = data.enterToClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearToClass = data.appearToClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
var duration = data.duration;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var context = activeInstance;
var transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
context = transitionNode.context;
transitionNode = transitionNode.parent;
}
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear && appearClass
? appearClass
: enterClass;
var activeClass = isAppear && appearActiveClass
? appearActiveClass
: enterActiveClass;
var toClass = isAppear && appearToClass
? appearToClass
: enterToClass;
var beforeEnterHook = isAppear
? (beforeAppear || beforeEnter)
: beforeEnter;
var enterHook = isAppear
? (typeof appear === 'function' ? appear : enter)
: enter;
var afterEnterHook = isAppear
? (afterAppear || afterEnter)
: afterEnter;
var enterCancelledHook = isAppear
? (appearCancelled || enterCancelled)
: enterCancelled;
var explicitEnterDuration = toNumber(
isObject(duration)
? duration.enter
: duration
);
if (explicitEnterDuration != null) {
checkDuration(explicitEnterDuration, 'enter', vnode);
}
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(enterHook);
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, toClass);
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode, 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb
) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
});
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
removeTransitionClass(el, startClass);
if (!cb.cancelled) {
addTransitionClass(el, toClass);
if (!userWantsControl) {
if (isValidDuration(explicitEnterDuration)) {
setTimeout(cb, explicitEnterDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (isDef(el._enterCb)) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (isUndef(data) || el.nodeType !== 1) {
return rm()
}
/* istanbul ignore if */
if (isDef(el._leaveCb)) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveToClass = data.leaveToClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var duration = data.duration;
var expectsCSS = css !== false && !isIE9;
var userWantsControl = getHookArgumentsLength(leave);
var explicitLeaveDuration = toNumber(
isObject(duration)
? duration.leave
: duration
);
if (isDef(explicitLeaveDuration)) {
checkDuration(explicitLeaveDuration, 'leave', vnode);
}
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show && el.parentNode) {
(el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
removeTransitionClass(el, leaveClass);
if (!cb.cancelled) {
addTransitionClass(el, leaveToClass);
if (!userWantsControl) {
if (isValidDuration(explicitLeaveDuration)) {
setTimeout(cb, explicitLeaveDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
// only used in dev mode
function checkDuration (val, name, vnode) {
if (typeof val !== 'number') {
warn(
"<transition> explicit " + name + " duration is not a valid number - " +
"got " + (JSON.stringify(val)) + ".",
vnode.context
);
} else if (isNaN(val)) {
warn(
"<transition> explicit " + name + " duration is NaN - " +
'the duration expression might be incorrect.',
vnode.context
);
}
}
function isValidDuration (val) {
return typeof val === 'number' && !isNaN(val)
}
/**
* Normalize a transition hook's argument length. The hook may be:
* - a merged hook (invoker) with the original in .fns
* - a wrapped component method (check ._length)
* - a plain function (.length)
*/
function getHookArgumentsLength (fn) {
if (isUndef(fn)) {
return false
}
var invokerFns = fn.fns;
if (isDef(invokerFns)) {
// invoker
return getHookArgumentsLength(
Array.isArray(invokerFns)
? invokerFns[0]
: invokerFns
)
} else {
return (fn._length || fn.length) > 1
}
}
function _enter (_, vnode) {
if (vnode.data.show !== true) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove: function remove$$1 (vnode, rm) {
/* istanbul ignore else */
if (vnode.data.show !== true) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var directive = {
inserted: function inserted (el, binding, vnode, oldVnode) {
if (vnode.tag === 'select') {
// #6903
if (oldVnode.elm && !oldVnode.elm._vOptions) {
mergeVNodeHook(vnode, 'postpatch', function () {
directive.componentUpdated(el, binding, vnode);
});
} else {
setSelected(el, binding, vnode.context);
}
el._vOptions = [].map.call(el.options, getValue);
} else if (vnode.tag === 'textarea' || isTextInputType(el.type)) {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd);
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var prevOptions = el._vOptions;
var curOptions = el._vOptions = [].map.call(el.options, getValue);
if (curOptions.some(function (o, i) { return !looseEqual(o, prevOptions[i]); })) {
// trigger change event if
// no matching option found for at least one value
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, curOptions); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions);
if (needReset) {
trigger(el, 'change');
}
}
}
}
};
function setSelected (el, binding, vm) {
actuallySetSelected(el, binding, vm);
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(function () {
actuallySetSelected(el, binding, vm);
}, 0);
}
}
function actuallySetSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
return options.every(function (o) { return !looseEqual(o, value); })
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
// prevent triggering an input event for no reason
if (!e.target.composing) { return }
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.componentInstance && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.componentInstance._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition$$1 = vnode.data && vnode.data.transition;
var originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition$$1) {
vnode.data.show = true;
enter(vnode, function () {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (!value === !oldValue) { return }
vnode = locateNode(vnode);
var transition$$1 = vnode.data && vnode.data.transition;
if (transition$$1) {
vnode.data.show = true;
if (value) {
enter(vnode, function () {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
},
unbind: function unbind (
el,
binding,
vnode,
oldVnode,
isDestroy
) {
if (!isDestroy) {
el.style.display = el.__vOriginalDisplay;
}
}
};
var platformDirectives = {
model: directive,
show: show
};
/* */
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String,
duration: [Number, String, Object]
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1];
}
return data
}
function placeholder (h, rawChild) {
if (/\d-keep-alive$/.test(rawChild.tag)) {
return h('keep-alive', {
props: rawChild.componentOptions.propsData
})
}
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
function isSameChild (child, oldChild) {
return oldChild.key === child.key && oldChild.tag === child.tag
}
var isNotTextNode = function (c) { return c.tag || isAsyncPlaceholder(c); };
var isVShowDirective = function (d) { return d.name === 'show'; };
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(isNotTextNode);
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if (mode && mode !== 'in-out' && mode !== 'out-in'
) {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
var id = "__transition-" + (this._uid) + "-";
child.key = child.key == null
? child.isComment
? id + 'comment'
: id + child.tag
: isPrimitive(child.key)
? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(isVShowDirective)) {
child.data.show = true;
}
if (
oldChild &&
oldChild.data &&
!isSameChild(child, oldChild) &&
!isAsyncPlaceholder(oldChild) &&
// #6687 component root is a comment node
!(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment)
) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild.data.transition = extend({}, data);
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
});
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
if (isAsyncPlaceholder(child)) {
return oldRawChild
}
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave);
mergeVNodeHook(data, 'enterCancelled', performLeave);
mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; });
}
}
return rawChild
}
};
/* */
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
beforeMount: function beforeMount () {
var this$1 = this;
var update = this._update;
this._update = function (vnode, hydrating) {
var restoreActiveInstance = setActiveInstance(this$1);
// force removing pass
this$1.__patch__(
this$1._vnode,
this$1.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this$1._vnode = this$1.kept;
restoreActiveInstance();
update.call(this$1, vnode, hydrating);
};
},
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else {
var opts = c.componentOptions;
var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
// assign to this to avoid being removed in tree-shaking
// $flow-disable-line
this._reflow = document.body.offsetHeight;
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (e && e.target !== el) {
return
}
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
/* istanbul ignore if */
if (this._hasMove) {
return this._hasMove
}
// Detect whether an element with the move class applied has
// CSS transitions. Since the element may be inside an entering
// transition at this very moment, we make a clone of it and remove
// all other transition classes applied to ensure only the move class
// is applied.
var clone = el.cloneNode();
if (el._transitionClasses) {
el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); });
}
addClass(clone, moveClass);
clone.style.display = 'none';
this.$el.appendChild(clone);
var info = getTransitionInfo(clone);
this.$el.removeChild(clone);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue.config.mustUseProp = mustUseProp;
Vue.config.isReservedTag = isReservedTag;
Vue.config.isReservedAttr = isReservedAttr;
Vue.config.getTagNamespace = getTagNamespace;
Vue.config.isUnknownElement = isUnknownElement;
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives);
extend(Vue.options.components, platformComponents);
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop;
// public mount method
Vue.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return mountComponent(this, el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
if (inBrowser) {
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue);
} else {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
if (config.productionTip !== false &&
typeof console !== 'undefined'
) {
console[console.info ? 'info' : 'log'](
"You are running Vue in development mode.\n" +
"Make sure to turn on production mode when deploying for production.\n" +
"See more tips at https://vuejs.org/guide/deployment.html"
);
}
}, 0);
}
/* */
var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var rawTokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index, tokenValue;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
rawTokens.push(tokenValue = text.slice(lastIndex, index));
tokens.push(JSON.stringify(tokenValue));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
rawTokens.push({ '@binding': exp });
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
rawTokens.push(tokenValue = text.slice(lastIndex));
tokens.push(JSON.stringify(tokenValue));
}
return {
expression: tokens.join('+'),
tokens: rawTokens
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if (staticClass) {
var res = parseText(staticClass, options.delimiters);
if (res) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.',
el.rawAttrsMap['class']
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData
};
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
{
var res = parseText(staticStyle, options.delimiters);
if (res) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.',
el.rawAttrsMap['style']
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$1 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:(" + (el.styleBinding) + "),";
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$1
};
/* */
var decoder;
var he = {
decode: function decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
};
/* */
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr'
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track'
);
/**
* Not type-checking this file because it's mostly vendor code.
*/
// Regular Expressions for parsing tags and attributes
var attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/;
var dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+?\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/;
var ncname = "[a-zA-Z_][\\-\\.0-9_a-zA-Z" + (unicodeRegExp.source) + "]*";
var qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")";
var startTagOpen = new RegExp(("^<" + qnameCapture));
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp(("^<\\/" + qnameCapture + "[^>]*>"));
var doctype = /^<!DOCTYPE [^>]+>/i;
// #7298: escape - to avoid being passed as HTML comment when inlined in page
var comment = /^<!\--/;
var conditionalComment = /^<!\[/;
// Special Elements (can contain anything)
var isPlainTextElement = makeMap('script,style,textarea', true);
var reCache = {};
var decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n',
'	': '\t',
''': "'"
};
var encodedAttr = /&(?:lt|gt|quot|amp|#39);/g;
var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g;
// #5992
var isIgnoreNewlineTag = makeMap('pre,textarea', true);
var shouldIgnoreFirstNewline = function (tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; };
function decodeAttr (value, shouldDecodeNewlines) {
var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;
return value.replace(re, function (match) { return decodingMap[match]; })
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3);
}
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) {
advance(1);
}
continue
}
}
var text = (void 0), rest = (void 0), next = (void 0);
if (textEnd >= 0) {
rest = html.slice(textEnd);
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest = html.slice(textEnd);
}
text = html.substring(0, textEnd);
}
if (textEnd < 0) {
text = html;
}
if (text) {
advance(text.length);
}
if (options.chars && text) {
options.chars(text, index - text.length, index);
}
} else {
var endTagLength = 0;
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var rest$1 = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1);
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest$1.length;
html = rest$1;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last) {
options.chars && options.chars(html);
if (!stack.length && options.warn) {
options.warn(("Mal-formatted tag at end of template: \"" + html + "\""), { start: index + html.length });
}
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {
attr.start = index;
advance(attr[0].length);
attr.end = index;
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag);
}
if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {
parseEndTag(tagName);
}
}
var unary = isUnaryTag$$1(tagName) || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
var value = args[3] || args[4] || args[5] || '';
var shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'
? options.shouldDecodeNewlinesForHref
: options.shouldDecodeNewlines;
attrs[i] = {
name: args[1],
value: decodeAttr(value, shouldDecodeNewlines)
};
if (options.outputSourceRange) {
attrs[i].start = args.start + args[0].match(/^\s*/).length;
attrs[i].end = args.end;
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end });
lastTag = tagName;
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tagName, start, end) {
var pos, lowerCasedTagName;
if (start == null) { start = index; }
if (end == null) { end = index; }
// Find the closest opened tag of the same type
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (i > pos || !tagName &&
options.warn
) {
options.warn(
("tag <" + (stack[i].tag) + "> has no matching end tag."),
{ start: stack[i].start, end: stack[i].end }
);
}
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
var onRE = /^@|^v-on:/;
var dirRE = /^v-|^@|^:|^#/;
var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
var stripParensRE = /^\(|\)$/g;
var dynamicArgRE = /^\[.*\]$/;
var argRE = /:(.*)$/;
var bindRE = /^:|^\.|^v-bind:/;
var modifierRE = /\.[^.\]]+(?=[^\]]*$)/g;
var slotRE = /^v-slot(:|$)|^#/;
var lineBreakRE = /[\r\n]/;
var whitespaceRE$1 = /[ \f\t\r\n]+/g;
var invalidAttributeRE = /[\s"'<>\/=]/;
var decodeHTMLCached = cached(he.decode);
var emptySlotScopeToken = "_empty_";
// configurable state
var warn$2;
var delimiters;
var transforms;
var preTransforms;
var postTransforms;
var platformIsPreTag;
var platformMustUseProp;
var platformGetTagNamespace;
var maybeComponent;
function createASTElement (
tag,
attrs,
parent
) {
return {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
rawAttrsMap: {},
parent: parent,
children: []
}
}
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$2 = options.warn || baseWarn;
platformIsPreTag = options.isPreTag || no;
platformMustUseProp = options.mustUseProp || no;
platformGetTagNamespace = options.getTagNamespace || no;
var isReservedTag = options.isReservedTag || no;
maybeComponent = function (el) { return !!(
el.component ||
el.attrsMap[':is'] ||
el.attrsMap['v-bind:is'] ||
!(el.attrsMap.is ? isReservedTag(el.attrsMap.is) : isReservedTag(el.tag))
); };
transforms = pluckModuleFunction(options.modules, 'transformNode');
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var whitespaceOption = options.whitespace;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
function warnOnce (msg, range) {
if (!warned) {
warned = true;
warn$2(msg, range);
}
}
function closeElement (element) {
trimEndingWhitespace(element);
if (!inVPre && !element.processed) {
element = processElement(element, options);
}
// tree management
if (!stack.length && element !== root) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
{
checkRootConstraints(element);
}
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else {
warnOnce(
"Component template should contain exactly one root element. " +
"If you are using v-if on multiple elements, " +
"use v-else-if to chain them instead.",
{ start: element.start }
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else {
if (element.slotScope) {
// scoped slot
// keep it in the children list so that v-else(-if) conditions can
// find it as the prev node.
var name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
}
currentParent.children.push(element);
element.parent = currentParent;
}
}
// final children cleanup
// filter out scoped slots
element.children = element.children.filter(function (c) { return !(c).slotScope; });
// remove trailing whitespace node again
trimEndingWhitespace(element);
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
// apply post-transforms
for (var i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options);
}
}
function trimEndingWhitespace (el) {
// remove trailing whitespace node
if (!inPre) {
var lastNode;
while (
(lastNode = el.children[el.children.length - 1]) &&
lastNode.type === 3 &&
lastNode.text === ' '
) {
el.children.pop();
}
}
}
function checkRootConstraints (el) {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes.',
{ start: el.start }
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.',
el.rawAttrsMap['v-for']
);
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,
shouldKeepComment: options.comments,
outputSourceRange: options.outputSourceRange,
start: function start (tag, attrs, unary, start$1, end) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = createASTElement(tag, attrs, currentParent);
if (ns) {
element.ns = ns;
}
{
if (options.outputSourceRange) {
element.start = start$1;
element.end = end;
element.rawAttrsMap = element.attrsList.reduce(function (cumulated, attr) {
cumulated[attr.name] = attr;
return cumulated
}, {});
}
attrs.forEach(function (attr) {
if (invalidAttributeRE.test(attr.name)) {
warn$2(
"Invalid dynamic argument expression: attribute names cannot contain " +
"spaces, quotes, <, >, / or =.",
{
start: attr.start + attr.name.indexOf("["),
end: attr.start + attr.name.length
}
);
}
});
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
warn$2(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">" + ', as they will not be parsed.',
{ start: element.start }
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
element = preTransforms[i](element, options) || element;
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else if (!element.processed) {
// structural directives
processFor(element);
processIf(element);
processOnce(element);
}
if (!root) {
root = element;
{
checkRootConstraints(root);
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
closeElement(element);
}
},
end: function end (tag, start, end$1) {
var element = stack[stack.length - 1];
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
if (options.outputSourceRange) {
element.end = end$1;
}
closeElement(element);
},
chars: function chars (text, start, end) {
if (!currentParent) {
{
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.',
{ start: start }
);
} else if ((text = text.trim())) {
warnOnce(
("text \"" + text + "\" outside root element will be ignored."),
{ start: start }
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
var children = currentParent.children;
if (inPre || text.trim()) {
text = isTextTag(currentParent) ? text : decodeHTMLCached(text);
} else if (!children.length) {
// remove the whitespace-only node right after an opening tag
text = '';
} else if (whitespaceOption) {
if (whitespaceOption === 'condense') {
// in condense mode, remove the whitespace node if it contains
// line break, otherwise condense to a single space
text = lineBreakRE.test(text) ? '' : ' ';
} else {
text = ' ';
}
} else {
text = preserveWhitespace ? ' ' : '';
}
if (text) {
if (!inPre && whitespaceOption === 'condense') {
// condense consecutive whitespaces into single space
text = text.replace(whitespaceRE$1, ' ');
}
var res;
var child;
if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) {
child = {
type: 2,
expression: res.expression,
tokens: res.tokens,
text: text
};
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
child = {
type: 3,
text: text
};
}
if (child) {
if (options.outputSourceRange) {
child.start = start;
child.end = end;
}
children.push(child);
}
}
},
comment: function comment (text, start, end) {
// adding anything as a sibling to the root node is forbidden
// comments should still be allowed, but ignored
if (currentParent) {
var child = {
type: 3,
text: text,
isComment: true
};
if (options.outputSourceRange) {
child.start = start;
child.end = end;
}
currentParent.children.push(child);
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var list = el.attrsList;
var len = list.length;
if (len) {
var attrs = el.attrs = new Array(len);
for (var i = 0; i < len; i++) {
attrs[i] = {
name: list[i].name,
value: JSON.stringify(list[i].value)
};
if (list[i].start != null) {
attrs[i].start = list[i].start;
attrs[i].end = list[i].end;
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processElement (
element,
options
) {
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = (
!element.key &&
!element.scopedSlots &&
!element.attrsList.length
);
processRef(element);
processSlotContent(element);
processSlotOutlet(element);
processComponent(element);
for (var i = 0; i < transforms.length; i++) {
element = transforms[i](element, options) || element;
}
processAttrs(element);
return element
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
{
if (el.tag === 'template') {
warn$2(
"<template> cannot be keyed. Place the key on real elements instead.",
getRawBindingAttr(el, 'key')
);
}
if (el.for) {
var iterator = el.iterator2 || el.iterator1;
var parent = el.parent;
if (iterator && iterator === exp && parent && parent.tag === 'transition-group') {
warn$2(
"Do not use v-for index as key on <transition-group> children, " +
"this is the same as not using keys.",
getRawBindingAttr(el, 'key'),
true /* tip */
);
}
}
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var res = parseFor(exp);
if (res) {
extend(el, res);
} else {
warn$2(
("Invalid v-for expression: " + exp),
el.rawAttrsMap['v-for']
);
}
}
}
function parseFor (exp) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) { return }
var res = {};
res.for = inMatch[2].trim();
var alias = inMatch[1].trim().replace(stripParensRE, '');
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
res.alias = alias.replace(forIteratorRE, '').trim();
res.iterator1 = iteratorMatch[1].trim();
if (iteratorMatch[2]) {
res.iterator2 = iteratorMatch[2].trim();
}
} else {
res.alias = alias;
}
return res
}
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else {
warn$2(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if.",
el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else']
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (children[i].text !== ' ') {
warn$2(
"text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " +
"will be ignored.",
children[i]
);
}
children.pop();
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
var once$$1 = getAndRemoveAttr(el, 'v-once');
if (once$$1 != null) {
el.once = true;
}
}
// handle content being passed to a component as slot,
// e.g. <template slot="xxx">, <div slot-scope="xxx">
function processSlotContent (el) {
var slotScope;
if (el.tag === 'template') {
slotScope = getAndRemoveAttr(el, 'scope');
/* istanbul ignore if */
if (slotScope) {
warn$2(
"the \"scope\" attribute for scoped slots have been deprecated and " +
"replaced by \"slot-scope\" since 2.5. The new \"slot-scope\" attribute " +
"can also be used on plain elements in addition to <template> to " +
"denote scoped slots.",
el.rawAttrsMap['scope'],
true
);
}
el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope');
} else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {
/* istanbul ignore if */
if (el.attrsMap['v-for']) {
warn$2(
"Ambiguous combined usage of slot-scope and v-for on <" + (el.tag) + "> " +
"(v-for takes higher priority). Use a wrapper <template> for the " +
"scoped slot to make it clearer.",
el.rawAttrsMap['slot-scope'],
true
);
}
el.slotScope = slotScope;
}
// slot="xxx"
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']);
// preserve slot as an attribute for native shadow DOM compat
// only for non-scoped slots.
if (el.tag !== 'template' && !el.slotScope) {
addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot'));
}
}
// 2.6 v-slot syntax
{
if (el.tag === 'template') {
// v-slot on <template>
var slotBinding = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding) {
{
if (el.slotTarget || el.slotScope) {
warn$2(
"Unexpected mixed usage of different slot syntaxes.",
el
);
}
if (el.parent && !maybeComponent(el.parent)) {
warn$2(
"<template v-slot> can only appear at the root level inside " +
"the receiving component",
el
);
}
}
var ref = getSlotName(slotBinding);
var name = ref.name;
var dynamic = ref.dynamic;
el.slotTarget = name;
el.slotTargetDynamic = dynamic;
el.slotScope = slotBinding.value || emptySlotScopeToken; // force it into a scoped slot for perf
}
} else {
// v-slot on component, denotes default slot
var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding$1) {
{
if (!maybeComponent(el)) {
warn$2(
"v-slot can only be used on components or <template>.",
slotBinding$1
);
}
if (el.slotScope || el.slotTarget) {
warn$2(
"Unexpected mixed usage of different slot syntaxes.",
el
);
}
if (el.scopedSlots) {
warn$2(
"To avoid scope ambiguity, the default slot should also use " +
"<template> syntax when there are other named slots.",
slotBinding$1
);
}
}
// add the component's children to its default slot
var slots = el.scopedSlots || (el.scopedSlots = {});
var ref$1 = getSlotName(slotBinding$1);
var name$1 = ref$1.name;
var dynamic$1 = ref$1.dynamic;
var slotContainer = slots[name$1] = createASTElement('template', [], el);
slotContainer.slotTarget = name$1;
slotContainer.slotTargetDynamic = dynamic$1;
slotContainer.children = el.children.filter(function (c) {
if (!c.slotScope) {
c.parent = slotContainer;
return true
}
});
slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken;
// remove children as they are returned from scopedSlots now
el.children = [];
// mark el non-plain so data gets generated
el.plain = false;
}
}
}
}
function getSlotName (binding) {
var name = binding.name.replace(slotRE, '');
if (!name) {
if (binding.name[0] !== '#') {
name = 'default';
} else {
warn$2(
"v-slot shorthand syntax requires a slot name.",
binding
);
}
}
return dynamicArgRE.test(name)
// dynamic [name]
? { name: name.slice(1, -1), dynamic: true }
// static name
: { name: ("\"" + name + "\""), dynamic: false }
}
// handle <slot/> outlets
function processSlotOutlet (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (el.key) {
warn$2(
"`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead.",
getRawBindingAttr(el, 'key')
);
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var i, l, name, rawName, value, modifiers, syncGen, isDynamic;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name.replace(dirRE, ''));
// support .foo shorthand syntax for the .prop modifier
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isDynamic = dynamicArgRE.test(name);
if (isDynamic) {
name = name.slice(1, -1);
}
if (
value.trim().length === 0
) {
warn$2(
("The value for a v-bind expression cannot be empty. Found in \"v-bind:" + name + "\"")
);
}
if (modifiers) {
if (modifiers.prop && !isDynamic) {
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel && !isDynamic) {
name = camelize(name);
}
if (modifiers.sync) {
syncGen = genAssignmentCode(value, "$event");
if (!isDynamic) {
addHandler(
el,
("update:" + (camelize(name))),
syncGen,
null,
false,
warn$2,
list[i]
);
if (hyphenate(name) !== camelize(name)) {
addHandler(
el,
("update:" + (hyphenate(name))),
syncGen,
null,
false,
warn$2,
list[i]
);
}
} else {
// handler w/ dynamic event name
addHandler(
el,
("\"update:\"+(" + name + ")"),
syncGen,
null,
false,
warn$2,
list[i],
true // dynamic
);
}
}
}
if ((modifiers && modifiers.prop) || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value, list[i], isDynamic);
} else {
addAttr(el, name, value, list[i], isDynamic);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
isDynamic = dynamicArgRE.test(name);
if (isDynamic) {
name = name.slice(1, -1);
}
addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
var arg = argMatch && argMatch[1];
isDynamic = false;
if (arg) {
name = name.slice(0, -(arg.length + 1));
if (dynamicArgRE.test(arg)) {
arg = arg.slice(1, -1);
isDynamic = true;
}
}
addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]);
if (name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
{
var res = parseText(value, delimiters);
if (res) {
warn$2(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.',
list[i]
);
}
}
addAttr(el, name, JSON.stringify(value), list[i]);
// #6887 firefox doesn't update muted state if set via attribute
// even immediately after element creation
if (!el.component &&
name === 'muted' &&
platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, 'true', list[i]);
}
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if (
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
// for script (e.g. type="x/template") or style, do not decode content
function isTextTag (el) {
return el.tag === 'script' || el.tag === 'style'
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$2(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"You are binding v-model directly to a v-for iteration alias. " +
"This will not be able to modify the v-for source array because " +
"writing to the alias is like modifying a function local variable. " +
"Consider using an array of objects and use v-model on an object property instead.",
el.rawAttrsMap['v-model']
);
}
_el = _el.parent;
}
}
/* */
function preTransformNode (el, options) {
if (el.tag === 'input') {
var map = el.attrsMap;
if (!map['v-model']) {
return
}
var typeBinding;
if (map[':type'] || map['v-bind:type']) {
typeBinding = getBindingAttr(el, 'type');
}
if (!map.type && !typeBinding && map['v-bind']) {
typeBinding = "(" + (map['v-bind']) + ").type";
}
if (typeBinding) {
var ifCondition = getAndRemoveAttr(el, 'v-if', true);
var ifConditionExtra = ifCondition ? ("&&(" + ifCondition + ")") : "";
var hasElse = getAndRemoveAttr(el, 'v-else', true) != null;
var elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true);
// 1. checkbox
var branch0 = cloneASTElement(el);
// process for on the main node
processFor(branch0);
addRawAttr(branch0, 'type', 'checkbox');
processElement(branch0, options);
branch0.processed = true; // prevent it from double-processed
branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra;
addIfCondition(branch0, {
exp: branch0.if,
block: branch0
});
// 2. add radio else-if condition
var branch1 = cloneASTElement(el);
getAndRemoveAttr(branch1, 'v-for', true);
addRawAttr(branch1, 'type', 'radio');
processElement(branch1, options);
addIfCondition(branch0, {
exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra,
block: branch1
});
// 3. other
var branch2 = cloneASTElement(el);
getAndRemoveAttr(branch2, 'v-for', true);
addRawAttr(branch2, ':type', typeBinding);
processElement(branch2, options);
addIfCondition(branch0, {
exp: ifCondition,
block: branch2
});
if (hasElse) {
branch0.else = true;
} else if (elseIfCondition) {
branch0.elseif = elseIfCondition;
}
return branch0
}
}
}
function cloneASTElement (el) {
return createASTElement(el.tag, el.attrsList.slice(), el.parent)
}
var model$1 = {
preTransformNode: preTransformNode
};
var modules$1 = [
klass$1,
style$1,
model$1
];
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"), dir);
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"), dir);
}
}
var directives$1 = {
model: model,
text: text,
html: html
};
/* */
var baseOptions = {
expectHTML: true,
modules: modules$1,
directives: directives$1,
isPreTag: isPreTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: genStaticKeys(modules$1)
};
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic$1(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' +
(keys ? ',' + keys : '')
)
}
function markStatic$1 (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic$1(child);
if (!child.static) {
node.static = false;
}
}
if (node.ifConditions) {
for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {
var block = node.ifConditions[i$1].block;
markStatic$1(block);
if (!block.static) {
node.static = false;
}
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
for (var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) {
markStaticRoots(node.ifConditions[i$1].block, isInFor);
}
}
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function(?:\s+[\w$]+)?\s*\(/;
var fnInvokeRE = /\([^)]*?\);*$/;
var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/;
// KeyboardEvent.keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// KeyboardEvent.key aliases
var keyNames = {
// #7880: IE11 and Edge use `Esc` for Escape key name.
esc: ['Esc', 'Escape'],
tab: 'Tab',
enter: 'Enter',
// #9112: IE11 uses `Spacebar` for Space key name.
space: [' ', 'Spacebar'],
// #7806: IE11 uses key names without `Arrow` prefix for arrow keys.
up: ['Up', 'ArrowUp'],
left: ['Left', 'ArrowLeft'],
right: ['Right', 'ArrowRight'],
down: ['Down', 'ArrowDown'],
// #9112: IE11 uses `Del` for Delete key name.
'delete': ['Backspace', 'Delete', 'Del']
};
// #4868: modifiers that prevent the execution of the listener
// need to explicitly return null so that we can determine whether to remove
// the listener for .once
var genGuard = function (condition) { return ("if(" + condition + ")return null;"); };
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: genGuard("$event.target !== $event.currentTarget"),
ctrl: genGuard("!$event.ctrlKey"),
shift: genGuard("!$event.shiftKey"),
alt: genGuard("!$event.altKey"),
meta: genGuard("!$event.metaKey"),
left: genGuard("'button' in $event && $event.button !== 0"),
middle: genGuard("'button' in $event && $event.button !== 1"),
right: genGuard("'button' in $event && $event.button !== 2")
};
function genHandlers (
events,
isNative
) {
var prefix = isNative ? 'nativeOn:' : 'on:';
var staticHandlers = "";
var dynamicHandlers = "";
for (var name in events) {
var handlerCode = genHandler(events[name]);
if (events[name] && events[name].dynamic) {
dynamicHandlers += name + "," + handlerCode + ",";
} else {
staticHandlers += "\"" + name + "\":" + handlerCode + ",";
}
}
staticHandlers = "{" + (staticHandlers.slice(0, -1)) + "}";
if (dynamicHandlers) {
return prefix + "_d(" + staticHandlers + ",[" + (dynamicHandlers.slice(0, -1)) + "])"
} else {
return prefix + staticHandlers
}
}
function genHandler (handler) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(handler); }).join(',')) + "]")
}
var isMethodPath = simplePathRE.test(handler.value);
var isFunctionExpression = fnExpRE.test(handler.value);
var isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, ''));
if (!handler.modifiers) {
if (isMethodPath || isFunctionExpression) {
return handler.value
}
return ("function($event){" + (isFunctionInvocation ? ("return " + (handler.value)) : handler.value) + "}") // inline statement
} else {
var code = '';
var genModifierCode = '';
var keys = [];
for (var key in handler.modifiers) {
if (modifierCode[key]) {
genModifierCode += modifierCode[key];
// left/right
if (keyCodes[key]) {
keys.push(key);
}
} else if (key === 'exact') {
var modifiers = (handler.modifiers);
genModifierCode += genGuard(
['ctrl', 'shift', 'alt', 'meta']
.filter(function (keyModifier) { return !modifiers[keyModifier]; })
.map(function (keyModifier) { return ("$event." + keyModifier + "Key"); })
.join('||')
);
} else {
keys.push(key);
}
}
if (keys.length) {
code += genKeyFilter(keys);
}
// Make sure modifiers like prevent and stop get executed after key filtering
if (genModifierCode) {
code += genModifierCode;
}
var handlerCode = isMethodPath
? ("return " + (handler.value) + ".apply(null, arguments)")
: isFunctionExpression
? ("return (" + (handler.value) + ").apply(null, arguments)")
: isFunctionInvocation
? ("return " + (handler.value))
: handler.value;
return ("function($event){" + code + handlerCode + "}")
}
}
function genKeyFilter (keys) {
return (
// make sure the key filters only apply to KeyboardEvents
// #9441: can't use 'keyCode' in $event because Chrome autofill fires fake
// key events that do not have keyCode property...
"if(!$event.type.indexOf('key')&&" +
(keys.map(genFilterCode).join('&&')) + ")return null;"
)
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var keyCode = keyCodes[key];
var keyName = keyNames[key];
return (
"_k($event.keyCode," +
(JSON.stringify(key)) + "," +
(JSON.stringify(keyCode)) + "," +
"$event.key," +
"" + (JSON.stringify(keyName)) +
")"
)
}
/* */
function on (el, dir) {
if (dir.modifiers) {
warn("v-on without argument does not support modifiers.");
}
el.wrapListeners = function (code) { return ("_g(" + code + "," + (dir.value) + ")"); };
}
/* */
function bind$1 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")")
};
}
/* */
var baseDirectives = {
on: on,
bind: bind$1,
cloak: noop
};
/* */
var CodegenState = function CodegenState (options) {
this.options = options;
this.warn = options.warn || baseWarn;
this.transforms = pluckModuleFunction(options.modules, 'transformCode');
this.dataGenFns = pluckModuleFunction(options.modules, 'genData');
this.directives = extend(extend({}, baseDirectives), options.directives);
var isReservedTag = options.isReservedTag || no;
this.maybeComponent = function (el) { return !!el.component || !isReservedTag(el.tag); };
this.onceId = 0;
this.staticRenderFns = [];
this.pre = false;
};
function generate (
ast,
options
) {
var state = new CodegenState(options);
// fix #11483, Root level <script> tags should not be rendered.
var code = ast ? (ast.tag === 'script' ? 'null' : genElement(ast, state)) : '_c("div")';
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: state.staticRenderFns
}
}
function genElement (el, state) {
if (el.parent) {
el.pre = el.pre || el.parent.pre;
}
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el, state)
} else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
} else if (el.for && !el.forProcessed) {
return genFor(el, state)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.tag === 'template' && !el.slotTarget && !state.pre) {
return genChildren(el, state) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el, state)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el, state);
} else {
var data;
if (!el.plain || (el.pre && state.maybeComponent(el))) {
data = genData$2(el, state);
}
var children = el.inlineTemplate ? null : genChildren(el, state, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < state.transforms.length; i++) {
code = state.transforms[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el, state) {
el.staticProcessed = true;
// Some elements (templates) need to behave differently inside of a v-pre
// node. All pre nodes are static roots, so we can use this as a location to
// wrap a state change and reset it upon exiting the pre node.
var originalPreState = state.pre;
if (el.pre) {
state.pre = el.pre;
}
state.staticRenderFns.push(("with(this){return " + (genElement(el, state)) + "}"));
state.pre = originalPreState;
return ("_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el, state) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
state.warn(
"v-once can only be used inside v-for that is keyed. ",
el.rawAttrsMap['v-once']
);
return genElement(el, state)
}
return ("_o(" + (genElement(el, state)) + "," + (state.onceId++) + "," + key + ")")
} else {
return genStatic(el, state)
}
}
function genIf (
el,
state,
altGen,
altEmpty
) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)
}
function genIfConditions (
conditions,
state,
altGen,
altEmpty
) {
if (!conditions.length) {
return altEmpty || '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions, state, altGen, altEmpty)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return altGen
? altGen(el, state)
: el.once
? genOnce(el, state)
: genElement(el, state)
}
}
function genFor (
el,
state,
altGen,
altHelper
) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
if (state.maybeComponent(el) &&
el.tag !== 'slot' &&
el.tag !== 'template' &&
!el.key
) {
state.warn(
"<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " +
"v-for should have explicit keys. " +
"See https://vuejs.org/guide/list.html#key for more info.",
el.rawAttrsMap['v-for'],
true /* tip */
);
}
el.forProcessed = true; // avoid recursion
return (altHelper || '_l') + "((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + ((altGen || genElement)(el, state)) +
'})'
}
function genData$2 (el, state) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el, state);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < state.dataGenFns.length; i++) {
data += state.dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:" + (genProps(el.attrs)) + ",";
}
// DOM props
if (el.props) {
data += "domProps:" + (genProps(el.props)) + ",";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events, false)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true)) + ",";
}
// slot target
// only for non-scoped slots
if (el.slotTarget && !el.slotScope) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el, el.scopedSlots, state)) + ",";
}
// component v-model
if (el.model) {
data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el, state);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind dynamic argument wrap
// v-bind with dynamic arguments must be applied using the same v-bind object
// merge helper so that class/style/mustUseProp attrs are handled correctly.
if (el.dynamicAttrs) {
data = "_b(" + data + ",\"" + (el.tag) + "\"," + (genProps(el.dynamicAttrs)) + ")";
}
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
// v-on data wrap
if (el.wrapListeners) {
data = el.wrapListeners(data);
}
return data
}
function genDirectives (el, state) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = state.directives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, state.warn);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:" + (dir.isDynamicArg ? dir.arg : ("\"" + (dir.arg) + "\""))) : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el, state) {
var ast = el.children[0];
if (el.children.length !== 1 || ast.type !== 1) {
state.warn(
'Inline-template components must have exactly one child element.',
{ start: el.start }
);
}
if (ast && ast.type === 1) {
var inlineRenderFns = generate(ast, state.options);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (
el,
slots,
state
) {
// by default scoped slots are considered "stable", this allows child
// components with only scoped slots to skip forced updates from parent.
// but in some cases we have to bail-out of this optimization
// for example if the slot contains dynamic names, has v-if or v-for on them...
var needsForceUpdate = el.for || Object.keys(slots).some(function (key) {
var slot = slots[key];
return (
slot.slotTargetDynamic ||
slot.if ||
slot.for ||
containsSlotChild(slot) // is passing down slot from parent which may be dynamic
)
});
// #9534: if a component with scoped slots is inside a conditional branch,
// it's possible for the same component to be reused but with different
// compiled slot content. To avoid that, we generate a unique key based on
// the generated code of all the slot contents.
var needsKey = !!el.if;
// OR when it is inside another scoped slot or v-for (the reactivity may be
// disconnected due to the intermediate scope variable)
// #9438, #9506
// TODO: this can be further optimized by properly analyzing in-scope bindings
// and skip force updating ones that do not actually use scope variables.
if (!needsForceUpdate) {
var parent = el.parent;
while (parent) {
if (
(parent.slotScope && parent.slotScope !== emptySlotScopeToken) ||
parent.for
) {
needsForceUpdate = true;
break
}
if (parent.if) {
needsKey = true;
}
parent = parent.parent;
}
}
var generatedSlots = Object.keys(slots)
.map(function (key) { return genScopedSlot(slots[key], state); })
.join(',');
return ("scopedSlots:_u([" + generatedSlots + "]" + (needsForceUpdate ? ",null,true" : "") + (!needsForceUpdate && needsKey ? (",null,false," + (hash(generatedSlots))) : "") + ")")
}
function hash(str) {
var hash = 5381;
var i = str.length;
while(i) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}
return hash >>> 0
}
function containsSlotChild (el) {
if (el.type === 1) {
if (el.tag === 'slot') {
return true
}
return el.children.some(containsSlotChild)
}
return false
}
function genScopedSlot (
el,
state
) {
var isLegacySyntax = el.attrsMap['slot-scope'];
if (el.if && !el.ifProcessed && !isLegacySyntax) {
return genIf(el, state, genScopedSlot, "null")
}
if (el.for && !el.forProcessed) {
return genFor(el, state, genScopedSlot)
}
var slotScope = el.slotScope === emptySlotScopeToken
? ""
: String(el.slotScope);
var fn = "function(" + slotScope + "){" +
"return " + (el.tag === 'template'
? el.if && isLegacySyntax
? ("(" + (el.if) + ")?" + (genChildren(el, state) || 'undefined') + ":undefined")
: genChildren(el, state) || 'undefined'
: genElement(el, state)) + "}";
// reverse proxy v-slot without scope on this.$slots
var reverseProxy = slotScope ? "" : ",proxy:true";
return ("{key:" + (el.slotTarget || "\"default\"") + ",fn:" + fn + reverseProxy + "}")
}
function genChildren (
el,
state,
checkSkip,
altGenElement,
altGenNode
) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (children.length === 1 &&
el$1.for &&
el$1.tag !== 'template' &&
el$1.tag !== 'slot'
) {
var normalizationType = checkSkip
? state.maybeComponent(el$1) ? ",1" : ",0"
: "";
return ("" + ((altGenElement || genElement)(el$1, state)) + normalizationType)
}
var normalizationType$1 = checkSkip
? getNormalizationType(children, state.maybeComponent)
: 0;
var gen = altGenNode || genNode;
return ("[" + (children.map(function (c) { return gen(c, state); }).join(',')) + "]" + (normalizationType$1 ? ("," + normalizationType$1) : ''))
}
}
// determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function getNormalizationType (
children,
maybeComponent
) {
var res = 0;
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (el.type !== 1) {
continue
}
if (needsNormalization(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
res = 2;
break
}
if (maybeComponent(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {
res = 1;
}
}
return res
}
function needsNormalization (el) {
return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}
function genNode (node, state) {
if (node.type === 1) {
return genElement(node, state)
} else if (node.type === 3 && node.isComment) {
return genComment(node)
} else {
return genText(node)
}
}
function genText (text) {
return ("_v(" + (text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))) + ")")
}
function genComment (comment) {
return ("_e(" + (JSON.stringify(comment.text)) + ")")
}
function genSlot (el, state) {
var slotName = el.slotName || '"default"';
var children = genChildren(el, state);
var res = "_t(" + slotName + (children ? (",function(){return " + children + "}") : '');
var attrs = el.attrs || el.dynamicAttrs
? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function (attr) { return ({
// slot props are camelized
name: camelize(attr.name),
value: attr.value,
dynamic: attr.dynamic
}); }))
: null;
var bind$$1 = el.attrsMap['v-bind'];
if ((attrs || bind$$1) && !children) {
res += ",null";
}
if (attrs) {
res += "," + attrs;
}
if (bind$$1) {
res += (attrs ? '' : ',null') + "," + bind$$1;
}
return res + ')'
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (
componentName,
el,
state
) {
var children = el.inlineTemplate ? null : genChildren(el, state, true);
return ("_c(" + componentName + "," + (genData$2(el, state)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var staticProps = "";
var dynamicProps = "";
for (var i = 0; i < props.length; i++) {
var prop = props[i];
var value = transformSpecialNewlines(prop.value);
if (prop.dynamic) {
dynamicProps += (prop.name) + "," + value + ",";
} else {
staticProps += "\"" + (prop.name) + "\":" + value + ",";
}
}
staticProps = "{" + (staticProps.slice(0, -1)) + "}";
if (dynamicProps) {
return ("_d(" + staticProps + ",[" + (dynamicProps.slice(0, -1)) + "])")
} else {
return staticProps
}
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
// these keywords should not appear inside expressions, but operators like
// typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// these unary operators should not be used as property/method names
var unaryOperatorsRE = new RegExp('\\b' + (
'delete,typeof,void'
).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)');
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast, warn) {
if (ast) {
checkNode(ast, warn);
}
}
function checkNode (node, warn) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
var range = node.rawAttrsMap[name];
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), warn, range);
} else if (name === 'v-slot' || name[0] === '#') {
checkFunctionParameterExpression(value, (name + "=\"" + value + "\""), warn, range);
} else if (onRE.test(name)) {
checkEvent(value, (name + "=\"" + value + "\""), warn, range);
} else {
checkExpression(value, (name + "=\"" + value + "\""), warn, range);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], warn);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, warn, node);
}
}
function checkEvent (exp, text, warn, range) {
var stripped = exp.replace(stripStringRE, '');
var keywordMatch = stripped.match(unaryOperatorsRE);
if (keywordMatch && stripped.charAt(keywordMatch.index - 1) !== '$') {
warn(
"avoid using JavaScript unary operator as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()),
range
);
}
checkExpression(exp, text, warn, range);
}
function checkFor (node, text, warn, range) {
checkExpression(node.for || '', text, warn, range);
checkIdentifier(node.alias, 'v-for alias', text, warn, range);
checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range);
checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range);
}
function checkIdentifier (
ident,
type,
text,
warn,
range
) {
if (typeof ident === 'string') {
try {
new Function(("var " + ident + "=_"));
} catch (e) {
warn(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim())), range);
}
}
}
function checkExpression (exp, text, warn, range) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
warn(
"avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\"\n Raw expression: " + (text.trim()),
range
);
} else {
warn(
"invalid expression: " + (e.message) + " in\n\n" +
" " + exp + "\n\n" +
" Raw expression: " + (text.trim()) + "\n",
range
);
}
}
}
function checkFunctionParameterExpression (exp, text, warn, range) {
try {
new Function(exp, '');
} catch (e) {
warn(
"invalid function parameter expression: " + (e.message) + " in\n\n" +
" " + exp + "\n\n" +
" Raw expression: " + (text.trim()) + "\n",
range
);
}
}
/* */
var range = 2;
function generateCodeFrame (
source,
start,
end
) {
if ( start === void 0 ) start = 0;
if ( end === void 0 ) end = source.length;
var lines = source.split(/\r?\n/);
var count = 0;
var res = [];
for (var i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (var j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) { continue }
res.push(("" + (j + 1) + (repeat$1(" ", 3 - String(j + 1).length)) + "| " + (lines[j])));
var lineLength = lines[j].length;
if (j === i) {
// push underline
var pad = start - (count - lineLength) + 1;
var length = end > count ? lineLength - pad : end - start;
res.push(" | " + repeat$1(" ", pad) + repeat$1("^", length));
} else if (j > i) {
if (end > count) {
var length$1 = Math.min(end - count, lineLength);
res.push(" | " + repeat$1("^", length$1));
}
count += lineLength + 1;
}
}
break
}
}
return res.join('\n')
}
function repeat$1 (str, n) {
var result = '';
if (n > 0) {
while (true) { // eslint-disable-line
if (n & 1) { result += str; }
n >>>= 1;
if (n <= 0) { break }
str += str;
}
}
return result
}
/* */
function createFunction (code, errors) {
try {
return new Function(code)
} catch (err) {
errors.push({ err: err, code: code });
return noop
}
}
function createCompileToFunctionFn (compile) {
var cache = Object.create(null);
return function compileToFunctions (
template,
options,
vm
) {
options = extend({}, options);
var warn$$1 = options.warn || warn;
delete options.warn;
/* istanbul ignore if */
{
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn$$1(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
// check cache
var key = options.delimiters
? String(options.delimiters) + template
: template;
if (cache[key]) {
return cache[key]
}
// compile
var compiled = compile(template, options);
// check compilation errors/tips
{
if (compiled.errors && compiled.errors.length) {
if (options.outputSourceRange) {
compiled.errors.forEach(function (e) {
warn$$1(
"Error compiling template:\n\n" + (e.msg) + "\n\n" +
generateCodeFrame(template, e.start, e.end),
vm
);
});
} else {
warn$$1(
"Error compiling template:\n\n" + template + "\n\n" +
compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n',
vm
);
}
}
if (compiled.tips && compiled.tips.length) {
if (options.outputSourceRange) {
compiled.tips.forEach(function (e) { return tip(e.msg, vm); });
} else {
compiled.tips.forEach(function (msg) { return tip(msg, vm); });
}
}
}
// turn code into functions
var res = {};
var fnGenErrors = [];
res.render = createFunction(compiled.render, fnGenErrors);
res.staticRenderFns = compiled.staticRenderFns.map(function (code) {
return createFunction(code, fnGenErrors)
});
// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
{
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn$$1(
"Failed to generate render function:\n\n" +
fnGenErrors.map(function (ref) {
var err = ref.err;
var code = ref.code;
return ((err.toString()) + " in\n\n" + code + "\n");
}).join('\n'),
vm
);
}
}
return (cache[key] = res)
}
}
/* */
function createCompilerCreator (baseCompile) {
return function createCompiler (baseOptions) {
function compile (
template,
options
) {
var finalOptions = Object.create(baseOptions);
var errors = [];
var tips = [];
var warn = function (msg, range, tip) {
(tip ? tips : errors).push(msg);
};
if (options) {
if (options.outputSourceRange) {
// $flow-disable-line
var leadingSpaceLength = template.match(/^\s*/)[0].length;
warn = function (msg, range, tip) {
var data = { msg: msg };
if (range) {
if (range.start != null) {
data.start = range.start + leadingSpaceLength;
}
if (range.end != null) {
data.end = range.end + leadingSpaceLength;
}
}
(tip ? tips : errors).push(data);
};
}
// merge custom modules
if (options.modules) {
finalOptions.modules =
(baseOptions.modules || []).concat(options.modules);
}
// merge custom directives
if (options.directives) {
finalOptions.directives = extend(
Object.create(baseOptions.directives || null),
options.directives
);
}
// copy other options
for (var key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
finalOptions.warn = warn;
var compiled = baseCompile(template.trim(), finalOptions);
{
detectErrors(compiled.ast, warn);
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
return {
compile: compile,
compileToFunctions: createCompileToFunctionFn(compile)
}
}
}
/* */
// `createCompilerCreator` allows creating compilers that use alternative
// parser/optimizer/codegen, e.g the SSR optimizing compiler.
// Here we just export a default compiler using the default parts.
var createCompiler = createCompilerCreator(function baseCompile (
template,
options
) {
var ast = parse(template.trim(), options);
if (options.optimize !== false) {
optimize(ast, options);
}
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
var ref$1 = createCompiler(baseOptions);
var compile = ref$1.compile;
var compileToFunctions = ref$1.compileToFunctions;
/* */
// check whether current browser encodes a char inside attribute values
var div;
function getShouldDecode (href) {
div = div || document.createElement('div');
div.innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>";
return div.innerHTML.indexOf(' ') > 0
}
// #3663: IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false;
// #6828: chrome encodes content in a[href]
var shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false;
/* */
var idToTemplate = cached(function (id) {
var el = query(id);
return el && el.innerHTML
});
var mount = Vue.prototype.$mount;
Vue.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if (!template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
{
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile');
}
var ref = compileToFunctions(template, {
outputSourceRange: "development" !== 'production',
shouldDecodeNewlines: shouldDecodeNewlines,
shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile end');
measure(("vue " + (this._name) + " compile"), 'compile', 'compile end');
}
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
var container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue.compile = compileToFunctions;
return Vue;
});
//Included:lib/003.simplest-db-v1.0.3.part.js
/*lib:simplest-db@1.0.3 + modifications*/
(function (root, factory) {
const scope = (typeof window !== 'undefined') ? window : global;
if("SimplestDB" in scope) return scope.SimplestDB;
const output = factory();
if(typeof module === 'object' && typeof module.exports === 'object')
module.exports = output;
if(typeof define === 'function' && define.amd)
define([], factory);
if(typeof exports === 'object')
exports["SimplestDB"] = output;
scope["SimplestDB"] = output;
})(this, function() {
class SimplestDB {
static create(...args) {
return new this(...args);
}
static getFS() {
if(this.$fs) {
return this.$fs;
}
this.$fs = new SimplestDB({
schema: "system",
tables: {
"fs": {
columns: {
"path": { is_type: "string" },
"contents": { is_type: "string" },
"metadata": { is_type: "object" },
}
}
}
});
return this.$fs;
}
static getCache() {
if(this.$cache) {
return this.$cache;
}
this.$cache = new SimplestDB({
schema: "system",
tables: {
"cache": {
columns: {
"key": { is_type: "string" },
"value": { is_type: "string" },
}
}
}
});
return this.$cache;
}
constructor(schema = {}, noValidate = false) {
if(typeof schema !== "object") throw new Error("Required «schema» to be an object, found «" + typeof(schema) + "» [0301]");
if(typeof schema.schema !== "string") schema.schema = "system";
if(!("attributes" in schema)) {Object.assign(schema, {attributes:{}})}
if(!("tables" in schema)) {Object.assign(schema, {tables:{}})}
this.schema = this.validateSchema(schema);
this.noValidate = noValidate;
this.baseDir = (typeof schema.baseDir === "string" ? schema.baseDir.replace(/^\/+/g, "").replace(/\/+$/g, "") : "./sdb_modules") + "/";
if(typeof global === "object") {
const fs = require("fs");
const hasBaseDir = fs.existsSync(this.baseDir) && fs.lstatSync(this.baseDir).isDirectory();
if(!hasBaseDir) {
fs.mkdirSync(this.baseDir);
}
}
}
validateTable(tableId) {
if(typeof tableId !== "string") throw new Error("Required parameter table «" + tableId + "» to be a string, found «" + typeof(tableId) + "» [0101]");
if(this.noValidate) return this.schema.tables[tableId];
if(!(tableId in this.schema.tables)) throw new Error("Required parameter table «" + tableId + "» to exist as table in schema, only accepted: «" + Object.keys(this.schema.tables).join("», «") + "» [0402]");
return this.schema.tables[tableId];
}
validateRow(tableId, value) {
if(typeof tableId !== "string") throw new Error("Required parameter table «" + tableId + "» to be a string, found «" + typeof(tableId) + "» [0801]");
if(this.noValidate) return this.schema.tables[tableId];
if(!(tableId in this.schema.tables)) throw new Error("Required parameter table «" + tableId + "» to exist as table in schema, only accepted: «" + Object.keys(this.schema.tables).join("», «") + "» [0802]");
return true;
}
validateSchema(schema) {
if(typeof schema !== "object") throw new Error("Required «schema» to be an object, found «" + typeof(schema) + "» [0301]");
if(typeof schema.schema !== "string") throw new Error("Required «schema.schema» to be a string, found «" + typeof(schema) + "» [0302]");
if(typeof schema.attributes === "undefined") schema.attributes = {};
if(typeof schema.attributes !== "object") throw new Error("Required «schema.attributes» to be an object, found «" + typeof(attributes) + "» [0303]");
if(typeof schema.tables === "undefined") schema.tables = {};
if(typeof schema.tables !== "object") throw new Error("Required «schema.tables» to be an object, found «" + typeof(tables) + "» [0304]");
const tableIds = Object.keys(schema.tables);
for(let indexTable = 0; indexTable < tableIds.length; indexTable++) {
const tableId = tableIds[indexTable];
if(typeof schema.tables[tableId] !== "object") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "]» to be an object, found «" + typeof(schema.tables[tableId]) + "» [0305]");
if(typeof schema.tables[tableId].attributes === "undefined") schema.tables[tableId].attributes = {};
if(typeof schema.tables[tableId].attributes !== "object") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "].attributes» to be an object, found «" + typeof(attributes) + "» [0306]");
if(typeof schema.tables[tableId].columns === "undefined") schema.tables[tableId].columns = {};
if(typeof schema.tables[tableId].columns !== "object") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "].columns» to be an object, found «" + typeof(columns) + "» [0307]");
const tableData = schema.tables[tableId];
const columnIds = Object.keys(tableData.columns);
for(let indexColumn = 0; indexColumn < columnIds.length; indexColumn++) {
const columnId = columnIds[indexColumn];
const columnData = tableData.columns[columnId];
if(typeof columnData !== "object") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "].columns[" + JSON.stringify(columnId) + "]»")
if(typeof columnData.attributes === "undefined") columnData.attributes = {};
if(typeof columnData.attributes !== "object") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "].columns[" + JSON.stringify(columnId) + "].attributes»")
if(typeof columnData.is_type !== "string") throw new Error("Required «schema.tables[" + JSON.stringify(tableId) + "].columns[" + JSON.stringify(columnId) + "].is_type»")
}
}
return schema;
}
setSchema(schema) {
this.schema = this.validateSchema(schema);
}
consumeIdOf(tableId) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be an object, found «" + typeof(tableId) + "» [0901]");
this.validateTable(tableId);
if(typeof window === "object") {
const storageId = "SDB_STORAGE_FOR_" + this.schema.schema;
if(!(storageId in localStorage)) {
localStorage[storageId] = JSON.stringify({$KEYS:{[tableId]:1},[tableId]:{}});
return 1;
}
const storageJson = localStorage[storageId];
const storageData = JSON.parse(storageJson);
const tableLastId = storageData.$KEYS[tableId]++;
localStorage[storageId] = JSON.stringify(storageData);
return tableLastId;
} else if(typeof global === "object") {
const storageId = this.baseDir + this.schema.schema + ".data.json";
const fs = require("fs");
if(!fs.existsSync(storageId)) {
fs.writeFileSync(storageId, JSON.stringify({$KEYS:{[tableId]:1},[tableId]:{}}));
return 1;
}
const storageJson = fs.readFileSync(storageId).toString();
const storageData = JSON.parse(storageJson);
const tableLastId = storageData.$KEYS[tableId]++;
fs.writeFileSync(storageId, JSON.stringify(storageData), "utf8");
return tableLastId;
}
}
getData(tableId) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be an object, found «" + typeof(tableId) + "» [0401]");
this.validateTable(tableId);
if(typeof window === "object") {
const storageId = "SDB_STORAGE_FOR_" + this.schema.schema;
if(!(storageId in localStorage)) {
localStorage[storageId] = JSON.stringify({$KEYS:{}});
}
const storageJson = localStorage[storageId];
const storageData = JSON.parse(storageJson);
if(!(tableId in storageData)) {
return {};
throw new Error("Required model «" + tableId + "» to exist in database and not only in schema «" + this.schema.schema + "» [0402]");
}
return storageData[tableId];
} else if(typeof global === "object") {
const storageId = this.baseDir + this.schema.schema + ".data.json";
const fs = require("fs");
if(!fs.existsSync(storageId)) {
fs.writeFileSync(storageId, JSON.stringify({$KEYS:{}}), "utf8");
}
const storageJson = fs.readFileSync(storageId).toString();
const storageData = JSON.parse(storageJson);
if(!(tableId in storageData)) {
return {};
throw new Error("Required model «" + tableId + "» to exist in database and not only in schema «" + this.schema.schema + "» [0403]");
}
return Object.assign({}, storageData[tableId]);
}
}
setData(tableId, modelId, data) {
if(typeof window === "object") {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [0501]");
if(typeof modelId !== "number") throw new Error("Required «modelId» to be an number, found «" + typeof(modelId) + "» [0502]");
if(typeof data === "undefined") {}
else if(typeof data !== "object") throw new Error("Required «data» to be an object, found «" + typeof(data) + "» [0503]");
this.validateTable(tableId);
const storageId = "SDB_STORAGE_FOR_" + this.schema.schema;
if(!(storageId in localStorage)) {
localStorage[storageId] = JSON.stringify({$KEYS:{}});
}
const storageJson = localStorage[storageId];
const storageData = JSON.parse(storageJson);
if(!(tableId in storageData)) {
storageData[tableId] = {};
storageData.$KEYS[tableId] = 1;
}
let operation = "update";
let selectedId = (modelId === 0) ? storageData.$KEYS[tableId]++ : modelId;
if(!(selectedId in storageData[tableId])) {
if(modelId !== 0) {
throw new Error("Required parameter modelId «" + modelId + "» to be 0 or to exist as id in table «" + storageId + ":" + tableId + "» [0504]")
} else operation = "insert";
}
if(typeof data === "undefined") {
delete storageData[tableId][selectedId];
} else {
if(operation === "insert") {
data.id = selectedId;
}
storageData[tableId][selectedId] = Object.assign({}, storageData[tableId][selectedId] || {}, data);
}
const json = JSON.stringify(storageData);
localStorage[storageId] = json;
return selectedId;
} else if(typeof global === "object") {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [1101]");
if(typeof modelId !== "number") throw new Error("Required «modelId» to be an number, found «" + typeof(modelId) + "» [1102]");
if(typeof data === "undefined") {}
else if(typeof data !== "object") throw new Error("Required «data» to be an object, found «" + typeof(data) + "» [1103]");
this.validateTable(tableId);
const fs = require("fs");
const storageId = this.baseDir + this.schema.schema + ".data.json";
if(!fs.existsSync(storageId)) {
fs.writeFileSync(storageId, JSON.stringify({[tableId]:{},$KEYS:{[tableId]:1}}), "utf8");
}
const storageJson0 = fs.readFileSync(storageId).toString();
const storageData = JSON.parse(storageJson0);
if(!(tableId in storageData)) {
storageData[tableId] = {};
storageData.$KEYS[tableId] = 1;
}
let operation = "update";
let selectedId = modelId === 0 ? storageData.$KEYS[tableId]++ : modelId;
if(!(selectedId in storageData[tableId])) {
if(modelId !== 0) {
throw new Error("Required id «" + modelId + "» to be 0 (insert) or to exist as id in table «" + storageId + ":" + tableId + "#" + modelId + "» [1104]")
} else operation = "insert";
}
if(typeof data === "undefined") {
delete storageData[tableId][selectedId];
} else {
if(operation === "insert") {
data.id = selectedId;
}
storageData[tableId][selectedId] = Object.assign({}, storageData[tableId][selectedId] || {}, data);
}
const json = JSON.stringify(storageData);
fs.writeFileSync(storageId, json, "utf8");
return selectedId;
}
}
select(tableId, filter) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [0601]");
this.validateTable(tableId);
const data = this.getData(tableId);
if(typeof filter === "function") {
return Object.values(data).filter(filter).reduce((output, item) => {
try {
output[item.id] = item;
return output;
} catch (error) {
return false;
}
}, {});
} else if(typeof filter === "undefined") {
return data;
} else {
throw new Error("Required «filter» to be a valid, found «" + typeof(filter) + "» type [0602]");
}
}
insert(tableId, value) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [0701]");
if(typeof value !== "object") throw new Error("Required «value» to be an object, found «" + typeof(value) + "» [0702]");
this.validateRow(tableId, value);
return this.setData(tableId, 0, value);
}
update(tableId, instanceId, value) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [1201]");
if(typeof instanceId !== "number") throw new Error("Required «instanceId» to be an number, found «" + typeof(instanceId) + "» [1202]");
if(typeof value !== "object") throw new Error("Required «value» to be an object, found «" + typeof(value) + "» [1203]");
this.validateRow(tableId, value);
return this.setData(tableId, instanceId, value);
}
delete(tableId, instanceId) {
if(typeof tableId !== "string") throw new Error("Required «tableId» to be a string, found «" + typeof(tableId) + "» [1401]");
if(typeof instanceId !== "number") throw new Error("Required «instanceId» to be an number, found «" + typeof(instanceId) + "» [1402]");
this.validateTable(tableId);
return this.setData(tableId, instanceId, undefined);
}
}
SimplestDB.default = SimplestDB;
return SimplestDB;
}, this);
//Included:lib/004.ejs.part.js
(function (factory) {
// Only navigators:
if (typeof window === 'undefined') return;
// General boilerplate:
if (typeof window !== "undefined") {
if ("i18next" in window) return window.i18next;
}
if (typeof global !== "undefined") {
if ("i18next" in global) return global.i18next;
}
const output = factory();
if (typeof module === 'object' && typeof module.exports === 'object') module.exports = output;
if (typeof define === 'function' && define.amd) define([], factory);
if (typeof exports === 'object') exports["i18next"] = output;
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') window.i18next = output;
}
if (typeof global !== "undefined") {
if (typeof global !== 'undefined') global.i18next = output;
}
return output;
})(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) {
/*
* EJS Embedded JavaScript templates (v3.1.6)
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
'use strict';
/**
* @file Embedded JavaScript templating engine. {@link http://ejs.co}
* @author Matthew Eernisse <mde@fleegix.org>
* @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
* @project EJS
* @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
*/
/**
* EJS internal functions.
*
* Technically this "module" lies in the same file as {@link module:ejs}, for
* the sake of organization all the private functions re grouped into this
* module.
*
* @module ejs-internal
* @private
*/
/**
* Embedded JavaScript templating engine.
*
* @module ejs
* @public
*/
var fs = require('fs');
var path = require('path');
var utils = require('./utils');
var scopeOptionWarned = false;
/** @type {string} */
var _VERSION_STRING = require('../package.json').version;
var _DEFAULT_OPEN_DELIMITER = '<';
var _DEFAULT_CLOSE_DELIMITER = '>';
var _DEFAULT_DELIMITER = '%';
var _DEFAULT_LOCALS_NAME = 'locals';
var _NAME = 'ejs';
var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
// We don't allow 'cache' option to be passed in the data obj for
// the normal `render` call, but this is where Express 2 & 3 put it
// so we make an exception for `renderFile`
var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
var _BOM = /^\uFEFF/;
/**
* EJS template function cache. This can be a LRU object from lru-cache NPM
* module. By default, it is {@link module:utils.cache}, a simple in-process
* cache that grows continuously.
*
* @type {Cache}
*/
exports.cache = utils.cache;
/**
* Custom file loader. Useful for template preprocessing or restricting access
* to a certain part of the filesystem.
*
* @type {fileLoader}
*/
exports.fileLoader = fs.readFileSync;
/**
* Name of the object containing the locals.
*
* This variable is overridden by {@link Options}`.localsName` if it is not
* `undefined`.
*
* @type {String}
* @public
*/
exports.localsName = _DEFAULT_LOCALS_NAME;
/**
* Promise implementation -- defaults to the native implementation if available
* This is mostly just for testability
*
* @type {PromiseConstructorLike}
* @public
*/
exports.promiseImpl = (new Function('return this;'))().Promise;
/**
* Get the path to the included file from the parent file path and the
* specified path.
*
* @param {String} name specified path
* @param {String} filename parent file path
* @param {Boolean} [isDir=false] whether the parent file path is a directory
* @return {String}
*/
exports.resolveInclude = function (name, filename, isDir) {
var dirname = path.dirname;
var extname = path.extname;
var resolve = path.resolve;
var includePath = resolve(isDir ? filename : dirname(filename), name);
var ext = extname(name);
if (!ext) {
includePath += '.ejs';
}
return includePath;
};
/**
* Try to resolve file path on multiple directories
*
* @param {String} name specified path
* @param {Array<String>} paths list of possible parent directory paths
* @return {String}
*/
function resolvePaths(name, paths) {
var filePath;
if (paths.some(function (v) {
filePath = exports.resolveInclude(name, v, true);
return fs.existsSync(filePath);
})) {
return filePath;
}
}
/**
* Get the path to the included file by Options
*
* @param {String} path specified path
* @param {Options} options compilation options
* @return {String}
*/
function getIncludePath(path, options) {
var includePath;
var filePath;
var views = options.views;
var match = /^[A-Za-z]+:\\|^\//.exec(path);
// Abs path
if (match && match.length) {
path = path.replace(/^\/*/, '');
if (Array.isArray(options.root)) {
includePath = resolvePaths(path, options.root);
} else {
includePath = exports.resolveInclude(path, options.root || '/', true);
}
}
// Relative paths
else {
// Look relative to a passed filename first
if (options.filename) {
filePath = exports.resolveInclude(path, options.filename);
if (fs.existsSync(filePath)) {
includePath = filePath;
}
}
// Then look in any views directories
if (!includePath && Array.isArray(views)) {
includePath = resolvePaths(path, views);
}
if (!includePath && typeof options.includer !== 'function') {
throw new Error('Could not find the include file "' +
options.escapeFunction(path) + '"');
}
}
return includePath;
}
/**
* Get the template from a string or a file, either compiled on-the-fly or
* read from cache (if enabled), and cache the template if needed.
*
* If `template` is not set, the file specified in `options.filename` will be
* read.
*
* If `options.cache` is true, this function reads the file from
* `options.filename` so it must be set prior to calling this function.
*
* @memberof module:ejs-internal
* @param {Options} options compilation options
* @param {String} [template] template source
* @return {(TemplateFunction|ClientFunction)}
* Depending on the value of `options.client`, either type might be returned.
* @static
*/
function handleCache(options, template) {
var func;
var filename = options.filename;
var hasTemplate = arguments.length > 1;
if (options.cache) {
if (!filename) {
throw new Error('cache option requires a filename');
}
func = exports.cache.get(filename);
if (func) {
return func;
}
if (!hasTemplate) {
template = fileLoader(filename).toString().replace(_BOM, '');
}
}
else if (!hasTemplate) {
// istanbul ignore if: should not happen at all
if (!filename) {
throw new Error('Internal EJS error: no file name or template '
+ 'provided');
}
template = fileLoader(filename).toString().replace(_BOM, '');
}
func = exports.compile(template, options);
if (options.cache) {
exports.cache.set(filename, func);
}
return func;
}
/**
* Try calling handleCache with the given options and data and call the
* callback with the result. If an error occurs, call the callback with
* the error. Used by renderFile().
*
* @memberof module:ejs-internal
* @param {Options} options compilation options
* @param {Object} data template data
* @param {RenderFileCallback} cb callback
* @static
*/
function tryHandleCache(options, data, cb) {
var result;
if (!cb) {
if (typeof exports.promiseImpl == 'function') {
return new exports.promiseImpl(function (resolve, reject) {
try {
result = handleCache(options)(data);
resolve(result);
}
catch (err) {
reject(err);
}
});
}
else {
throw new Error('Please provide a callback function');
}
}
else {
try {
result = handleCache(options)(data);
}
catch (err) {
return cb(err);
}
cb(null, result);
}
}
/**
* fileLoader is independent
*
* @param {String} filePath ejs file path.
* @return {String} The contents of the specified file.
* @static
*/
function fileLoader(filePath) {
return exports.fileLoader(filePath);
}
/**
* Get the template function.
*
* If `options.cache` is `true`, then the template is cached.
*
* @memberof module:ejs-internal
* @param {String} path path for the specified file
* @param {Options} options compilation options
* @return {(TemplateFunction|ClientFunction)}
* Depending on the value of `options.client`, either type might be returned
* @static
*/
function includeFile(path, options) {
var opts = utils.shallowCopy({}, options);
opts.filename = getIncludePath(path, opts);
if (typeof options.includer === 'function') {
var includerResult = options.includer(path, opts.filename);
if (includerResult) {
if (includerResult.filename) {
opts.filename = includerResult.filename;
}
if (includerResult.template) {
return handleCache(opts, includerResult.template);
}
}
}
return handleCache(opts);
}
/**
* Re-throw the given `err` in context to the `str` of ejs, `filename`, and
* `lineno`.
*
* @implements {RethrowCallback}
* @memberof module:ejs-internal
* @param {Error} err Error object
* @param {String} str EJS source
* @param {String} flnm file name of the EJS file
* @param {Number} lineno line number of the error
* @param {EscapeCallback} esc
* @static
*/
function rethrow(err, str, flnm, lineno, esc) {
var lines = str.split('\n');
var start = Math.max(lineno - 3, 0);
var end = Math.min(lines.length, lineno + 3);
var filename = esc(flnm);
// Error context
var context = lines.slice(start, end).map(function (line, i) {
var curr = i + start + 1;
return (curr == lineno ? ' >> ' : ' ')
+ curr
+ '| '
+ line;
}).join('\n');
// Alter exception message
err.path = filename;
err.message = (filename || 'ejs') + ':'
+ lineno + '\n'
+ context + '\n\n'
+ err.message;
throw err;
}
function stripSemi(str) {
return str.replace(/;(\s*$)/, '$1');
}
/**
* Compile the given `str` of ejs into a template function.
*
* @param {String} template EJS template
*
* @param {Options} [opts] compilation options
*
* @return {(TemplateFunction|ClientFunction)}
* Depending on the value of `opts.client`, either type might be returned.
* Note that the return type of the function also depends on the value of `opts.async`.
* @public
*/
exports.compile = function compile(template, opts) {
var templ;
// v1 compat
// 'scope' is 'context'
// FIXME: Remove this in a future version
if (opts && opts.scope) {
if (!scopeOptionWarned) {
console.warn('`scope` option is deprecated and will be removed in EJS 3');
scopeOptionWarned = true;
}
if (!opts.context) {
opts.context = opts.scope;
}
delete opts.scope;
}
templ = new Template(template, opts);
return templ.compile();
};
/**
* Render the given `template` of ejs.
*
* If you would like to include options but not data, you need to explicitly
* call this function with `data` being an empty object or `null`.
*
* @param {String} template EJS template
* @param {Object} [data={}] template data
* @param {Options} [opts={}] compilation and rendering options
* @return {(String|Promise<String>)}
* Return value type depends on `opts.async`.
* @public
*/
exports.render = function (template, d, o) {
var data = d || {};
var opts = o || {};
// No options object -- if there are optiony names
// in the data, copy them to options
if (arguments.length == 2) {
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
}
return handleCache(opts, template)(data);
};
/**
* Render an EJS file at the given `path` and callback `cb(err, str)`.
*
* If you would like to include options but not data, you need to explicitly
* call this function with `data` being an empty object or `null`.
*
* @param {String} path path to the EJS file
* @param {Object} [data={}] template data
* @param {Options} [opts={}] compilation and rendering options
* @param {RenderFileCallback} cb callback
* @public
*/
exports.renderFile = function () {
var args = Array.prototype.slice.call(arguments);
var filename = args.shift();
var cb;
var opts = { filename: filename };
var data;
var viewOpts;
// Do we have a callback?
if (typeof arguments[arguments.length - 1] == 'function') {
cb = args.pop();
}
// Do we have data/opts?
if (args.length) {
// Should always have data obj
data = args.shift();
// Normal passed opts (data obj + opts obj)
if (args.length) {
// Use shallowCopy so we don't pollute passed in opts obj with new vals
utils.shallowCopy(opts, args.pop());
}
// Special casing for Express (settings + opts-in-data)
else {
// Express 3 and 4
if (data.settings) {
// Pull a few things from known locations
if (data.settings.views) {
opts.views = data.settings.views;
}
if (data.settings['view cache']) {
opts.cache = true;
}
// Undocumented after Express 2, but still usable, esp. for
// items that are unsafe to be passed along with data, like `root`
viewOpts = data.settings['view options'];
if (viewOpts) {
utils.shallowCopy(opts, viewOpts);
}
}
// Express 2 and lower, values set in app.locals, or people who just
// want to pass options in their data. NOTE: These values will override
// anything previously set in settings or settings['view options']
utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
}
opts.filename = filename;
}
else {
data = {};
}
return tryHandleCache(opts, data, cb);
};
/**
* Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
* @public
*/
/**
* EJS template class
* @public
*/
exports.Template = Template;
exports.clearCache = function () {
exports.cache.reset();
};
function Template(text, opts) {
opts = opts || {};
var options = {};
this.templateText = text;
/** @type {string | null} */
this.mode = null;
this.truncate = false;
this.currentLine = 1;
this.source = '';
options.client = opts.client || false;
options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
options.compileDebug = opts.compileDebug !== false;
options.debug = !!opts.debug;
options.filename = opts.filename;
options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
options.strict = opts.strict || false;
options.context = opts.context;
options.cache = opts.cache || false;
options.rmWhitespace = opts.rmWhitespace;
options.root = opts.root;
options.includer = opts.includer;
options.outputFunctionName = opts.outputFunctionName;
options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
options.views = opts.views;
options.async = opts.async;
options.destructuredLocals = opts.destructuredLocals;
options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
if (options.strict) {
options._with = false;
}
else {
options._with = typeof opts._with != 'undefined' ? opts._with : true;
}
this.opts = options;
this.regex = this.createRegex();
}
Template.modes = {
EVAL: 'eval',
ESCAPED: 'escaped',
RAW: 'raw',
COMMENT: 'comment',
LITERAL: 'literal'
};
Template.prototype = {
createRegex: function () {
var str = _REGEX_STRING;
var delim = utils.escapeRegExpChars(this.opts.delimiter);
var open = utils.escapeRegExpChars(this.opts.openDelimiter);
var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
str = str.replace(/%/g, delim)
.replace(/</g, open)
.replace(/>/g, close);
return new RegExp(str);
},
compile: function () {
/** @type {string} */
var src;
/** @type {ClientFunction} */
var fn;
var opts = this.opts;
var prepended = '';
var appended = '';
/** @type {EscapeCallback} */
var escapeFn = opts.escapeFunction;
/** @type {FunctionConstructor} */
var ctor;
/** @type {string} */
var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
if (!this.source) {
this.generateSource();
prepended +=
' var __output = "";\n' +
' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
}
if (opts.destructuredLocals && opts.destructuredLocals.length) {
var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
for (var i = 0; i < opts.destructuredLocals.length; i++) {
var name = opts.destructuredLocals[i];
if (i > 0) {
destructuring += ',\n ';
}
destructuring += name + ' = __locals.' + name;
}
prepended += destructuring + ';\n';
}
if (opts._with !== false) {
prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
appended += ' }' + '\n';
}
appended += ' return __output;' + '\n';
this.source = prepended + this.source + appended;
}
if (opts.compileDebug) {
src = 'var __line = 1' + '\n'
+ ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
+ ' , __filename = ' + sanitizedFilename + ';' + '\n'
+ 'try {' + '\n'
+ this.source
+ '} catch (e) {' + '\n'
+ ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
+ '}' + '\n';
}
else {
src = this.source;
}
if (opts.client) {
src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
if (opts.compileDebug) {
src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
}
}
if (opts.strict) {
src = '"use strict";\n' + src;
}
if (opts.debug) {
console.log(src);
}
if (opts.compileDebug && opts.filename) {
src = src + '\n'
+ '//# sourceURL=' + sanitizedFilename + '\n';
}
try {
if (opts.async) {
// Have to use generated function for this, since in envs without support,
// it breaks in parsing
try {
ctor = (new Function('return (async function(){}).constructor;'))();
}
catch (e) {
if (e instanceof SyntaxError) {
throw new Error('This environment does not support async/await');
}
else {
throw e;
}
}
}
else {
ctor = Function;
}
fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
}
catch (e) {
// istanbul ignore else
if (e instanceof SyntaxError) {
if (opts.filename) {
e.message += ' in ' + opts.filename;
}
e.message += ' while compiling ejs\n\n';
e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
e.message += 'https://github.com/RyanZim/EJS-Lint';
if (!opts.async) {
e.message += '\n';
e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
}
}
throw e;
}
// Return a callable function which will execute the function
// created by the source-code, with the passed data as locals
// Adds a local `include` function which allows full recursive include
var returnedFn = opts.client ? fn : function anonymous(data) {
var include = function (path, includeData) {
var d = utils.shallowCopy({}, data);
if (includeData) {
d = utils.shallowCopy(d, includeData);
}
return includeFile(path, opts)(d);
};
return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
};
if (opts.filename && typeof Object.defineProperty === 'function') {
var filename = opts.filename;
var basename = path.basename(filename, path.extname(filename));
try {
Object.defineProperty(returnedFn, 'name', {
value: basename,
writable: false,
enumerable: false,
configurable: true
});
} catch (e) {/* ignore */ }
}
return returnedFn;
},
generateSource: function () {
var opts = this.opts;
if (opts.rmWhitespace) {
// Have to use two separate replace here as `^` and `$` operators don't
// work well with `\r` and empty lines don't work well with the `m` flag.
this.templateText =
this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
}
// Slurp spaces and tabs before <%_ and after _%>
this.templateText =
this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
var self = this;
var matches = this.parseTemplateText();
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
if (matches && matches.length) {
matches.forEach(function (line, index) {
var closing;
// If this is an opening tag, check for closing tags
// FIXME: May end up with some false positives here
// Better to store modes as k/v with openDelimiter + delimiter as key
// Then this can simply check against the map
if (line.indexOf(o + d) === 0 // If it is a tag
&& line.indexOf(o + d + d) !== 0) { // and is not escaped
closing = matches[index + 2];
if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
throw new Error('Could not find matching close tag for "' + line + '".');
}
}
self.scanLine(line);
});
}
},
parseTemplateText: function () {
var str = this.templateText;
var pat = this.regex;
var result = pat.exec(str);
var arr = [];
var firstPos;
while (result) {
firstPos = result.index;
if (firstPos !== 0) {
arr.push(str.substring(0, firstPos));
str = str.slice(firstPos);
}
arr.push(result[0]);
str = str.slice(result[0].length);
result = pat.exec(str);
}
if (str) {
arr.push(str);
}
return arr;
},
_addOutput: function (line) {
if (this.truncate) {
// Only replace single leading linebreak in the line after
// -%> tag -- this is the single, trailing linebreak
// after the tag that the truncation mode replaces
// Handle Win / Unix / old Mac linebreaks -- do the \r\n
// combo first in the regex-or
line = line.replace(/^(?:\r\n|\r|\n)/, '');
this.truncate = false;
}
if (!line) {
return line;
}
// Preserve literal slashes
line = line.replace(/\\/g, '\\\\');
// Convert linebreaks
line = line.replace(/\n/g, '\\n');
line = line.replace(/\r/g, '\\r');
// Escape double-quotes
// - this will be the delimiter during execution
line = line.replace(/"/g, '\\"');
this.source += ' ; __append("' + line + '")' + '\n';
},
scanLine: function (line) {
var self = this;
var d = this.opts.delimiter;
var o = this.opts.openDelimiter;
var c = this.opts.closeDelimiter;
var newLineCount = 0;
newLineCount = (line.split('\n').length - 1);
switch (line) {
case o + d:
case o + d + '_':
this.mode = Template.modes.EVAL;
break;
case o + d + '=':
this.mode = Template.modes.ESCAPED;
break;
case o + d + '-':
this.mode = Template.modes.RAW;
break;
case o + d + '#':
this.mode = Template.modes.COMMENT;
break;
case o + d + d:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
break;
case d + d + c:
this.mode = Template.modes.LITERAL;
this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
break;
case d + c:
case '-' + d + c:
case '_' + d + c:
if (this.mode == Template.modes.LITERAL) {
this._addOutput(line);
}
this.mode = null;
this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
break;
default:
// In script mode, depends on type of tag
if (this.mode) {
// If '//' is found without a line break, add a line break.
switch (this.mode) {
case Template.modes.EVAL:
case Template.modes.ESCAPED:
case Template.modes.RAW:
if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
line += '\n';
}
}
switch (this.mode) {
// Just executing code
case Template.modes.EVAL:
this.source += ' ; ' + line + '\n';
break;
// Exec, esc, and output
case Template.modes.ESCAPED:
this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
break;
// Exec and output
case Template.modes.RAW:
this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
break;
case Template.modes.COMMENT:
// Do nothing
break;
// Literal <%% mode, append as raw output
case Template.modes.LITERAL:
this._addOutput(line);
break;
}
}
// In string mode, just add the output
else {
this._addOutput(line);
}
}
if (self.opts.compileDebug && newLineCount) {
this.currentLine += newLineCount;
this.source += ' ; __line = ' + this.currentLine + '\n';
}
}
};
/**
* Escape characters reserved in XML.
*
* This is simply an export of {@link module:utils.escapeXML}.
*
* If `markup` is `undefined` or `null`, the empty string is returned.
*
* @param {String} markup Input string
* @return {String} Escaped string
* @public
* @func
* */
exports.escapeXML = utils.escapeXML;
/**
* Express.js support.
*
* This is an alias for {@link module:ejs.renderFile}, in order to support
* Express.js out-of-the-box.
*
* @func
*/
exports.__express = exports.renderFile;
/**
* Version of EJS.
*
* @readonly
* @type {String}
* @public
*/
exports.VERSION = _VERSION_STRING;
/**
* Name for detection of EJS.
*
* @readonly
* @type {String}
* @public
*/
exports.name = _NAME;
/* istanbul ignore if */
if (typeof window != 'undefined') {
window.ejs = exports;
}
}, { "../package.json": 6, "./utils": 2, "fs": 3, "path": 4 }], 2: [function (require, module, exports) {
/*
* EJS Embedded JavaScript templates
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/**
* Private utility functions
* @module utils
* @private
*/
'use strict';
var regExpChars = /[|\\{}()[\]^$+*?.]/g;
/**
* Escape characters reserved in regular expressions.
*
* If `string` is `undefined` or `null`, the empty string is returned.
*
* @param {String} string Input string
* @return {String} Escaped string
* @static
* @private
*/
exports.escapeRegExpChars = function (string) {
// istanbul ignore if
if (!string) {
return '';
}
return String(string).replace(regExpChars, '\\$&');
};
var _ENCODE_HTML_RULES = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
var _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
}
/**
* Stringified version of constants used by {@link module:utils.escapeXML}.
*
* It is used in the process of generating {@link ClientFunction}s.
*
* @readonly
* @type {String}
*/
var escapeFuncStr =
'var _ENCODE_HTML_RULES = {\n'
+ ' "&": "&"\n'
+ ' , "<": "<"\n'
+ ' , ">": ">"\n'
+ ' , \'"\': """\n'
+ ' , "\'": "'"\n'
+ ' }\n'
+ ' , _MATCH_HTML = /[&<>\'"]/g;\n'
+ 'function encode_char(c) {\n'
+ ' return _ENCODE_HTML_RULES[c] || c;\n'
+ '};\n';
/**
* Escape characters reserved in XML.
*
* If `markup` is `undefined` or `null`, the empty string is returned.
*
* @implements {EscapeCallback}
* @param {String} markup Input string
* @return {String} Escaped string
* @static
* @private
*/
exports.escapeXML = function (markup) {
return markup == undefined
? ''
: String(markup)
.replace(_MATCH_HTML, encode_char);
};
exports.escapeXML.toString = function () {
return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
};
/**
* Naive copy of properties from one object to another.
* Does not recurse into non-scalar properties
* Does not check to see if the property has a value before copying
*
* @param {Object} to Destination object
* @param {Object} from Source object
* @return {Object} Destination object
* @static
* @private
*/
exports.shallowCopy = function (to, from) {
from = from || {};
for (var p in from) {
to[p] = from[p];
}
return to;
};
/**
* Naive copy of a list of key names, from one object to another.
* Only copies property if it is actually defined
* Does not recurse into non-scalar properties
*
* @param {Object} to Destination object
* @param {Object} from Source object
* @param {Array} list List of properties to copy
* @return {Object} Destination object
* @static
* @private
*/
exports.shallowCopyFromList = function (to, from, list) {
for (var i = 0; i < list.length; i++) {
var p = list[i];
if (typeof from[p] != 'undefined') {
to[p] = from[p];
}
}
return to;
};
/**
* Simple in-process cache implementation. Does not implement limits of any
* sort.
*
* @implements {Cache}
* @static
* @private
*/
exports.cache = {
_data: {},
set: function (key, val) {
this._data[key] = val;
},
get: function (key) {
return this._data[key];
},
remove: function (key) {
delete this._data[key];
},
reset: function () {
this._data = {};
}
};
/**
* Transforms hyphen case variable into camel case.
*
* @param {String} string Hyphen case string
* @return {String} Camel case string
* @static
* @private
*/
exports.hyphenToCamel = function (str) {
return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
};
}, {}], 3: [function (require, module, exports) {
}, {}], 4: [function (require, module, exports) {
(function (process) {
// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
// backported and transplited with Babel, with backwards-compat fixes
// 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.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// path.resolve([from ...], to)
// posix version
exports.resolve = function () {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// 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 = normalizeArray(filter(resolvedPath.split('/'), function (p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function (path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function (p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function (path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function () {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function (p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function (from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function (path) {
if (typeof path !== 'string') path = 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 '//';
// Backwards-compat fix:
return '/';
}
return path.slice(0, end);
};
function basename(path) {
if (typeof path !== 'string') path = path + '';
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
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);
}
// Uses a mixed approach for backwards-compatibility, as ext behavior changed
// in new Node.js versions, so only basename() above is backported here
exports.basename = function (path, ext) {
var f = basename(path);
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function (path) {
if (typeof path !== 'string') path = 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);
};
function filter(xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this, require('_process'))
}, { "_process": 5 }], 5: [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; };
}, {}], 6: [function (require, module, exports) {
module.exports = {
"name": "ejs",
"description": "Embedded JavaScript templates",
"keywords": [
"template",
"engine",
"ejs"
],
"version": "3.1.6",
"author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
"license": "Apache-2.0",
"bin": {
"ejs": "./bin/cli.js"
},
"main": "./lib/ejs.js",
"jsdelivr": "ejs.min.js",
"unpkg": "ejs.min.js",
"repository": {
"type": "git",
"url": "git://github.com/mde/ejs.git"
},
"bugs": "https://github.com/mde/ejs/issues",
"homepage": "https://github.com/mde/ejs",
"dependencies": {
"jake": "^10.6.1"
},
"devDependencies": {
"browserify": "^16.5.1",
"eslint": "^6.8.0",
"git-directory-deploy": "^1.5.1",
"jsdoc": "^3.6.4",
"lru-cache": "^4.0.1",
"mocha": "^7.1.1",
"uglify-js": "^3.3.16"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
}
}
}, {}]
}, {}, [1])(1)
});
//Included:lib/006.castelog.part.js
//Included:lib/009.vue-router-v3.5.1.part.js
/*!
* vue-router v3.5.1
* (c) 2021 Evan You
* @license MIT
*/
(function (factory) {
// Only navigators:
if (typeof window === 'undefined') return;
// General boilerplate:
if (typeof window !== "undefined") {
if ("VueRouter" in window) return window.VueRouter;
}
if (typeof global !== "undefined") {
if ("VueRouter" in global) return global.VueRouter;
}
const output = factory();
if (typeof module === 'object' && typeof module.exports === 'object') module.exports = output;
if (typeof define === 'function' && define.amd) define([], factory);
if (typeof exports === 'object') exports["VueRouter"] = output;
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') window.VueRouter = output;
}
if (typeof global !== "undefined") {
if (typeof global !== 'undefined') global.VueRouter = output;
}
return output;
}(function () {
'use strict';
function assert(condition, message) {
if (!condition) {
throw new Error(("[vue-router] " + message))
}
}
function warn(condition, message) {
if (!condition) {
typeof console !== 'undefined' && console.warn(("[vue-router] " + message));
}
}
function extend(a, b) {
for (var key in b) {
a[key] = b[key];
}
return a
}
/* */
var encodeReserveRE = /[!'()*]/g;
var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
var commaRE = /%2C/g;
// fixed encodeURIComponent which is more conformant to RFC3986:
// - escapes [!'()*]
// - preserve commas
var encode = function (str) {
return encodeURIComponent(str)
.replace(encodeReserveRE, encodeReserveReplacer)
.replace(commaRE, ',');
};
function decode(str) {
try {
return decodeURIComponent(str)
} catch (err) {
{
warn(false, ("Error decoding \"" + str + "\". Leaving it intact."));
}
}
return str
}
function resolveQuery(
query,
extraQuery,
_parseQuery
) {
if (extraQuery === void 0) extraQuery = {};
var parse = _parseQuery || parseQuery;
var parsedQuery;
try {
parsedQuery = parse(query || '');
} catch (e) {
warn(false, e.message);
parsedQuery = {};
}
for (var key in extraQuery) {
var value = extraQuery[key];
parsedQuery[key] = Array.isArray(value)
? value.map(castQueryParamValue)
: castQueryParamValue(value);
}
return parsedQuery
}
var castQueryParamValue = function (value) { return (value == null || typeof value === 'object' ? value : String(value)); };
function parseQuery(query) {
var res = {};
query = query.trim().replace(/^(\?|#|&)/, '');
if (!query) {
return res
}
query.split('&').forEach(function (param) {
var parts = param.replace(/\+/g, ' ').split('=');
var key = decode(parts.shift());
var val = parts.length > 0 ? decode(parts.join('=')) : null;
if (res[key] === undefined) {
res[key] = val;
} else if (Array.isArray(res[key])) {
res[key].push(val);
} else {
res[key] = [res[key], val];
}
});
return res
}
function stringifyQuery(obj) {
var res = obj
? Object.keys(obj)
.map(function (key) {
var val = obj[key];
if (val === undefined) {
return ''
}
if (val === null) {
return encode(key)
}
if (Array.isArray(val)) {
var result = [];
val.forEach(function (val2) {
if (val2 === undefined) {
return
}
if (val2 === null) {
result.push(encode(key));
} else {
result.push(encode(key) + '=' + encode(val2));
}
});
return result.join('&')
}
return encode(key) + '=' + encode(val)
})
.filter(function (x) { return x.length > 0; })
.join('&')
: null;
return res ? ("?" + res) : ''
}
/* */
var trailingSlashRE = /\/?$/;
function createRoute(
record,
location,
redirectedFrom,
router
) {
var stringifyQuery = router && router.options.stringifyQuery;
var query = location.query || {};
try {
query = clone(query);
} catch (e) { }
var route = {
name: location.name || (record && record.name),
meta: (record && record.meta) || {},
path: location.path || '/',
hash: location.hash || '',
query: query,
params: location.params || {},
fullPath: getFullPath(location, stringifyQuery),
matched: record ? formatMatch(record) : []
};
if (redirectedFrom) {
route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
}
return Object.freeze(route)
}
function clone(value) {
if (Array.isArray(value)) {
return value.map(clone)
} else if (value && typeof value === 'object') {
var res = {};
for (var key in value) {
res[key] = clone(value[key]);
}
return res
} else {
return value
}
}
// the starting route that represents the initial state
var START = createRoute(null, {
path: '/'
});
function formatMatch(record) {
var res = [];
while (record) {
res.unshift(record);
record = record.parent;
}
return res
}
function getFullPath(
ref,
_stringifyQuery
) {
var path = ref.path;
var query = ref.query; if (query === void 0) query = {};
var hash = ref.hash; if (hash === void 0) hash = '';
var stringify = _stringifyQuery || stringifyQuery;
return (path || '/') + stringify(query) + hash
}
function isSameRoute(a, b, onlyPath) {
if (b === START) {
return a === b
} else if (!b) {
return false
} else if (a.path && b.path) {
return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
a.hash === b.hash &&
isObjectEqual(a.query, b.query))
} else if (a.name && b.name) {
return (
a.name === b.name &&
(onlyPath || (
a.hash === b.hash &&
isObjectEqual(a.query, b.query) &&
isObjectEqual(a.params, b.params))
)
)
} else {
return false
}
}
function isObjectEqual(a, b) {
if (a === void 0) a = {};
if (b === void 0) b = {};
// handle null value #1566
if (!a || !b) { return a === b }
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
if (aKeys.length !== bKeys.length) {
return false
}
return aKeys.every(function (key, i) {
var aVal = a[key];
var bKey = bKeys[i];
if (bKey !== key) { return false }
var bVal = b[key];
// query values can be null and undefined
if (aVal == null || bVal == null) { return aVal === bVal }
// check nested equality
if (typeof aVal === 'object' && typeof bVal === 'object') {
return isObjectEqual(aVal, bVal)
}
return String(aVal) === String(bVal)
})
}
function isIncludedRoute(current, target) {
return (
current.path.replace(trailingSlashRE, '/').indexOf(
target.path.replace(trailingSlashRE, '/')
) === 0 &&
(!target.hash || current.hash === target.hash) &&
queryIncludes(current.query, target.query)
)
}
function queryIncludes(current, target) {
for (var key in target) {
if (!(key in current)) {
return false
}
}
return true
}
function handleRouteEntered(route) {
for (var i = 0; i < route.matched.length; i++) {
var record = route.matched[i];
for (var name in record.instances) {
var instance = record.instances[name];
var cbs = record.enteredCbs[name];
if (!instance || !cbs) { continue }
delete record.enteredCbs[name];
for (var i$1 = 0; i$1 < cbs.length; i$1++) {
if (!instance._isBeingDestroyed) { cbs[i$1](instance); }
}
}
}
}
var View = {
name: 'RouterView',
functional: true,
props: {
name: {
type: String,
default: 'default'
}
},
render: function render(_, ref) {
var props = ref.props;
var children = ref.children;
var parent = ref.parent;
var data = ref.data;
// used by devtools to display a router-view badge
data.routerView = true;
// directly use parent context's createElement() function
// so that components rendered by router-view can resolve named slots
var h = parent.$createElement;
var name = props.name;
var route = parent.$route;
var cache = parent._routerViewCache || (parent._routerViewCache = {});
// determine current view depth, also check to see if the tree
// has been toggled inactive but kept-alive.
var depth = 0;
var inactive = false;
while (parent && parent._routerRoot !== parent) {
var vnodeData = parent.$vnode ? parent.$vnode.data : {};
if (vnodeData.routerView) {
depth++;
}
if (vnodeData.keepAlive && parent._directInactive && parent._inactive) {
inactive = true;
}
parent = parent.$parent;
}
data.routerViewDepth = depth;
// render previous view if the tree is inactive and kept-alive
if (inactive) {
var cachedData = cache[name];
var cachedComponent = cachedData && cachedData.component;
if (cachedComponent) {
// #2301
// pass props
if (cachedData.configProps) {
fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
}
return h(cachedComponent, data, children)
} else {
// render previous empty view
return h()
}
}
var matched = route.matched[depth];
var component = matched && matched.components[name];
// render empty node if no matched route or no config component
if (!matched || !component) {
cache[name] = null;
return h()
}
// cache component
cache[name] = { component: component };
// attach instance registration hook
// this will be called in the instance's injected lifecycle hooks
data.registerRouteInstance = function (vm, val) {
// val could be undefined for unregistration
var current = matched.instances[name];
if (
(val && current !== vm) ||
(!val && current === vm)
) {
matched.instances[name] = val;
}
}
// also register instance in prepatch hook
// in case the same component instance is reused across different routes
; (data.hook || (data.hook = {})).prepatch = function (_, vnode) {
matched.instances[name] = vnode.componentInstance;
};
// register instance in init hook
// in case kept-alive component be actived when routes changed
data.hook.init = function (vnode) {
if (vnode.data.keepAlive &&
vnode.componentInstance &&
vnode.componentInstance !== matched.instances[name]
) {
matched.instances[name] = vnode.componentInstance;
}
// if the route transition has already been confirmed then we weren't
// able to call the cbs during confirmation as the component was not
// registered yet, so we call it here.
handleRouteEntered(route);
};
var configProps = matched.props && matched.props[name];
// save route and configProps in cache
if (configProps) {
extend(cache[name], {
route: route,
configProps: configProps
});
fillPropsinData(component, data, route, configProps);
}
return h(component, data, children)
}
};
function fillPropsinData(component, data, route, configProps) {
// resolve props
var propsToPass = data.props = resolveProps(route, configProps);
if (propsToPass) {
// clone to prevent mutation
propsToPass = data.props = extend({}, propsToPass);
// pass non-declared props as attrs
var attrs = data.attrs = data.attrs || {};
for (var key in propsToPass) {
if (!component.props || !(key in component.props)) {
attrs[key] = propsToPass[key];
delete propsToPass[key];
}
}
}
}
function resolveProps(route, config) {
switch (typeof config) {
case 'undefined':
return
case 'object':
return config
case 'function':
return config(route)
case 'boolean':
return config ? route.params : undefined
default:
{
warn(
false,
"props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
"expecting an object, function or boolean."
);
}
}
}
/* */
function resolvePath(
relative,
base,
append
) {
var firstChar = relative.charAt(0);
if (firstChar === '/') {
return relative
}
if (firstChar === '?' || firstChar === '#') {
return base + relative
}
var stack = base.split('/');
// remove trailing segment if:
// - not appending
// - appending to trailing slash (last segment is empty)
if (!append || !stack[stack.length - 1]) {
stack.pop();
}
// resolve relative path
var segments = relative.replace(/^\//, '').split('/');
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment === '..') {
stack.pop();
} else if (segment !== '.') {
stack.push(segment);
}
}
// ensure leading slash
if (stack[0] !== '') {
stack.unshift('');
}
return stack.join('/')
}
function parsePath(path) {
var hash = '';
var query = '';
var hashIndex = path.indexOf('#');
if (hashIndex >= 0) {
hash = path.slice(hashIndex);
path = path.slice(0, hashIndex);
}
var queryIndex = path.indexOf('?');
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1);
path = path.slice(0, queryIndex);
}
return {
path: path,
query: query,
hash: hash
}
}
function cleanPath(path) {
return path.replace(/\/\//g, '/')
}
var isarray = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/**
* Expose `pathToRegexp`.
*/
var pathToRegexp_1 = pathToRegexp;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g');
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse(str, options) {
var tokens = [];
var key = 0;
var index = 0;
var path = '';
var defaultDelimiter = options && options.delimiter || '/';
var res;
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0];
var escaped = res[1];
var offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
continue
}
var next = str[index];
var prefix = res[2];
var name = res[3];
var capture = res[4];
var group = res[5];
var modifier = res[6];
var asterisk = res[7];
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
}
var partial = prefix != null && next != null && next !== prefix;
var repeat = modifier === '+' || modifier === '*';
var optional = modifier === '?' || modifier === '*';
var delimiter = res[2] || defaultDelimiter;
var pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
});
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index);
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path);
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile(str, options) {
return tokensToFunction(parse(str, options), options)
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty(str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk(str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens, options) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length);
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
}
}
return function (obj, opts) {
var path = '';
var data = obj || {};
var options = opts || {};
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue
}
var value = data[token.name];
var segment;
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix;
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (isarray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j]);
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment;
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value);
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment;
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup(group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys(re, keys) {
re.keys = keys;
return re
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags(options) {
return options && options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp(path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null
});
}
}
return attachKeys(path, keys)
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp(path, keys, options) {
var parts = [];
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
return attachKeys(regexp, keys)
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp(path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp(tokens, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var route = '';
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
} else {
var prefix = escapeString(token.prefix);
var capture = '(?:' + token.pattern + ')';
keys.push(token);
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*';
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?';
} else {
capture = prefix + '(' + capture + ')?';
}
} else {
capture = prefix + '(' + capture + ')';
}
route += capture;
}
}
var delimiter = escapeString(options.delimiter || '/');
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
}
if (end) {
route += '$';
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
}
return attachKeys(new RegExp('^' + route, flags(options)), keys)
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp(path, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */ (keys || options);
keys = [];
}
options = options || {};
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */(keys))
}
if (isarray(path)) {
return arrayToRegexp(/** @type {!Array} */(path), /** @type {!Array} */(keys), options)
}
return stringToRegexp(/** @type {string} */(path), /** @type {!Array} */(keys), options)
}
pathToRegexp_1.parse = parse_1;
pathToRegexp_1.compile = compile_1;
pathToRegexp_1.tokensToFunction = tokensToFunction_1;
pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
/* */
// $flow-disable-line
var regexpCompileCache = Object.create(null);
function fillParams(
path,
params,
routeMsg
) {
params = params || {};
try {
var filler =
regexpCompileCache[path] ||
(regexpCompileCache[path] = pathToRegexp_1.compile(path));
// Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
// and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
if (typeof params.pathMatch === 'string') { params[0] = params.pathMatch; }
return filler(params, { pretty: true })
} catch (e) {
{
// Fix #3072 no warn if `pathMatch` is string
warn(typeof params.pathMatch === 'string', ("missing param for " + routeMsg + ": " + (e.message)));
}
return ''
} finally {
// delete the 0 if it was added
delete params[0];
}
}
/* */
function normalizeLocation(
raw,
current,
append,
router
) {
var next = typeof raw === 'string' ? { path: raw } : raw;
// named target
if (next._normalized) {
return next
} else if (next.name) {
next = extend({}, raw);
var params = next.params;
if (params && typeof params === 'object') {
next.params = extend({}, params);
}
return next
}
// relative params
if (!next.path && next.params && current) {
next = extend({}, next);
next._normalized = true;
var params$1 = extend(extend({}, current.params), next.params);
if (current.name) {
next.name = current.name;
next.params = params$1;
} else if (current.matched.length) {
var rawPath = current.matched[current.matched.length - 1].path;
next.path = fillParams(rawPath, params$1, ("path " + (current.path)));
} else {
warn(false, "relative params navigation requires a current route.");
}
return next
}
var parsedPath = parsePath(next.path || '');
var basePath = (current && current.path) || '/';
var path = parsedPath.path
? resolvePath(parsedPath.path, basePath, append || next.append)
: basePath;
var query = resolveQuery(
parsedPath.query,
next.query,
router && router.options.parseQuery
);
var hash = next.hash || parsedPath.hash;
if (hash && hash.charAt(0) !== '#') {
hash = "#" + hash;
}
return {
_normalized: true,
path: path,
query: query,
hash: hash
}
}
/* */
// work around weird flow bug
var toTypes = [String, Object];
var eventTypes = [String, Array];
var noop = function () { };
var warnedCustomSlot;
var warnedTagProp;
var warnedEventProp;
var Link = {
name: 'RouterLink',
props: {
to: {
type: toTypes,
required: true
},
tag: {
type: String,
default: 'a'
},
custom: Boolean,
exact: Boolean,
exactPath: Boolean,
append: Boolean,
replace: Boolean,
activeClass: String,
exactActiveClass: String,
ariaCurrentValue: {
type: String,
default: 'page'
},
event: {
type: eventTypes,
default: 'click'
}
},
render: function render(h) {
var this$1 = this;
var router = this.$router;
var current = this.$route;
var ref = router.resolve(
this.to,
current,
this.append
);
var location = ref.location;
var route = ref.route;
var href = ref.href;
var classes = {};
var globalActiveClass = router.options.linkActiveClass;
var globalExactActiveClass = router.options.linkExactActiveClass;
// Support global empty active class
var activeClassFallback =
globalActiveClass == null ? 'router-link-active' : globalActiveClass;
var exactActiveClassFallback =
globalExactActiveClass == null
? 'router-link-exact-active'
: globalExactActiveClass;
var activeClass =
this.activeClass == null ? activeClassFallback : this.activeClass;
var exactActiveClass =
this.exactActiveClass == null
? exactActiveClassFallback
: this.exactActiveClass;
var compareTarget = route.redirectedFrom
? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
: route;
classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
classes[activeClass] = this.exact || this.exactPath
? classes[exactActiveClass]
: isIncludedRoute(current, compareTarget);
var ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
var handler = function (e) {
if (guardEvent(e)) {
if (this$1.replace) {
router.replace(location, noop);
} else {
router.push(location, noop);
}
}
};
var on = { click: guardEvent };
if (Array.isArray(this.event)) {
this.event.forEach(function (e) {
on[e] = handler;
});
} else {
on[this.event] = handler;
}
var data = { class: classes };
var scopedSlot =
!this.$scopedSlots.$hasNormal &&
this.$scopedSlots.default &&
this.$scopedSlots.default({
href: href,
route: route,
navigate: handler,
isActive: classes[activeClass],
isExactActive: classes[exactActiveClass]
});
if (scopedSlot) {
if (!this.custom) {
!warnedCustomSlot && warn(false, 'In Vue Router 4, the v-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link v-slot="{ navigate, href }" custom></router-link>\n');
warnedCustomSlot = true;
}
if (scopedSlot.length === 1) {
return scopedSlot[0]
} else if (scopedSlot.length > 1 || !scopedSlot.length) {
{
warn(
false,
("<router-link> with to=\"" + (this.to) + "\" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.")
);
}
return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
}
}
{
if ('tag' in this.$options.propsData && !warnedTagProp) {
warn(
false,
"<router-link>'s tag prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
);
warnedTagProp = true;
}
if ('event' in this.$options.propsData && !warnedEventProp) {
warn(
false,
"<router-link>'s event prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
);
warnedEventProp = true;
}
}
if (this.tag === 'a') {
data.on = on;
data.attrs = { href: href, 'aria-current': ariaCurrentValue };
} else {
// find the first <a> child and apply listener and href
var a = findAnchor(this.$slots.default);
if (a) {
// in case the <a> is a static node
a.isStatic = false;
var aData = (a.data = extend({}, a.data));
aData.on = aData.on || {};
// transform existing events in both objects into arrays so we can push later
for (var event in aData.on) {
var handler$1 = aData.on[event];
if (event in on) {
aData.on[event] = Array.isArray(handler$1) ? handler$1 : [handler$1];
}
}
// append new listeners for router-link
for (var event$1 in on) {
if (event$1 in aData.on) {
// on[event] is always a function
aData.on[event$1].push(on[event$1]);
} else {
aData.on[event$1] = handler;
}
}
var aAttrs = (a.data.attrs = extend({}, a.data.attrs));
aAttrs.href = href;
aAttrs['aria-current'] = ariaCurrentValue;
} else {
// doesn't have <a> child, apply listener to self
data.on = on;
}
}
return h(this.tag, data, this.$slots.default)
}
};
function guardEvent(e) {
// don't redirect with control keys
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
// don't redirect when preventDefault called
if (e.defaultPrevented) { return }
// don't redirect on right click
if (e.button !== undefined && e.button !== 0) { return }
// don't redirect if `target="_blank"`
if (e.currentTarget && e.currentTarget.getAttribute) {
var target = e.currentTarget.getAttribute('target');
if (/\b_blank\b/i.test(target)) { return }
}
// this may be a Weex event which doesn't have this method
if (e.preventDefault) {
e.preventDefault();
}
return true
}
function findAnchor(children) {
if (children) {
var child;
for (var i = 0; i < children.length; i++) {
child = children[i];
if (child.tag === 'a') {
return child
}
if (child.children && (child = findAnchor(child.children))) {
return child
}
}
}
}
var _Vue;
function install(Vue) {
if (install.installed && _Vue === Vue) { return }
install.installed = true;
_Vue = Vue;
var isDef = function (v) { return v !== undefined; };
var registerInstance = function (vm, callVal) {
var i = vm.$options._parentVnode;
if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
i(vm, callVal);
}
};
Vue.mixin({
beforeCreate: function beforeCreate() {
if (isDef(this.$options.router)) {
this._routerRoot = this;
this._router = this.$options.router;
this._router.init(this);
Vue.util.defineReactive(this, '_route', this._router.history.current);
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
}
registerInstance(this, this);
},
destroyed: function destroyed() {
registerInstance(this);
}
});
Object.defineProperty(Vue.prototype, '$router', {
get: function get() { return this._routerRoot._router }
});
Object.defineProperty(Vue.prototype, '$route', {
get: function get() { return this._routerRoot._route }
});
Vue.component('RouterView', View);
Vue.component('RouterLink', Link);
var strats = Vue.config.optionMergeStrategies;
// use the same hook merging strategy for route hooks
strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
}
/* */
var inBrowser = typeof window !== 'undefined';
/* */
function createRouteMap(
routes,
oldPathList,
oldPathMap,
oldNameMap,
parentRoute
) {
// the path list is used to control path matching priority
var pathList = oldPathList || [];
// $flow-disable-line
var pathMap = oldPathMap || Object.create(null);
// $flow-disable-line
var nameMap = oldNameMap || Object.create(null);
routes.forEach(function (route) {
addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
});
// ensure wildcard routes are always at the end
for (var i = 0, l = pathList.length; i < l; i++) {
if (pathList[i] === '*') {
pathList.push(pathList.splice(i, 1)[0]);
l--;
i--;
}
}
{
// warn if routes do not include leading slashes
var found = pathList
// check for missing leading slash
.filter(function (path) { return path && path.charAt(0) !== '*' && path.charAt(0) !== '/'; });
if (found.length > 0) {
var pathNames = found.map(function (path) { return ("- " + path); }).join('\n');
warn(false, ("Non-nested routes must include a leading slash character. Fix the following routes: \n" + pathNames));
}
}
return {
pathList: pathList,
pathMap: pathMap,
nameMap: nameMap
}
}
function addRouteRecord(
pathList,
pathMap,
nameMap,
route,
parent,
matchAs
) {
var path = route.path;
var name = route.name;
{
assert(path != null, "\"path\" is required in a route configuration.");
assert(
typeof route.component !== 'string',
"route config \"component\" for path: " + (String(
path || name
)) + " cannot be a " + "string id. Use an actual component instead."
);
warn(
// eslint-disable-next-line no-control-regex
!/[^\u0000-\u007F]+/.test(path),
"Route with path \"" + path + "\" contains unencoded characters, make sure " +
"your path is correctly encoded before passing it to the router. Use " +
"encodeURI to encode static segments of your path."
);
}
var pathToRegexpOptions =
route.pathToRegexpOptions || {};
var normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
if (typeof route.caseSensitive === 'boolean') {
pathToRegexpOptions.sensitive = route.caseSensitive;
}
var record = {
path: normalizedPath,
regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
components: route.components || { default: route.component },
alias: route.alias
? typeof route.alias === 'string'
? [route.alias]
: route.alias
: [],
instances: {},
enteredCbs: {},
name: name,
parent: parent,
matchAs: matchAs,
redirect: route.redirect,
beforeEnter: route.beforeEnter,
meta: route.meta || {},
props:
route.props == null
? {}
: route.components
? route.props
: { default: route.props }
};
if (route.children) {
// Warn if route is named, does not redirect and has a default child route.
// If users navigate to this route by name, the default child will
// not be rendered (GH Issue #629)
{
if (
route.name &&
!route.redirect &&
route.children.some(function (child) { return /^\/?$/.test(child.path); })
) {
warn(
false,
"Named Route '" + (route.name) + "' has a default child route. " +
"When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
"the default child route will not be rendered. Remove the name from " +
"this route and use the name of the default child route for named " +
"links instead."
);
}
}
route.children.forEach(function (child) {
var childMatchAs = matchAs
? cleanPath((matchAs + "/" + (child.path)))
: undefined;
addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
});
}
if (!pathMap[record.path]) {
pathList.push(record.path);
pathMap[record.path] = record;
}
if (route.alias !== undefined) {
var aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
for (var i = 0; i < aliases.length; ++i) {
var alias = aliases[i];
if (alias === path) {
warn(
false,
("Found an alias with the same value as the path: \"" + path + "\". You have to remove that alias. It will be ignored in development.")
);
// skip in dev to make it work
continue
}
var aliasRoute = {
path: alias,
children: route.children
};
addRouteRecord(
pathList,
pathMap,
nameMap,
aliasRoute,
parent,
record.path || '/' // matchAs
);
}
}
if (name) {
if (!nameMap[name]) {
nameMap[name] = record;
} else if (!matchAs) {
warn(
false,
"Duplicate named routes definition: " +
"{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
);
}
}
}
function compileRouteRegex(
path,
pathToRegexpOptions
) {
var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
{
var keys = Object.create(null);
regex.keys.forEach(function (key) {
warn(
!keys[key.name],
("Duplicate param keys in route with path: \"" + path + "\"")
);
keys[key.name] = true;
});
}
return regex
}
function normalizePath(
path,
parent,
strict
) {
if (!strict) { path = path.replace(/\/$/, ''); }
if (path[0] === '/') { return path }
if (parent == null) { return path }
return cleanPath(((parent.path) + "/" + path))
}
/* */
function createMatcher(
routes,
router
) {
var ref = createRouteMap(routes);
var pathList = ref.pathList;
var pathMap = ref.pathMap;
var nameMap = ref.nameMap;
function addRoutes(routes) {
createRouteMap(routes, pathList, pathMap, nameMap);
}
function addRoute(parentOrRoute, route) {
var parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
// $flow-disable-line
createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
// add aliases of parent
if (parent) {
createRouteMap(
// $flow-disable-line route is defined if parent is
parent.alias.map(function (alias) { return ({ path: alias, children: [route] }); }),
pathList,
pathMap,
nameMap,
parent
);
}
}
function getRoutes() {
return pathList.map(function (path) { return pathMap[path]; })
}
function match(
raw,
currentRoute,
redirectedFrom
) {
var location = normalizeLocation(raw, currentRoute, false, router);
var name = location.name;
if (name) {
var record = nameMap[name];
{
warn(record, ("Route with name '" + name + "' does not exist"));
}
if (!record) { return _createRoute(null, location) }
var paramNames = record.regex.keys
.filter(function (key) { return !key.optional; })
.map(function (key) { return key.name; });
if (typeof location.params !== 'object') {
location.params = {};
}
if (currentRoute && typeof currentRoute.params === 'object') {
for (var key in currentRoute.params) {
if (!(key in location.params) && paramNames.indexOf(key) > -1) {
location.params[key] = currentRoute.params[key];
}
}
}
location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
return _createRoute(record, location, redirectedFrom)
} else if (location.path) {
location.params = {};
for (var i = 0; i < pathList.length; i++) {
var path = pathList[i];
var record$1 = pathMap[path];
if (matchRoute(record$1.regex, location.path, location.params)) {
return _createRoute(record$1, location, redirectedFrom)
}
}
}
// no match
return _createRoute(null, location)
}
function redirect(
record,
location
) {
var originalRedirect = record.redirect;
var redirect = typeof originalRedirect === 'function'
? originalRedirect(createRoute(record, location, null, router))
: originalRedirect;
if (typeof redirect === 'string') {
redirect = { path: redirect };
}
if (!redirect || typeof redirect !== 'object') {
{
warn(
false, ("invalid redirect option: " + (JSON.stringify(redirect)))
);
}
return _createRoute(null, location)
}
var re = redirect;
var name = re.name;
var path = re.path;
var query = location.query;
var hash = location.hash;
var params = location.params;
query = re.hasOwnProperty('query') ? re.query : query;
hash = re.hasOwnProperty('hash') ? re.hash : hash;
params = re.hasOwnProperty('params') ? re.params : params;
if (name) {
// resolved named direct
var targetRecord = nameMap[name];
{
assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
}
return match({
_normalized: true,
name: name,
query: query,
hash: hash,
params: params
}, undefined, location)
} else if (path) {
// 1. resolve relative redirect
var rawPath = resolveRecordPath(path, record);
// 2. resolve params
var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
// 3. rematch with existing query and hash
return match({
_normalized: true,
path: resolvedPath,
query: query,
hash: hash
}, undefined, location)
} else {
{
warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
}
return _createRoute(null, location)
}
}
function alias(
record,
location,
matchAs
) {
var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
var aliasedMatch = match({
_normalized: true,
path: aliasedPath
});
if (aliasedMatch) {
var matched = aliasedMatch.matched;
var aliasedRecord = matched[matched.length - 1];
location.params = aliasedMatch.params;
return _createRoute(aliasedRecord, location)
}
return _createRoute(null, location)
}
function _createRoute(
record,
location,
redirectedFrom
) {
if (record && record.redirect) {
return redirect(record, redirectedFrom || location)
}
if (record && record.matchAs) {
return alias(record, location, record.matchAs)
}
return createRoute(record, location, redirectedFrom, router)
}
return {
match: match,
addRoute: addRoute,
getRoutes: getRoutes,
addRoutes: addRoutes
}
}
function matchRoute(
regex,
path,
params
) {
var m = path.match(regex);
if (!m) {
return false
} else if (!params) {
return true
}
for (var i = 1, len = m.length; i < len; ++i) {
var key = regex.keys[i - 1];
if (key) {
// Fix #1994: using * with props: true generates a param named 0
params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
}
}
return true
}
function resolveRecordPath(path, record) {
return resolvePath(path, record.parent ? record.parent.path : '/', true)
}
/* */
// use User Timing api (if present) for more accurate key precision
var Time =
inBrowser && window.performance && window.performance.now
? window.performance
: Date;
function genStateKey() {
return Time.now().toFixed(3)
}
var _key = genStateKey();
function getStateKey() {
return _key
}
function setStateKey(key) {
return (_key = key)
}
/* */
var positionStore = Object.create(null);
function setupScroll() {
// Prevent browser scroll behavior on History popstate
if ('scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
// Fix for #1585 for Firefox
// Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
// Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
// window.location.protocol + '//' + window.location.host
// location.host contains the port and location.hostname doesn't
var protocolAndPath = window.location.protocol + '//' + window.location.host;
var absolutePath = window.location.href.replace(protocolAndPath, '');
// preserve existing history state as it could be overriden by the user
var stateCopy = extend({}, window.history.state);
stateCopy.key = getStateKey();
window.history.replaceState(stateCopy, '', absolutePath);
window.addEventListener('popstate', handlePopState);
return function () {
window.removeEventListener('popstate', handlePopState);
}
}
function handleScroll(
router,
to,
from,
isPop
) {
if (!router.app) {
return
}
var behavior = router.options.scrollBehavior;
if (!behavior) {
return
}
{
assert(typeof behavior === 'function', "scrollBehavior must be a function");
}
// wait until re-render finishes before scrolling
router.app.$nextTick(function () {
var position = getScrollPosition();
var shouldScroll = behavior.call(
router,
to,
from,
isPop ? position : null
);
if (!shouldScroll) {
return
}
if (typeof shouldScroll.then === 'function') {
shouldScroll
.then(function (shouldScroll) {
scrollToPosition((shouldScroll), position);
})
.catch(function (err) {
{
assert(false, err.toString());
}
});
} else {
scrollToPosition(shouldScroll, position);
}
});
}
function saveScrollPosition() {
var key = getStateKey();
if (key) {
positionStore[key] = {
x: window.pageXOffset,
y: window.pageYOffset
};
}
}
function handlePopState(e) {
saveScrollPosition();
if (e.state && e.state.key) {
setStateKey(e.state.key);
}
}
function getScrollPosition() {
var key = getStateKey();
if (key) {
return positionStore[key]
}
}
function getElementPosition(el, offset) {
var docEl = document.documentElement;
var docRect = docEl.getBoundingClientRect();
var elRect = el.getBoundingClientRect();
return {
x: elRect.left - docRect.left - offset.x,
y: elRect.top - docRect.top - offset.y
}
}
function isValidPosition(obj) {
return isNumber(obj.x) || isNumber(obj.y)
}
function normalizePosition(obj) {
return {
x: isNumber(obj.x) ? obj.x : window.pageXOffset,
y: isNumber(obj.y) ? obj.y : window.pageYOffset
}
}
function normalizeOffset(obj) {
return {
x: isNumber(obj.x) ? obj.x : 0,
y: isNumber(obj.y) ? obj.y : 0
}
}
function isNumber(v) {
return typeof v === 'number'
}
var hashStartsWithNumberRE = /^#\d/;
function scrollToPosition(shouldScroll, position) {
var isObject = typeof shouldScroll === 'object';
if (isObject && typeof shouldScroll.selector === 'string') {
// getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
// but at the same time, it doesn't make much sense to select an element with an id and an extra selector
var el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
: document.querySelector(shouldScroll.selector);
if (el) {
var offset =
shouldScroll.offset && typeof shouldScroll.offset === 'object'
? shouldScroll.offset
: {};
offset = normalizeOffset(offset);
position = getElementPosition(el, offset);
} else if (isValidPosition(shouldScroll)) {
position = normalizePosition(shouldScroll);
}
} else if (isObject && isValidPosition(shouldScroll)) {
position = normalizePosition(shouldScroll);
}
if (position) {
// $flow-disable-line
if ('scrollBehavior' in document.documentElement.style) {
window.scrollTo({
left: position.x,
top: position.y,
// $flow-disable-line
behavior: shouldScroll.behavior
});
} else {
window.scrollTo(position.x, position.y);
}
}
}
/* */
var supportsPushState =
inBrowser &&
(function () {
var ua = window.navigator.userAgent;
if (
(ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
ua.indexOf('Mobile Safari') !== -1 &&
ua.indexOf('Chrome') === -1 &&
ua.indexOf('Windows Phone') === -1
) {
return false
}
return window.history && typeof window.history.pushState === 'function'
})();
function pushState(url, replace) {
saveScrollPosition();
// try...catch the pushState call to get around Safari
// DOM Exception 18 where it limits to 100 pushState calls
var history = window.history;
try {
if (replace) {
// preserve existing history state as it could be overriden by the user
var stateCopy = extend({}, history.state);
stateCopy.key = getStateKey();
history.replaceState(stateCopy, '', url);
} else {
history.pushState({ key: setStateKey(genStateKey()) }, '', url);
}
} catch (e) {
window.location[replace ? 'replace' : 'assign'](url);
}
}
function replaceState(url) {
pushState(url, true);
}
/* */
function runQueue(queue, fn, cb) {
var step = function (index) {
if (index >= queue.length) {
cb();
} else {
if (queue[index]) {
fn(queue[index], function () {
step(index + 1);
});
} else {
step(index + 1);
}
}
};
step(0);
}
// When changing thing, also edit router.d.ts
var NavigationFailureType = {
redirected: 2,
aborted: 4,
cancelled: 8,
duplicated: 16
};
function createNavigationRedirectedError(from, to) {
return createRouterError(
from,
to,
NavigationFailureType.redirected,
("Redirected when going from \"" + (from.fullPath) + "\" to \"" + (stringifyRoute(
to
)) + "\" via a navigation guard.")
)
}
function createNavigationDuplicatedError(from, to) {
var error = createRouterError(
from,
to,
NavigationFailureType.duplicated,
("Avoided redundant navigation to current location: \"" + (from.fullPath) + "\".")
);
// backwards compatible with the first introduction of Errors
error.name = 'NavigationDuplicated';
return error
}
function createNavigationCancelledError(from, to) {
return createRouterError(
from,
to,
NavigationFailureType.cancelled,
("Navigation cancelled from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" with a new navigation.")
)
}
function createNavigationAbortedError(from, to) {
return createRouterError(
from,
to,
NavigationFailureType.aborted,
("Navigation aborted from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" via a navigation guard.")
)
}
function createRouterError(from, to, type, message) {
var error = new Error(message);
error._isRouter = true;
error.from = from;
error.to = to;
error.type = type;
return error
}
var propertiesToLog = ['params', 'query', 'hash'];
function stringifyRoute(to) {
if (typeof to === 'string') { return to }
if ('path' in to) { return to.path }
var location = {};
propertiesToLog.forEach(function (key) {
if (key in to) { location[key] = to[key]; }
});
return JSON.stringify(location, null, 2)
}
function isError(err) {
return Object.prototype.toString.call(err).indexOf('Error') > -1
}
function isNavigationFailure(err, errorType) {
return (
isError(err) &&
err._isRouter &&
(errorType == null || err.type === errorType)
)
}
/* */
function resolveAsyncComponents(matched) {
return function (to, from, next) {
var hasAsync = false;
var pending = 0;
var error = null;
flatMapComponents(matched, function (def, _, match, key) {
// if it's a function and doesn't have cid attached,
// assume it's an async component resolve function.
// we are not using Vue's default async resolving mechanism because
// we want to halt the navigation until the incoming component has been
// resolved.
if (typeof def === 'function' && def.cid === undefined) {
hasAsync = true;
pending++;
var resolve = once(function (resolvedDef) {
if (isESModule(resolvedDef)) {
resolvedDef = resolvedDef.default;
}
// save resolved on async factory in case it's used elsewhere
def.resolved = typeof resolvedDef === 'function'
? resolvedDef
: _Vue.extend(resolvedDef);
match.components[key] = resolvedDef;
pending--;
if (pending <= 0) {
next();
}
});
var reject = once(function (reason) {
var msg = "Failed to resolve async component " + key + ": " + reason;
warn(false, msg);
if (!error) {
error = isError(reason)
? reason
: new Error(msg);
next(error);
}
});
var res;
try {
res = def(resolve, reject);
} catch (e) {
reject(e);
}
if (res) {
if (typeof res.then === 'function') {
res.then(resolve, reject);
} else {
// new syntax in Vue 2.3
var comp = res.component;
if (comp && typeof comp.then === 'function') {
comp.then(resolve, reject);
}
}
}
}
});
if (!hasAsync) { next(); }
}
}
function flatMapComponents(
matched,
fn
) {
return flatten(matched.map(function (m) {
return Object.keys(m.components).map(function (key) {
return fn(
m.components[key],
m.instances[key],
m, key
);
})
}))
}
function flatten(arr) {
return Array.prototype.concat.apply([], arr)
}
var hasSymbol =
typeof Symbol === 'function' &&
typeof Symbol.toStringTag === 'symbol';
function isESModule(obj) {
return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
}
// in Webpack 2, require.ensure now also returns a Promise
// so the resolve/reject functions may get called an extra time
// if the user uses an arrow function shorthand that happens to
// return that Promise.
function once(fn) {
var called = false;
return function () {
var args = [], len = arguments.length;
while (len--) args[len] = arguments[len];
if (called) { return }
called = true;
return fn.apply(this, args)
}
}
/* */
var History = function History(router, base) {
this.router = router;
this.base = normalizeBase(base);
// start with a route object that stands for "nowhere"
this.current = START;
this.pending = null;
this.ready = false;
this.readyCbs = [];
this.readyErrorCbs = [];
this.errorCbs = [];
this.listeners = [];
};
History.prototype.listen = function listen(cb) {
this.cb = cb;
};
History.prototype.onReady = function onReady(cb, errorCb) {
if (this.ready) {
cb();
} else {
this.readyCbs.push(cb);
if (errorCb) {
this.readyErrorCbs.push(errorCb);
}
}
};
History.prototype.onError = function onError(errorCb) {
this.errorCbs.push(errorCb);
};
History.prototype.transitionTo = function transitionTo(
location,
onComplete,
onAbort
) {
var this$1 = this;
var route;
// catch redirect option https://github.com/vuejs/vue-router/issues/3201
try {
route = this.router.match(location, this.current);
} catch (e) {
this.errorCbs.forEach(function (cb) {
cb(e);
});
// Exception should still be thrown
throw e
}
var prev = this.current;
this.confirmTransition(
route,
function () {
this$1.updateRoute(route);
onComplete && onComplete(route);
this$1.ensureURL();
this$1.router.afterHooks.forEach(function (hook) {
hook && hook(route, prev);
});
// fire ready cbs once
if (!this$1.ready) {
this$1.ready = true;
this$1.readyCbs.forEach(function (cb) {
cb(route);
});
}
},
function (err) {
if (onAbort) {
onAbort(err);
}
if (err && !this$1.ready) {
// Initial redirection should not mark the history as ready yet
// because it's triggered by the redirection instead
// https://github.com/vuejs/vue-router/issues/3225
// https://github.com/vuejs/vue-router/issues/3331
if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
this$1.ready = true;
this$1.readyErrorCbs.forEach(function (cb) {
cb(err);
});
}
}
}
);
};
History.prototype.confirmTransition = function confirmTransition(route, onComplete, onAbort) {
var this$1 = this;
var current = this.current;
this.pending = route;
var abort = function (err) {
// changed after adding errors with
// https://github.com/vuejs/vue-router/pull/3047 before that change,
// redirect and aborted navigation would produce an err == null
if (!isNavigationFailure(err) && isError(err)) {
if (this$1.errorCbs.length) {
this$1.errorCbs.forEach(function (cb) {
cb(err);
});
} else {
warn(false, 'uncaught error during route navigation:');
console.error(err);
}
}
onAbort && onAbort(err);
};
var lastRouteIndex = route.matched.length - 1;
var lastCurrentIndex = current.matched.length - 1;
if (
isSameRoute(route, current) &&
// in the case the route map has been dynamically appended to
lastRouteIndex === lastCurrentIndex &&
route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
) {
this.ensureURL();
return abort(createNavigationDuplicatedError(current, route))
}
var ref = resolveQueue(
this.current.matched,
route.matched
);
var updated = ref.updated;
var deactivated = ref.deactivated;
var activated = ref.activated;
var queue = [].concat(
// in-component leave guards
extractLeaveGuards(deactivated),
// global before hooks
this.router.beforeHooks,
// in-component update hooks
extractUpdateHooks(updated),
// in-config enter guards
activated.map(function (m) { return m.beforeEnter; }),
// async components
resolveAsyncComponents(activated)
);
var iterator = function (hook, next) {
if (this$1.pending !== route) {
return abort(createNavigationCancelledError(current, route))
}
try {
hook(route, current, function (to) {
if (to === false) {
// next(false) -> abort navigation, ensure current URL
this$1.ensureURL(true);
abort(createNavigationAbortedError(current, route));
} else if (isError(to)) {
this$1.ensureURL(true);
abort(to);
} else if (
typeof to === 'string' ||
(typeof to === 'object' &&
(typeof to.path === 'string' || typeof to.name === 'string'))
) {
// next('/') or next({ path: '/' }) -> redirect
abort(createNavigationRedirectedError(current, route));
if (typeof to === 'object' && to.replace) {
this$1.replace(to);
} else {
this$1.push(to);
}
} else {
// confirm transition and pass on the value
next(to);
}
});
} catch (e) {
abort(e);
}
};
runQueue(queue, iterator, function () {
// wait until async components are resolved before
// extracting in-component enter guards
var enterGuards = extractEnterGuards(activated);
var queue = enterGuards.concat(this$1.router.resolveHooks);
runQueue(queue, iterator, function () {
if (this$1.pending !== route) {
return abort(createNavigationCancelledError(current, route))
}
this$1.pending = null;
onComplete(route);
if (this$1.router.app) {
this$1.router.app.$nextTick(function () {
handleRouteEntered(route);
});
}
});
});
};
History.prototype.updateRoute = function updateRoute(route) {
this.current = route;
this.cb && this.cb(route);
};
History.prototype.setupListeners = function setupListeners() {
// Default implementation is empty
};
History.prototype.teardown = function teardown() {
// clean up event listeners
// https://github.com/vuejs/vue-router/issues/2341
this.listeners.forEach(function (cleanupListener) {
cleanupListener();
});
this.listeners = [];
// reset current history route
// https://github.com/vuejs/vue-router/issues/3294
this.current = START;
this.pending = null;
};
function normalizeBase(base) {
if (!base) {
if (inBrowser) {
// respect <base> tag
var baseEl = document.querySelector('base');
base = (baseEl && baseEl.getAttribute('href')) || '/';
// strip full URL origin
base = base.replace(/^https?:\/\/[^\/]+/, '');
} else {
base = '/';
}
}
// make sure there's the starting slash
if (base.charAt(0) !== '/') {
base = '/' + base;
}
// remove trailing slash
return base.replace(/\/$/, '')
}
function resolveQueue(
current,
next
) {
var i;
var max = Math.max(current.length, next.length);
for (i = 0; i < max; i++) {
if (current[i] !== next[i]) {
break
}
}
return {
updated: next.slice(0, i),
activated: next.slice(i),
deactivated: current.slice(i)
}
}
function extractGuards(
records,
name,
bind,
reverse
) {
var guards = flatMapComponents(records, function (def, instance, match, key) {
var guard = extractGuard(def, name);
if (guard) {
return Array.isArray(guard)
? guard.map(function (guard) { return bind(guard, instance, match, key); })
: bind(guard, instance, match, key)
}
});
return flatten(reverse ? guards.reverse() : guards)
}
function extractGuard(
def,
key
) {
if (typeof def !== 'function') {
// extend now so that global mixins are applied.
def = _Vue.extend(def);
}
return def.options[key]
}
function extractLeaveGuards(deactivated) {
return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
}
function extractUpdateHooks(updated) {
return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
}
function bindGuard(guard, instance) {
if (instance) {
return function boundRouteGuard() {
return guard.apply(instance, arguments)
}
}
}
function extractEnterGuards(
activated
) {
return extractGuards(
activated,
'beforeRouteEnter',
function (guard, _, match, key) {
return bindEnterGuard(guard, match, key)
}
)
}
function bindEnterGuard(
guard,
match,
key
) {
return function routeEnterGuard(to, from, next) {
return guard(to, from, function (cb) {
if (typeof cb === 'function') {
if (!match.enteredCbs[key]) {
match.enteredCbs[key] = [];
}
match.enteredCbs[key].push(cb);
}
next(cb);
})
}
}
/* */
var HTML5History = /*@__PURE__*/(function (History) {
function HTML5History(router, base) {
History.call(this, router, base);
this._startLocation = getLocation(this.base);
}
if (History) HTML5History.__proto__ = History;
HTML5History.prototype = Object.create(History && History.prototype);
HTML5History.prototype.constructor = HTML5History;
HTML5History.prototype.setupListeners = function setupListeners() {
var this$1 = this;
if (this.listeners.length > 0) {
return
}
var router = this.router;
var expectScroll = router.options.scrollBehavior;
var supportsScroll = supportsPushState && expectScroll;
if (supportsScroll) {
this.listeners.push(setupScroll());
}
var handleRoutingEvent = function () {
var current = this$1.current;
// Avoiding first `popstate` event dispatched in some browsers but first
// history route not updated since async guard at the same time.
var location = getLocation(this$1.base);
if (this$1.current === START && location === this$1._startLocation) {
return
}
this$1.transitionTo(location, function (route) {
if (supportsScroll) {
handleScroll(router, route, current, true);
}
});
};
window.addEventListener('popstate', handleRoutingEvent);
this.listeners.push(function () {
window.removeEventListener('popstate', handleRoutingEvent);
});
};
HTML5History.prototype.go = function go(n) {
window.history.go(n);
};
HTML5History.prototype.push = function push(location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(location, function (route) {
pushState(cleanPath(this$1.base + route.fullPath));
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
}, onAbort);
};
HTML5History.prototype.replace = function replace(location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(location, function (route) {
replaceState(cleanPath(this$1.base + route.fullPath));
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
}, onAbort);
};
HTML5History.prototype.ensureURL = function ensureURL(push) {
if (getLocation(this.base) !== this.current.fullPath) {
var current = cleanPath(this.base + this.current.fullPath);
push ? pushState(current) : replaceState(current);
}
};
HTML5History.prototype.getCurrentLocation = function getCurrentLocation() {
return getLocation(this.base)
};
return HTML5History;
}(History));
function getLocation(base) {
var path = window.location.pathname;
if (base && path.toLowerCase().indexOf(base.toLowerCase()) === 0) {
path = path.slice(base.length);
}
return (path || '/') + window.location.search + window.location.hash
}
/* */
var HashHistory = /*@__PURE__*/(function (History) {
function HashHistory(router, base, fallback) {
History.call(this, router, base);
// check history fallback deeplinking
if (fallback && checkFallback(this.base)) {
return
}
ensureSlash();
}
if (History) HashHistory.__proto__ = History;
HashHistory.prototype = Object.create(History && History.prototype);
HashHistory.prototype.constructor = HashHistory;
// this is delayed until the app mounts
// to avoid the hashchange listener being fired too early
HashHistory.prototype.setupListeners = function setupListeners() {
var this$1 = this;
if (this.listeners.length > 0) {
return
}
var router = this.router;
var expectScroll = router.options.scrollBehavior;
var supportsScroll = supportsPushState && expectScroll;
if (supportsScroll) {
this.listeners.push(setupScroll());
}
var handleRoutingEvent = function () {
var current = this$1.current;
if (!ensureSlash()) {
return
}
this$1.transitionTo(getHash(), function (route) {
if (supportsScroll) {
handleScroll(this$1.router, route, current, true);
}
if (!supportsPushState) {
replaceHash(route.fullPath);
}
});
};
var eventType = supportsPushState ? 'popstate' : 'hashchange';
window.addEventListener(
eventType,
handleRoutingEvent
);
this.listeners.push(function () {
window.removeEventListener(eventType, handleRoutingEvent);
});
};
HashHistory.prototype.push = function push(location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(
location,
function (route) {
pushHash(route.fullPath);
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
},
onAbort
);
};
HashHistory.prototype.replace = function replace(location, onComplete, onAbort) {
var this$1 = this;
var ref = this;
var fromRoute = ref.current;
this.transitionTo(
location,
function (route) {
replaceHash(route.fullPath);
handleScroll(this$1.router, route, fromRoute, false);
onComplete && onComplete(route);
},
onAbort
);
};
HashHistory.prototype.go = function go(n) {
window.history.go(n);
};
HashHistory.prototype.ensureURL = function ensureURL(push) {
var current = this.current.fullPath;
if (getHash() !== current) {
push ? pushHash(current) : replaceHash(current);
}
};
HashHistory.prototype.getCurrentLocation = function getCurrentLocation() {
return getHash()
};
return HashHistory;
}(History));
function checkFallback(base) {
var location = getLocation(base);
if (!/^\/#/.test(location)) {
window.location.replace(cleanPath(base + '/#' + location));
return true
}
}
function ensureSlash() {
var path = getHash();
if (path.charAt(0) === '/') {
return true
}
replaceHash('/' + path);
return false
}
function getHash() {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
var href = window.location.href;
var index = href.indexOf('#');
// empty path
if (index < 0) { return '' }
href = href.slice(index + 1);
return href
}
function getUrl(path) {
var href = window.location.href;
var i = href.indexOf('#');
var base = i >= 0 ? href.slice(0, i) : href;
return (base + "#" + path)
}
function pushHash(path) {
if (supportsPushState) {
pushState(getUrl(path));
} else {
window.location.hash = path;
}
}
function replaceHash(path) {
if (supportsPushState) {
replaceState(getUrl(path));
} else {
window.location.replace(getUrl(path));
}
}
/* */
var AbstractHistory = /*@__PURE__*/(function (History) {
function AbstractHistory(router, base) {
History.call(this, router, base);
this.stack = [];
this.index = -1;
}
if (History) AbstractHistory.__proto__ = History;
AbstractHistory.prototype = Object.create(History && History.prototype);
AbstractHistory.prototype.constructor = AbstractHistory;
AbstractHistory.prototype.push = function push(location, onComplete, onAbort) {
var this$1 = this;
this.transitionTo(
location,
function (route) {
this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
this$1.index++;
onComplete && onComplete(route);
},
onAbort
);
};
AbstractHistory.prototype.replace = function replace(location, onComplete, onAbort) {
var this$1 = this;
this.transitionTo(
location,
function (route) {
this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
onComplete && onComplete(route);
},
onAbort
);
};
AbstractHistory.prototype.go = function go(n) {
var this$1 = this;
var targetIndex = this.index + n;
if (targetIndex < 0 || targetIndex >= this.stack.length) {
return
}
var route = this.stack[targetIndex];
this.confirmTransition(
route,
function () {
var prev = this$1.current;
this$1.index = targetIndex;
this$1.updateRoute(route);
this$1.router.afterHooks.forEach(function (hook) {
hook && hook(route, prev);
});
},
function (err) {
if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
this$1.index = targetIndex;
}
}
);
};
AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation() {
var current = this.stack[this.stack.length - 1];
return current ? current.fullPath : '/'
};
AbstractHistory.prototype.ensureURL = function ensureURL() {
// noop
};
return AbstractHistory;
}(History));
/* */
var VueRouter = function VueRouter(options) {
if (options === void 0) options = {};
this.app = null;
this.apps = [];
this.options = options;
this.beforeHooks = [];
this.resolveHooks = [];
this.afterHooks = [];
this.matcher = createMatcher(options.routes || [], this);
var mode = options.mode || 'hash';
this.fallback =
mode === 'history' && !supportsPushState && options.fallback !== false;
if (this.fallback) {
mode = 'hash';
}
if (!inBrowser) {
mode = 'abstract';
}
this.mode = mode;
switch (mode) {
case 'history':
this.history = new HTML5History(this, options.base);
break
case 'hash':
this.history = new HashHistory(this, options.base, this.fallback);
break
case 'abstract':
this.history = new AbstractHistory(this, options.base);
break
default:
{
assert(false, ("invalid mode: " + mode));
}
}
};
var prototypeAccessors = { currentRoute: { configurable: true } };
VueRouter.prototype.match = function match(raw, current, redirectedFrom) {
return this.matcher.match(raw, current, redirectedFrom)
};
prototypeAccessors.currentRoute.get = function () {
return this.history && this.history.current
};
VueRouter.prototype.init = function init(app /* Vue component instance */) {
var this$1 = this;
assert(
install.installed,
"not installed. Make sure to call `Vue.use(VueRouter)` " +
"before creating root instance."
);
this.apps.push(app);
// set up app destroyed handler
// https://github.com/vuejs/vue-router/issues/2639
app.$once('hook:destroyed', function () {
// clean out app from this.apps array once destroyed
var index = this$1.apps.indexOf(app);
if (index > -1) { this$1.apps.splice(index, 1); }
// ensure we still have a main app or null if no apps
// we do not release the router so it can be reused
if (this$1.app === app) { this$1.app = this$1.apps[0] || null; }
if (!this$1.app) { this$1.history.teardown(); }
});
// main app previously initialized
// return as we don't need to set up new history listener
if (this.app) {
return
}
this.app = app;
var history = this.history;
if (history instanceof HTML5History || history instanceof HashHistory) {
var handleInitialScroll = function (routeOrError) {
var from = history.current;
var expectScroll = this$1.options.scrollBehavior;
var supportsScroll = supportsPushState && expectScroll;
if (supportsScroll && 'fullPath' in routeOrError) {
handleScroll(this$1, routeOrError, from, false);
}
};
var setupListeners = function (routeOrError) {
history.setupListeners();
handleInitialScroll(routeOrError);
};
history.transitionTo(
history.getCurrentLocation(),
setupListeners,
setupListeners
);
}
history.listen(function (route) {
this$1.apps.forEach(function (app) {
app._route = route;
});
});
};
VueRouter.prototype.beforeEach = function beforeEach(fn) {
return registerHook(this.beforeHooks, fn)
};
VueRouter.prototype.beforeResolve = function beforeResolve(fn) {
return registerHook(this.resolveHooks, fn)
};
VueRouter.prototype.afterEach = function afterEach(fn) {
return registerHook(this.afterHooks, fn)
};
VueRouter.prototype.onReady = function onReady(cb, errorCb) {
this.history.onReady(cb, errorCb);
};
VueRouter.prototype.onError = function onError(errorCb) {
this.history.onError(errorCb);
};
VueRouter.prototype.push = function push(location, onComplete, onAbort) {
var this$1 = this;
// $flow-disable-line
if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
this$1.history.push(location, resolve, reject);
})
} else {
this.history.push(location, onComplete, onAbort);
}
};
VueRouter.prototype.replace = function replace(location, onComplete, onAbort) {
var this$1 = this;
// $flow-disable-line
if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
return new Promise(function (resolve, reject) {
this$1.history.replace(location, resolve, reject);
})
} else {
this.history.replace(location, onComplete, onAbort);
}
};
VueRouter.prototype.go = function go(n) {
this.history.go(n);
};
VueRouter.prototype.back = function back() {
this.go(-1);
};
VueRouter.prototype.forward = function forward() {
this.go(1);
};
VueRouter.prototype.getMatchedComponents = function getMatchedComponents(to) {
var route = to
? to.matched
? to
: this.resolve(to).route
: this.currentRoute;
if (!route) {
return []
}
return [].concat.apply(
[],
route.matched.map(function (m) {
return Object.keys(m.components).map(function (key) {
return m.components[key]
})
})
)
};
VueRouter.prototype.resolve = function resolve(
to,
current,
append
) {
current = current || this.history.current;
var location = normalizeLocation(to, current, append, this);
var route = this.match(location, current);
var fullPath = route.redirectedFrom || route.fullPath;
var base = this.history.base;
var href = createHref(base, fullPath, this.mode);
return {
location: location,
route: route,
href: href,
// for backwards compat
normalizedTo: location,
resolved: route
}
};
VueRouter.prototype.getRoutes = function getRoutes() {
return this.matcher.getRoutes()
};
VueRouter.prototype.addRoute = function addRoute(parentOrRoute, route) {
this.matcher.addRoute(parentOrRoute, route);
if (this.history.current !== START) {
this.history.transitionTo(this.history.getCurrentLocation());
}
};
VueRouter.prototype.addRoutes = function addRoutes(routes) {
{
warn(false, 'router.addRoutes() is deprecated and has been removed in Vue Router 4. Use router.addRoute() instead.');
}
this.matcher.addRoutes(routes);
if (this.history.current !== START) {
this.history.transitionTo(this.history.getCurrentLocation());
}
};
Object.defineProperties(VueRouter.prototype, prototypeAccessors);
function registerHook(list, fn) {
list.push(fn);
return function () {
var i = list.indexOf(fn);
if (i > -1) { list.splice(i, 1); }
}
}
function createHref(base, fullPath, mode) {
var path = mode === 'hash' ? '#' + fullPath : fullPath;
return base ? cleanPath(base + '/' + path) : path
}
VueRouter.install = install;
VueRouter.version = '3.5.1';
VueRouter.isNavigationFailure = isNavigationFailure;
VueRouter.NavigationFailureType = NavigationFailureType;
VueRouter.START_LOCATION = START;
if (inBrowser && window.Vue) {
window.Vue.use(VueRouter);
}
return VueRouter;
}));
//Included:lib/010.i18next-v21.8.0.js
!function (factory) {
// Only navigators:
if(typeof window === 'undefined') return;
// General boilerplate:
if(typeof window !== "undefined") {
if ("i18next" in window) return window.i18next;
}
if(typeof global !== "undefined") {
if ("i18next" in global) return global.i18next;
}
const output = factory();
if (typeof module === 'object' && typeof module.exports === 'object') module.exports = output;
if (typeof define === 'function' && define.amd) define([], factory);
if (typeof exports === 'object') exports["i18next"] = output;
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') window.i18next = output;
}
if (typeof global !== "undefined") {
if (typeof global !== 'undefined') global.i18next = output;
}
return output;
}(function () { "use strict"; function e(t) { return (e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) { return typeof e } : function (e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e })(t) } function t(e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") } function n(e, t) { for (var n = 0; n < t.length; n++) { var r = t[n]; r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r) } } function r(e, t, r) { return t && n(e.prototype, t), r && n(e, r), Object.defineProperty(e, "prototype", { writable: !1 }), e } function o(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e } function i(e, t) { return (i = Object.setPrototypeOf || function (e, t) { return e.__proto__ = t, e })(e, t) } function a(e, t) { if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function"); e.prototype = Object.create(t && t.prototype, { constructor: { value: e, writable: !0, configurable: !0 } }), Object.defineProperty(e, "prototype", { writable: !1 }), t && i(e, t) } function s(t, n) { if (n && ("object" === e(n) || "function" == typeof n)) return n; if (void 0 !== n) throw new TypeError("Derived constructors may only return object or undefined"); return o(t) } function u(e) { return (u = Object.setPrototypeOf ? Object.getPrototypeOf : function (e) { return e.__proto__ || Object.getPrototypeOf(e) })(e) } function c(e, t, n) { return t in e ? Object.defineProperty(e, t, { value: n, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = n, e } function l(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function f(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? l(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : l(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } var p = { type: "logger", log: function (e) { this.output("log", e) }, warn: function (e) { this.output("warn", e) }, error: function (e) { this.output("error", e) }, output: function (e, t) { console && console[e] && console[e].apply(console, t) } }, g = new (function () { function e(n) { var r = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; t(this, e), this.init(n, r) } return r(e, [{ key: "init", value: function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; this.prefix = t.prefix || "i18next:", this.logger = e || p, this.options = t, this.debug = t.debug } }, { key: "setDebug", value: function (e) { this.debug = e } }, { key: "log", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this.forward(t, "log", "", !0) } }, { key: "warn", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this.forward(t, "warn", "", !0) } }, { key: "error", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this.forward(t, "error", "") } }, { key: "deprecate", value: function () { for (var e = arguments.length, t = new Array(e), n = 0; n < e; n++)t[n] = arguments[n]; return this.forward(t, "warn", "WARNING DEPRECATED: ", !0) } }, { key: "forward", value: function (e, t, n, r) { return r && !this.debug ? null : ("string" == typeof e[0] && (e[0] = "".concat(n).concat(this.prefix, " ").concat(e[0])), this.logger[t](e)) } }, { key: "create", value: function (t) { return new e(this.logger, f(f({}, { prefix: "".concat(this.prefix, ":").concat(t, ":") }), this.options)) } }]), e }()), h = function () { function e() { t(this, e), this.observers = {} } return r(e, [{ key: "on", value: function (e, t) { var n = this; return e.split(" ").forEach(function (e) { n.observers[e] = n.observers[e] || [], n.observers[e].push(t) }), this } }, { key: "off", value: function (e, t) { this.observers[e] && (t ? this.observers[e] = this.observers[e].filter(function (e) { return e !== t }) : delete this.observers[e]) } }, { key: "emit", value: function (e) { for (var t = arguments.length, n = new Array(t > 1 ? t - 1 : 0), r = 1; r < t; r++)n[r - 1] = arguments[r]; this.observers[e] && [].concat(this.observers[e]).forEach(function (e) { e.apply(void 0, n) }); this.observers["*"] && [].concat(this.observers["*"]).forEach(function (t) { t.apply(t, [e].concat(n)) }) } }]), e }(); function d() { var e, t, n = new Promise(function (n, r) { e = n, t = r }); return n.resolve = e, n.reject = t, n } function v(e) { return null == e ? "" : "" + e } function y(e, t, n) { function r(e) { return e && e.indexOf("###") > -1 ? e.replace(/###/g, ".") : e } function o() { return !e || "string" == typeof e } for (var i = "string" != typeof t ? [].concat(t) : t.split("."); i.length > 1;) { if (o()) return {}; var a = r(i.shift()); !e[a] && n && (e[a] = new n), e = Object.prototype.hasOwnProperty.call(e, a) ? e[a] : {} } return o() ? {} : { obj: e, k: r(i.shift()) } } function m(e, t, n) { var r = y(e, t, Object); r.obj[r.k] = n } function b(e, t) { var n = y(e, t), r = n.obj, o = n.k; if (r) return r[o] } function O(e, t, n) { var r = b(e, n); return void 0 !== r ? r : b(t, n) } function k(e) { return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") } var w = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "/": "/" }; function x(e) { return "string" == typeof e ? e.replace(/[&<>"'\/]/g, function (e) { return w[e] }) : e } var S = "undefined" != typeof window && window.navigator && window.navigator.userAgent && window.navigator.userAgent.indexOf("MSIE") > -1, j = [" ", ",", "?", "!", ";"]; function P(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function L(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? P(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : P(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } function R(e) { var t = function () { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () { })), !0 } catch (e) { return !1 } }(); return function () { var n, r = u(e); if (t) { var o = u(this).constructor; n = Reflect.construct(r, arguments, o) } else n = r.apply(this, arguments); return s(this, n) } } var N = function (e) { a(i, h); var n = R(i); function i(e) { var r, a = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : { ns: ["translation"], defaultNS: "translation" }; return t(this, i), r = n.call(this), S && h.call(o(r)), r.data = e || {}, r.options = a, void 0 === r.options.keySeparator && (r.options.keySeparator = "."), void 0 === r.options.ignoreJSONStructure && (r.options.ignoreJSONStructure = !0), r } return r(i, [{ key: "addNamespaces", value: function (e) { this.options.ns.indexOf(e) < 0 && this.options.ns.push(e) } }, { key: "removeNamespaces", value: function (e) { var t = this.options.ns.indexOf(e); t > -1 && this.options.ns.splice(t, 1) } }, { key: "getResource", value: function (e, t, n) { var r = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, o = void 0 !== r.keySeparator ? r.keySeparator : this.options.keySeparator, i = void 0 !== r.ignoreJSONStructure ? r.ignoreJSONStructure : this.options.ignoreJSONStructure, a = [e, t]; n && "string" != typeof n && (a = a.concat(n)), n && "string" == typeof n && (a = a.concat(o ? n.split(o) : n)), e.indexOf(".") > -1 && (a = e.split(".")); var s = b(this.data, a); return s || !i || "string" != typeof n ? s : function e(t, n) { var r = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : "."; if (t) { if (t[n]) return t[n]; for (var o = n.split(r), i = t, a = 0; a < o.length; ++a) { if (!i) return; if ("string" == typeof i[o[a]] && a + 1 < o.length) return; if (void 0 === i[o[a]]) { for (var s = 2, u = o.slice(a, a + s).join(r), c = i[u]; void 0 === c && o.length > a + s;)s++, c = i[u = o.slice(a, a + s).join(r)]; if (void 0 === c) return; if (n.endsWith(u)) { if ("string" == typeof c) return c; if (u && "string" == typeof c[u]) return c[u] } var l = o.slice(a + s).join(r); return l ? e(c, l, r) : void 0 } i = i[o[a]] } return i } }(this.data && this.data[e] && this.data[e][t], n, o) } }, { key: "addResource", value: function (e, t, n, r) { var o = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : { silent: !1 }, i = this.options.keySeparator; void 0 === i && (i = "."); var a = [e, t]; n && (a = a.concat(i ? n.split(i) : n)), e.indexOf(".") > -1 && (r = t, t = (a = e.split("."))[1]), this.addNamespaces(t), m(this.data, a, r), o.silent || this.emit("added", e, t, n, r) } }, { key: "addResources", value: function (e, t, n) { var r = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : { silent: !1 }; for (var o in n) "string" != typeof n[o] && "[object Array]" !== Object.prototype.toString.apply(n[o]) || this.addResource(e, t, o, n[o], { silent: !0 }); r.silent || this.emit("added", e, t, n) } }, { key: "addResourceBundle", value: function (e, t, n, r, o) { var i = arguments.length > 5 && void 0 !== arguments[5] ? arguments[5] : { silent: !1 }, a = [e, t]; e.indexOf(".") > -1 && (r = n, n = t, t = (a = e.split("."))[1]), this.addNamespaces(t); var s = b(this.data, a) || {}; r ? function e(t, n, r) { for (var o in n) "__proto__" !== o && "constructor" !== o && (o in t ? "string" == typeof t[o] || t[o] instanceof String || "string" == typeof n[o] || n[o] instanceof String ? r && (t[o] = n[o]) : e(t[o], n[o], r) : t[o] = n[o]); return t }(s, n, o) : s = L(L({}, s), n), m(this.data, a, s), i.silent || this.emit("added", e, t, n) } }, { key: "removeResourceBundle", value: function (e, t) { this.hasResourceBundle(e, t) && delete this.data[e][t], this.removeNamespaces(t), this.emit("removed", e, t) } }, { key: "hasResourceBundle", value: function (e, t) { return void 0 !== this.getResource(e, t) } }, { key: "getResourceBundle", value: function (e, t) { return t || (t = this.options.defaultNS), "v1" === this.options.compatibilityAPI ? L(L({}, {}), this.getResource(e, t)) : this.getResource(e, t) } }, { key: "getDataByLanguage", value: function (e) { return this.data[e] } }, { key: "hasLanguageSomeTranslations", value: function (e) { var t = this.getDataByLanguage(e); return !!(t && Object.keys(t) || []).find(function (e) { return t[e] && Object.keys(t[e]).length > 0 }) } }, { key: "toJSON", value: function () { return this.data } }]), i }(), C = { processors: {}, addPostProcessor: function (e) { this.processors[e.name] = e }, handle: function (e, t, n, r, o) { var i = this; return e.forEach(function (e) { i.processors[e] && (t = i.processors[e].process(t, n, r, o)) }), t } }; function E(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function D(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? E(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : E(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } function F(e) { var t = function () { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () { })), !0 } catch (e) { return !1 } }(); return function () { var n, r = u(e); if (t) { var o = u(this).constructor; n = Reflect.construct(r, arguments, o) } else n = r.apply(this, arguments); return s(this, n) } } var I = {}, A = function (n) { a(s, h); var i = F(s); function s(e) { var n, r, a, u, c = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; return t(this, s), n = i.call(this), S && h.call(o(n)), r = ["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], a = e, u = o(n), r.forEach(function (e) { a[e] && (u[e] = a[e]) }), n.options = c, void 0 === n.options.keySeparator && (n.options.keySeparator = "."), n.logger = g.create("translator"), n } return r(s, [{ key: "changeLanguage", value: function (e) { e && (this.language = e) } }, { key: "exists", value: function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : { interpolation: {} }; if (null == e) return !1; var n = this.resolve(e, t); return n && void 0 !== n.res } }, { key: "extractFromKey", value: function (e, t) { var n = void 0 !== t.nsSeparator ? t.nsSeparator : this.options.nsSeparator; void 0 === n && (n = ":"); var r = void 0 !== t.keySeparator ? t.keySeparator : this.options.keySeparator, o = t.ns || this.options.defaultNS || [], i = n && e.indexOf(n) > -1, a = !(this.options.userDefinedKeySeparator || t.keySeparator || this.options.userDefinedNsSeparator || t.nsSeparator || function (e, t, n) { t = t || "", n = n || ""; var r = j.filter(function (e) { return t.indexOf(e) < 0 && n.indexOf(e) < 0 }); if (0 === r.length) return !0; var o = new RegExp("(".concat(r.map(function (e) { return "?" === e ? "\\?" : e }).join("|"), ")")), i = !o.test(e); if (!i) { var a = e.indexOf(n); a > 0 && !o.test(e.substring(0, a)) && (i = !0) } return i }(e, n, r)); if (i && !a) { var s = e.match(this.interpolator.nestingRegexp); if (s && s.length > 0) return { key: e, namespaces: o }; var u = e.split(n); (n !== r || n === r && this.options.ns.indexOf(u[0]) > -1) && (o = u.shift()), e = u.join(r) } return "string" == typeof o && (o = [o]), { key: e, namespaces: o } } }, { key: "translate", value: function (t, n, r) { var o = this; if ("object" !== e(n) && this.options.overloadTranslationOptionHandler && (n = this.options.overloadTranslationOptionHandler(arguments)), n || (n = {}), null == t) return ""; Array.isArray(t) || (t = [String(t)]); var i = void 0 !== n.returnDetails ? n.returnDetails : this.options.returnDetails, a = void 0 !== n.keySeparator ? n.keySeparator : this.options.keySeparator, u = this.extractFromKey(t[t.length - 1], n), c = u.key, l = u.namespaces, f = l[l.length - 1], p = n.lng || this.language, g = n.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; if (p && "cimode" === p.toLowerCase()) { if (g) { var h = n.nsSeparator || this.options.nsSeparator; return i ? (d.res = "".concat(f).concat(h).concat(c), d) : "".concat(f).concat(h).concat(c) } return i ? (d.res = c, d) : c } var d = this.resolve(t, n), v = d && d.res, y = d && d.usedKey || c, m = d && d.exactUsedKey || c, b = Object.prototype.toString.apply(v), O = void 0 !== n.joinArrays ? n.joinArrays : this.options.joinArrays, k = !this.i18nFormat || this.i18nFormat.handleAsObject; if (k && v && ("string" != typeof v && "boolean" != typeof v && "number" != typeof v) && ["[object Number]", "[object Function]", "[object RegExp]"].indexOf(b) < 0 && ("string" != typeof O || "[object Array]" !== b)) { if (!n.returnObjects && !this.options.returnObjects) { this.options.returnedObjectHandler || this.logger.warn("accessing an object - but returnObjects options is not enabled!"); var w = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(y, v, D(D({}, n), {}, { ns: l })) : "key '".concat(c, " (").concat(this.language, ")' returned an object instead of string."); return i ? (d.res = w, d) : w } if (a) { var x = "[object Array]" === b, S = x ? [] : {}, j = x ? m : y; for (var P in v) if (Object.prototype.hasOwnProperty.call(v, P)) { var L = "".concat(j).concat(a).concat(P); S[P] = this.translate(L, D(D({}, n), { joinArrays: !1, ns: l })), S[P] === L && (S[P] = v[P]) } v = S } } else if (k && "string" == typeof O && "[object Array]" === b) (v = v.join(O)) && (v = this.extendTranslation(v, t, n, r)); else { var R = !1, N = !1, C = void 0 !== n.count && "string" != typeof n.count, E = s.hasDefaultValue(n), F = C ? this.pluralResolver.getSuffix(p, n.count, n) : "", I = n["defaultValue".concat(F)] || n.defaultValue; !this.isValidLookup(v) && E && (R = !0, v = I), this.isValidLookup(v) || (N = !0, v = c); var A = (n.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey) && N ? void 0 : v, V = E && I !== v && this.options.updateMissing; if (N || R || V) { if (this.logger.log(V ? "updateKey" : "missingKey", p, f, c, V ? I : v), a) { var T = this.resolve(c, D(D({}, n), {}, { keySeparator: !1 })); T && T.res && this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.") } var U = [], B = this.languageUtils.getFallbackCodes(this.options.fallbackLng, n.lng || this.language); if ("fallback" === this.options.saveMissingTo && B && B[0]) for (var K = 0; K < B.length; K++)U.push(B[K]); else "all" === this.options.saveMissingTo ? U = this.languageUtils.toResolveHierarchy(n.lng || this.language) : U.push(n.lng || this.language); var M = function (e, t, r) { var i = E && r !== v ? r : A; o.options.missingKeyHandler ? o.options.missingKeyHandler(e, f, t, i, V, n) : o.backendConnector && o.backendConnector.saveMissing && o.backendConnector.saveMissing(e, f, t, i, V, n), o.emit("missingKey", e, f, t, v) }; this.options.saveMissing && (this.options.saveMissingPlurals && C ? U.forEach(function (e) { o.pluralResolver.getSuffixes(e, n).forEach(function (t) { M([e], c + t, n["defaultValue".concat(t)] || I) }) }) : M(U, c, I)) } v = this.extendTranslation(v, t, n, d, r), N && v === c && this.options.appendNamespaceToMissingKey && (v = "".concat(f, ":").concat(c)), (N || R) && this.options.parseMissingKeyHandler && (v = "v1" !== this.options.compatibilityAPI ? this.options.parseMissingKeyHandler(c, R ? v : void 0) : this.options.parseMissingKeyHandler(v)) } return i ? (d.res = v, d) : v } }, { key: "extendTranslation", value: function (e, t, n, r, o) { var i = this; if (this.i18nFormat && this.i18nFormat.parse) e = this.i18nFormat.parse(e, D(D({}, this.options.interpolation.defaultVariables), n), r.usedLng, r.usedNS, r.usedKey, { resolved: r }); else if (!n.skipInterpolation) { n.interpolation && this.interpolator.init(D(D({}, n), { interpolation: D(D({}, this.options.interpolation), n.interpolation) })); var a, s = "string" == typeof e && (n && n.interpolation && void 0 !== n.interpolation.skipOnVariables ? n.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); if (s) { var u = e.match(this.interpolator.nestingRegexp); a = u && u.length } var c = n.replace && "string" != typeof n.replace ? n.replace : n; if (this.options.interpolation.defaultVariables && (c = D(D({}, this.options.interpolation.defaultVariables), c)), e = this.interpolator.interpolate(e, c, n.lng || this.language, n), s) { var l = e.match(this.interpolator.nestingRegexp); a < (l && l.length) && (n.nest = !1) } !1 !== n.nest && (e = this.interpolator.nest(e, function () { for (var e = arguments.length, r = new Array(e), a = 0; a < e; a++)r[a] = arguments[a]; return o && o[0] === r[0] && !n.context ? (i.logger.warn("It seems you are nesting recursively key: ".concat(r[0], " in key: ").concat(t[0])), null) : i.translate.apply(i, r.concat([t])) }, n)), n.interpolation && this.interpolator.reset() } var f = n.postProcess || this.options.postProcess, p = "string" == typeof f ? [f] : f; return null != e && p && p.length && !1 !== n.applyPostProcessor && (e = C.handle(p, e, t, this.options && this.options.postProcessPassResolved ? D({ i18nResolved: r }, n) : n, this)), e } }, { key: "resolve", value: function (e) { var t, n, r, o, i, a = this, s = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; return "string" == typeof e && (e = [e]), e.forEach(function (e) { if (!a.isValidLookup(t)) { var u = a.extractFromKey(e, s), c = u.key; n = c; var l = u.namespaces; a.options.fallbackNS && (l = l.concat(a.options.fallbackNS)); var f = void 0 !== s.count && "string" != typeof s.count, p = f && !s.ordinal && 0 === s.count && a.pluralResolver.shouldUseIntlApi(), g = void 0 !== s.context && ("string" == typeof s.context || "number" == typeof s.context) && "" !== s.context, h = s.lngs ? s.lngs : a.languageUtils.toResolveHierarchy(s.lng || a.language, s.fallbackLng); l.forEach(function (e) { a.isValidLookup(t) || (i = e, !I["".concat(h[0], "-").concat(e)] && a.utils && a.utils.hasLoadedNamespace && !a.utils.hasLoadedNamespace(i) && (I["".concat(h[0], "-").concat(e)] = !0, a.logger.warn('key "'.concat(n, '" for languages "').concat(h.join(", "), '" won\'t get resolved as namespace "').concat(i, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")), h.forEach(function (n) { if (!a.isValidLookup(t)) { o = n; var i, u = [c]; if (a.i18nFormat && a.i18nFormat.addLookupKeys) a.i18nFormat.addLookupKeys(u, c, n, e, s); else { var l; f && (l = a.pluralResolver.getSuffix(n, s.count, s)); if (f && (u.push(c + l), p && u.push(c + "_zero")), g) { var h = "".concat(c).concat(a.options.contextSeparator).concat(s.context); u.push(h), f && (u.push(h + l), p && u.push(h + "_zero")) } } for (; i = u.pop();)a.isValidLookup(t) || (r = i, t = a.getResource(n, e, i, s)) } })) }) } }), { res: t, usedKey: n, exactUsedKey: r, usedLng: o, usedNS: i } } }, { key: "isValidLookup", value: function (e) { return !(void 0 === e || !this.options.returnNull && null === e || !this.options.returnEmptyString && "" === e) } }, { key: "getResource", value: function (e, t, n) { var r = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}; return this.i18nFormat && this.i18nFormat.getResource ? this.i18nFormat.getResource(e, t, n, r) : this.resourceStore.getResource(e, t, n, r) } }], [{ key: "hasDefaultValue", value: function (e) { for (var t in e) if (Object.prototype.hasOwnProperty.call(e, t) && "defaultValue" === t.substring(0, "defaultValue".length) && void 0 !== e[t]) return !0; return !1 } }]), s }(); function V(e) { return e.charAt(0).toUpperCase() + e.slice(1) } var T = function () { function e(n) { t(this, e), this.options = n, this.supportedLngs = this.options.supportedLngs || !1, this.logger = g.create("languageUtils") } return r(e, [{ key: "getScriptPartFromCode", value: function (e) { if (!e || e.indexOf("-") < 0) return null; var t = e.split("-"); return 2 === t.length ? null : (t.pop(), "x" === t[t.length - 1].toLowerCase() ? null : this.formatLanguageCode(t.join("-"))) } }, { key: "getLanguagePartFromCode", value: function (e) { if (!e || e.indexOf("-") < 0) return e; var t = e.split("-"); return this.formatLanguageCode(t[0]) } }, { key: "formatLanguageCode", value: function (e) { if ("string" == typeof e && e.indexOf("-") > -1) { var t = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"], n = e.split("-"); return this.options.lowerCaseLng ? n = n.map(function (e) { return e.toLowerCase() }) : 2 === n.length ? (n[0] = n[0].toLowerCase(), n[1] = n[1].toUpperCase(), t.indexOf(n[1].toLowerCase()) > -1 && (n[1] = V(n[1].toLowerCase()))) : 3 === n.length && (n[0] = n[0].toLowerCase(), 2 === n[1].length && (n[1] = n[1].toUpperCase()), "sgn" !== n[0] && 2 === n[2].length && (n[2] = n[2].toUpperCase()), t.indexOf(n[1].toLowerCase()) > -1 && (n[1] = V(n[1].toLowerCase())), t.indexOf(n[2].toLowerCase()) > -1 && (n[2] = V(n[2].toLowerCase()))), n.join("-") } return this.options.cleanCode || this.options.lowerCaseLng ? e.toLowerCase() : e } }, { key: "isSupportedCode", value: function (e) { return ("languageOnly" === this.options.load || this.options.nonExplicitSupportedLngs) && (e = this.getLanguagePartFromCode(e)), !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(e) > -1 } }, { key: "getBestMatchFromCodes", value: function (e) { var t, n = this; return e ? (e.forEach(function (e) { if (!t) { var r = n.formatLanguageCode(e); n.options.supportedLngs && !n.isSupportedCode(r) || (t = r) } }), !t && this.options.supportedLngs && e.forEach(function (e) { if (!t) { var r = n.getLanguagePartFromCode(e); if (n.isSupportedCode(r)) return t = r; t = n.options.supportedLngs.find(function (e) { if (0 === e.indexOf(r)) return e }) } }), t || (t = this.getFallbackCodes(this.options.fallbackLng)[0]), t) : null } }, { key: "getFallbackCodes", value: function (e, t) { if (!e) return []; if ("function" == typeof e && (e = e(t)), "string" == typeof e && (e = [e]), "[object Array]" === Object.prototype.toString.apply(e)) return e; if (!t) return e.default || []; var n = e[t]; return n || (n = e[this.getScriptPartFromCode(t)]), n || (n = e[this.formatLanguageCode(t)]), n || (n = e[this.getLanguagePartFromCode(t)]), n || (n = e.default), n || [] } }, { key: "toResolveHierarchy", value: function (e, t) { var n = this, r = this.getFallbackCodes(t || this.options.fallbackLng || [], e), o = [], i = function (e) { e && (n.isSupportedCode(e) ? o.push(e) : n.logger.warn("rejecting language code not found in supportedLngs: ".concat(e))) }; return "string" == typeof e && e.indexOf("-") > -1 ? ("languageOnly" !== this.options.load && i(this.formatLanguageCode(e)), "languageOnly" !== this.options.load && "currentOnly" !== this.options.load && i(this.getScriptPartFromCode(e)), "currentOnly" !== this.options.load && i(this.getLanguagePartFromCode(e))) : "string" == typeof e && i(this.formatLanguageCode(e)), r.forEach(function (e) { o.indexOf(e) < 0 && i(n.formatLanguageCode(e)) }), o } }]), e }(), U = [{ lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"], nr: [1, 2], fc: 1 }, { lngs: ["af", "an", "ast", "az", "bg", "bn", "ca", "da", "de", "dev", "el", "en", "eo", "es", "et", "eu", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "hi", "hu", "hy", "ia", "it", "kk", "kn", "ku", "lb", "mai", "ml", "mn", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "pa", "pap", "pms", "ps", "pt-PT", "rm", "sco", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"], nr: [1, 2], fc: 2 }, { lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"], nr: [1], fc: 3 }, { lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"], nr: [1, 2, 5], fc: 4 }, { lngs: ["ar"], nr: [0, 1, 2, 3, 11, 100], fc: 5 }, { lngs: ["cs", "sk"], nr: [1, 2, 5], fc: 6 }, { lngs: ["csb", "pl"], nr: [1, 2, 5], fc: 7 }, { lngs: ["cy"], nr: [1, 2, 3, 8], fc: 8 }, { lngs: ["fr"], nr: [1, 2], fc: 9 }, { lngs: ["ga"], nr: [1, 2, 3, 7, 11], fc: 10 }, { lngs: ["gd"], nr: [1, 2, 3, 20], fc: 11 }, { lngs: ["is"], nr: [1, 2], fc: 12 }, { lngs: ["jv"], nr: [0, 1], fc: 13 }, { lngs: ["kw"], nr: [1, 2, 3, 4], fc: 14 }, { lngs: ["lt"], nr: [1, 2, 10], fc: 15 }, { lngs: ["lv"], nr: [1, 2, 0], fc: 16 }, { lngs: ["mk"], nr: [1, 2], fc: 17 }, { lngs: ["mnk"], nr: [0, 1, 2], fc: 18 }, { lngs: ["mt"], nr: [1, 2, 11, 20], fc: 19 }, { lngs: ["or"], nr: [2, 1], fc: 2 }, { lngs: ["ro"], nr: [1, 2, 20], fc: 20 }, { lngs: ["sl"], nr: [5, 1, 2, 3], fc: 21 }, { lngs: ["he", "iw"], nr: [1, 2, 20, 21], fc: 22 }], B = { 1: function (e) { return Number(e > 1) }, 2: function (e) { return Number(1 != e) }, 3: function (e) { return 0 }, 4: function (e) { return Number(e % 10 == 1 && e % 100 != 11 ? 0 : e % 10 >= 2 && e % 10 <= 4 && (e % 100 < 10 || e % 100 >= 20) ? 1 : 2) }, 5: function (e) { return Number(0 == e ? 0 : 1 == e ? 1 : 2 == e ? 2 : e % 100 >= 3 && e % 100 <= 10 ? 3 : e % 100 >= 11 ? 4 : 5) }, 6: function (e) { return Number(1 == e ? 0 : e >= 2 && e <= 4 ? 1 : 2) }, 7: function (e) { return Number(1 == e ? 0 : e % 10 >= 2 && e % 10 <= 4 && (e % 100 < 10 || e % 100 >= 20) ? 1 : 2) }, 8: function (e) { return Number(1 == e ? 0 : 2 == e ? 1 : 8 != e && 11 != e ? 2 : 3) }, 9: function (e) { return Number(e >= 2) }, 10: function (e) { return Number(1 == e ? 0 : 2 == e ? 1 : e < 7 ? 2 : e < 11 ? 3 : 4) }, 11: function (e) { return Number(1 == e || 11 == e ? 0 : 2 == e || 12 == e ? 1 : e > 2 && e < 20 ? 2 : 3) }, 12: function (e) { return Number(e % 10 != 1 || e % 100 == 11) }, 13: function (e) { return Number(0 !== e) }, 14: function (e) { return Number(1 == e ? 0 : 2 == e ? 1 : 3 == e ? 2 : 3) }, 15: function (e) { return Number(e % 10 == 1 && e % 100 != 11 ? 0 : e % 10 >= 2 && (e % 100 < 10 || e % 100 >= 20) ? 1 : 2) }, 16: function (e) { return Number(e % 10 == 1 && e % 100 != 11 ? 0 : 0 !== e ? 1 : 2) }, 17: function (e) { return Number(1 == e || e % 10 == 1 && e % 100 != 11 ? 0 : 1) }, 18: function (e) { return Number(0 == e ? 0 : 1 == e ? 1 : 2) }, 19: function (e) { return Number(1 == e ? 0 : 0 == e || e % 100 > 1 && e % 100 < 11 ? 1 : e % 100 > 10 && e % 100 < 20 ? 2 : 3) }, 20: function (e) { return Number(1 == e ? 0 : 0 == e || e % 100 > 0 && e % 100 < 20 ? 1 : 2) }, 21: function (e) { return Number(e % 100 == 1 ? 1 : e % 100 == 2 ? 2 : e % 100 == 3 || e % 100 == 4 ? 3 : 0) }, 22: function (e) { return Number(1 == e ? 0 : 2 == e ? 1 : (e < 0 || e > 10) && e % 10 == 0 ? 2 : 3) } }, K = ["v1", "v2", "v3"], M = { zero: 0, one: 1, two: 2, few: 3, many: 4, other: 5 }; var H = function () { function e(n) { var r, o = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; t(this, e), this.languageUtils = n, this.options = o, this.logger = g.create("pluralResolver"), this.options.compatibilityJSON && "v4" !== this.options.compatibilityJSON || "undefined" != typeof Intl && Intl.PluralRules || (this.options.compatibilityJSON = "v3", this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")), this.rules = (r = {}, U.forEach(function (e) { e.lngs.forEach(function (t) { r[t] = { numbers: e.nr, plurals: B[e.fc] } }) }), r) } return r(e, [{ key: "addRule", value: function (e, t) { this.rules[e] = t } }, { key: "getRule", value: function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; if (this.shouldUseIntlApi()) try { return new Intl.PluralRules(e, { type: t.ordinal ? "ordinal" : "cardinal" }) } catch (e) { return } return this.rules[e] || this.rules[this.languageUtils.getLanguagePartFromCode(e)] } }, { key: "needsPlural", value: function (e) { var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, n = this.getRule(e, t); return this.shouldUseIntlApi() ? n && n.resolvedOptions().pluralCategories.length > 1 : n && n.numbers.length > 1 } }, { key: "getPluralFormsOfKey", value: function (e, t) { var n = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}; return this.getSuffixes(e, n).map(function (e) { return "".concat(t).concat(e) }) } }, { key: "getSuffixes", value: function (e) { var t = this, n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, r = this.getRule(e, n); return r ? this.shouldUseIntlApi() ? r.resolvedOptions().pluralCategories.sort(function (e, t) { return M[e] - M[t] }).map(function (e) { return "".concat(t.options.prepend).concat(e) }) : r.numbers.map(function (r) { return t.getSuffix(e, r, n) }) : [] } }, { key: "getSuffix", value: function (e, t) { var n = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, r = this.getRule(e, n); return r ? this.shouldUseIntlApi() ? "".concat(this.options.prepend).concat(r.select(t)) : this.getSuffixRetroCompatible(r, t) : (this.logger.warn("no plural rule found for: ".concat(e)), "") } }, { key: "getSuffixRetroCompatible", value: function (e, t) { var n = this, r = e.noAbs ? e.plurals(t) : e.plurals(Math.abs(t)), o = e.numbers[r]; this.options.simplifyPluralSuffix && 2 === e.numbers.length && 1 === e.numbers[0] && (2 === o ? o = "plural" : 1 === o && (o = "")); var i = function () { return n.options.prepend && o.toString() ? n.options.prepend + o.toString() : o.toString() }; return "v1" === this.options.compatibilityJSON ? 1 === o ? "" : "number" == typeof o ? "_plural_".concat(o.toString()) : i() : "v2" === this.options.compatibilityJSON ? i() : this.options.simplifyPluralSuffix && 2 === e.numbers.length && 1 === e.numbers[0] ? i() : this.options.prepend && r.toString() ? this.options.prepend + r.toString() : r.toString() } }, { key: "shouldUseIntlApi", value: function () { return !K.includes(this.options.compatibilityJSON) } }]), e }(); function z(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function J(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? z(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : z(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } var _ = function () { function e() { var n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; t(this, e), this.logger = g.create("interpolator"), this.options = n, this.format = n.interpolation && n.interpolation.format || function (e) { return e }, this.init(n) } return r(e, [{ key: "init", value: function () { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; e.interpolation || (e.interpolation = { escapeValue: !0 }); var t = e.interpolation; this.escape = void 0 !== t.escape ? t.escape : x, this.escapeValue = void 0 === t.escapeValue || t.escapeValue, this.useRawValueToEscape = void 0 !== t.useRawValueToEscape && t.useRawValueToEscape, this.prefix = t.prefix ? k(t.prefix) : t.prefixEscaped || "{{", this.suffix = t.suffix ? k(t.suffix) : t.suffixEscaped || "}}", this.formatSeparator = t.formatSeparator ? t.formatSeparator : t.formatSeparator || ",", this.unescapePrefix = t.unescapeSuffix ? "" : t.unescapePrefix || "-", this.unescapeSuffix = this.unescapePrefix ? "" : t.unescapeSuffix || "", this.nestingPrefix = t.nestingPrefix ? k(t.nestingPrefix) : t.nestingPrefixEscaped || k("$t("), this.nestingSuffix = t.nestingSuffix ? k(t.nestingSuffix) : t.nestingSuffixEscaped || k(")"), this.nestingOptionsSeparator = t.nestingOptionsSeparator ? t.nestingOptionsSeparator : t.nestingOptionsSeparator || ",", this.maxReplaces = t.maxReplaces ? t.maxReplaces : 1e3, this.alwaysFormat = void 0 !== t.alwaysFormat && t.alwaysFormat, this.resetRegExp() } }, { key: "reset", value: function () { this.options && this.init(this.options) } }, { key: "resetRegExp", value: function () { var e = "".concat(this.prefix, "(.+?)").concat(this.suffix); this.regexp = new RegExp(e, "g"); var t = "".concat(this.prefix).concat(this.unescapePrefix, "(.+?)").concat(this.unescapeSuffix).concat(this.suffix); this.regexpUnescape = new RegExp(t, "g"); var n = "".concat(this.nestingPrefix, "(.+?)").concat(this.nestingSuffix); this.nestingRegexp = new RegExp(n, "g") } }, { key: "interpolate", value: function (e, t, n, r) { var o, i, a, s = this, u = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; function c(e) { return e.replace(/\$/g, "$$$$") } var l = function (e) { if (e.indexOf(s.formatSeparator) < 0) { var o = O(t, u, e); return s.alwaysFormat ? s.format(o, void 0, n, J(J(J({}, r), t), {}, { interpolationkey: e })) : o } var i = e.split(s.formatSeparator), a = i.shift().trim(), c = i.join(s.formatSeparator).trim(); return s.format(O(t, u, a), c, n, J(J(J({}, r), t), {}, { interpolationkey: a })) }; this.resetRegExp(); var f = r && r.missingInterpolationHandler || this.options.missingInterpolationHandler, p = r && r.interpolation && void 0 !== r.interpolation.skipOnVariables ? r.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; return [{ regex: this.regexpUnescape, safeValue: function (e) { return c(e) } }, { regex: this.regexp, safeValue: function (e) { return s.escapeValue ? c(s.escape(e)) : c(e) } }].forEach(function (t) { for (a = 0; o = t.regex.exec(e);) { var n = o[1].trim(); if (void 0 === (i = l(n))) if ("function" == typeof f) { var u = f(e, o, r); i = "string" == typeof u ? u : "" } else if (r && r.hasOwnProperty(n)) i = ""; else { if (p) { i = o[0]; continue } s.logger.warn("missed to pass in variable ".concat(n, " for interpolating ").concat(e)), i = "" } else "string" == typeof i || s.useRawValueToEscape || (i = v(i)); var c = t.safeValue(i); if (e = e.replace(o[0], c), p ? (t.regex.lastIndex += c.length, t.regex.lastIndex -= o[0].length) : t.regex.lastIndex = 0, ++a >= s.maxReplaces) break } }), e } }, { key: "nest", value: function (e, t) { var n, r, o = this, i = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, a = J({}, i); function s(e, t) { var n = this.nestingOptionsSeparator; if (e.indexOf(n) < 0) return e; var r = e.split(new RegExp("".concat(n, "[ ]*{"))), o = "{".concat(r[1]); e = r[0], o = (o = this.interpolate(o, a)).replace(/'/g, '"'); try { a = JSON.parse(o), t && (a = J(J({}, t), a)) } catch (t) { return this.logger.warn("failed parsing options string in nesting for key ".concat(e), t), "".concat(e).concat(n).concat(o) } return delete a.defaultValue, e } for (a.applyPostProcessor = !1, delete a.defaultValue; n = this.nestingRegexp.exec(e);) { var u = [], c = !1; if (-1 !== n[0].indexOf(this.formatSeparator) && !/{.*}/.test(n[1])) { var l = n[1].split(this.formatSeparator).map(function (e) { return e.trim() }); n[1] = l.shift(), u = l, c = !0 } if ((r = t(s.call(this, n[1].trim(), a), a)) && n[0] === e && "string" != typeof r) return r; "string" != typeof r && (r = v(r)), r || (this.logger.warn("missed to resolve ".concat(n[1], " for nesting ").concat(e)), r = ""), c && (r = u.reduce(function (e, t) { return o.format(e, t, i.lng, J(J({}, i), {}, { interpolationkey: n[1].trim() })) }, r.trim())), e = e.replace(n[0], r), this.regexp.lastIndex = 0 } return e } }]), e }(); function q(e, t) { (null == t || t > e.length) && (t = e.length); for (var n = 0, r = new Array(t); n < t; n++)r[n] = e[n]; return r } function $(e) { return function (e) { if (Array.isArray(e)) return e }(e) || function (e) { if ("undefined" != typeof Symbol && null != e[Symbol.iterator] || null != e["@@iterator"]) return Array.from(e) }(e) || function (e, t) { if (e) { if ("string" == typeof e) return q(e, t); var n = Object.prototype.toString.call(e).slice(8, -1); return "Object" === n && e.constructor && (n = e.constructor.name), "Map" === n || "Set" === n ? Array.from(e) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? q(e, t) : void 0 } }(e) || function () { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.") }() } function W(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function Y(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? W(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : W(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } var G = function () { function e() { var n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; t(this, e), this.logger = g.create("formatter"), this.options = n, this.formats = { number: function (e, t, n) { return new Intl.NumberFormat(t, n).format(e) }, currency: function (e, t, n) { return new Intl.NumberFormat(t, Y(Y({}, n), {}, { style: "currency" })).format(e) }, datetime: function (e, t, n) { return new Intl.DateTimeFormat(t, Y({}, n)).format(e) }, relativetime: function (e, t, n) { return new Intl.RelativeTimeFormat(t, Y({}, n)).format(e, n.range || "day") }, list: function (e, t, n) { return new Intl.ListFormat(t, Y({}, n)).format(e) } }, this.init(n) } return r(e, [{ key: "init", value: function (e) { var t = (arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : { interpolation: {} }).interpolation; this.formatSeparator = t.formatSeparator ? t.formatSeparator : t.formatSeparator || "," } }, { key: "add", value: function (e, t) { this.formats[e.toLowerCase().trim()] = t } }, { key: "format", value: function (e, t, n, r) { var o = this; return t.split(this.formatSeparator).reduce(function (e, t) { var i = function (e) { var t = e.toLowerCase().trim(), n = {}; if (e.indexOf("(") > -1) { var r = e.split("("); t = r[0].toLowerCase().trim(); var o = r[1].substring(0, r[1].length - 1); "currency" === t && o.indexOf(":") < 0 ? n.currency || (n.currency = o.trim()) : "relativetime" === t && o.indexOf(":") < 0 ? n.range || (n.range = o.trim()) : o.split(";").forEach(function (e) { if (e) { var t = $(e.split(":")), r = t[0], o = t.slice(1).join(":"); n[r.trim()] || (n[r.trim()] = o.trim()), "false" === o.trim() && (n[r.trim()] = !1), "true" === o.trim() && (n[r.trim()] = !0), isNaN(o.trim()) || (n[r.trim()] = parseInt(o.trim(), 10)) } }) } return { formatName: t, formatOptions: n } }(t), a = i.formatName, s = i.formatOptions; if (o.formats[a]) { var u = e; try { var c = r && r.formatParams && r.formatParams[r.interpolationkey] || {}, l = c.locale || c.lng || r.locale || r.lng || n; u = o.formats[a](e, l, Y(Y(Y({}, s), r), c)) } catch (e) { o.logger.warn(e) } return u } return o.logger.warn("there was no format function for ".concat(a)), e }, e) } }]), e }(); function Q(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function X(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? Q(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : Q(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } function Z(e) { var t = function () { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () { })), !0 } catch (e) { return !1 } }(); return function () { var n, r = u(e); if (t) { var o = u(this).constructor; n = Reflect.construct(r, arguments, o) } else n = r.apply(this, arguments); return s(this, n) } } var ee = function (e) { a(i, h); var n = Z(i); function i(e, r, a) { var s, u = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}; return t(this, i), s = n.call(this), S && h.call(o(s)), s.backend = e, s.store = r, s.services = a, s.languageUtils = a.languageUtils, s.options = u, s.logger = g.create("backendConnector"), s.waitingReads = [], s.maxParallelReads = u.maxParallelReads || 10, s.readingCalls = 0, s.state = {}, s.queue = [], s.backend && s.backend.init && s.backend.init(a, u.backend, u), s } return r(i, [{ key: "queueLoad", value: function (e, t, n, r) { var o = this, i = {}, a = {}, s = {}, u = {}; return e.forEach(function (e) { var r = !0; t.forEach(function (t) { var s = "".concat(e, "|").concat(t); !n.reload && o.store.hasResourceBundle(e, t) ? o.state[s] = 2 : o.state[s] < 0 || (1 === o.state[s] ? void 0 !== a[s] && (a[s] = !0) : (o.state[s] = 1, r = !1, a[s] = !0, i[s] = !0, u[t] = !0)) }), r || (s[e] = !0) }), (Object.keys(i).length || Object.keys(a).length) && this.queue.push({ pending: a, pendingCount: Object.keys(a).length, loaded: {}, errors: [], callback: r }), { toLoad: Object.keys(i), pending: Object.keys(a), toLoadLanguages: Object.keys(s), toLoadNamespaces: Object.keys(u) } } }, { key: "loaded", value: function (e, t, n) { var r = e.split("|"), o = r[0], i = r[1]; t && this.emit("failedLoading", o, i, t), n && this.store.addResourceBundle(o, i, n), this.state[e] = t ? -1 : 2; var a = {}; this.queue.forEach(function (n) { var r, s, u, c, l, f; r = n.loaded, s = i, c = y(r, [o], Object), l = c.obj, f = c.k, l[f] = l[f] || [], u && (l[f] = l[f].concat(s)), u || l[f].push(s), function (e, t) { delete e.pending[t], e.pendingCount-- }(n, e), t && n.errors.push(t), 0 !== n.pendingCount || n.done || (Object.keys(n.loaded).forEach(function (e) { a[e] || (a[e] = {}); var t = Object.keys(a[e]); t.length && t.forEach(function (n) { void 0 !== t[n] && (a[e][n] = !0) }) }), n.done = !0, n.errors.length ? n.callback(n.errors) : n.callback()) }), this.emit("loaded", a), this.queue = this.queue.filter(function (e) { return !e.done }) } }, { key: "read", value: function (e, t, n) { var r = this, o = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : 0, i = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : 350, a = arguments.length > 5 ? arguments[5] : void 0; return e.length ? this.readingCalls >= this.maxParallelReads ? void this.waitingReads.push({ lng: e, ns: t, fcName: n, tried: o, wait: i, callback: a }) : (this.readingCalls++, this.backend[n](e, t, function (s, u) { if (s && u && o < 5) setTimeout(function () { r.read.call(r, e, t, n, o + 1, 2 * i, a) }, i); else { if (r.readingCalls--, r.waitingReads.length > 0) { var c = r.waitingReads.shift(); r.read(c.lng, c.ns, c.fcName, c.tried, c.wait, c.callback) } a(s, u) } })) : a(null, {}) } }, { key: "prepareLoading", value: function (e, t) { var n = this, r = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, o = arguments.length > 3 ? arguments[3] : void 0; if (!this.backend) return this.logger.warn("No backend was added via i18next.use. Will not load resources."), o && o(); "string" == typeof e && (e = this.languageUtils.toResolveHierarchy(e)), "string" == typeof t && (t = [t]); var i = this.queueLoad(e, t, r, o); if (!i.toLoad.length) return i.pending.length || o(), null; i.toLoad.forEach(function (e) { n.loadOne(e) }) } }, { key: "load", value: function (e, t, n) { this.prepareLoading(e, t, {}, n) } }, { key: "reload", value: function (e, t, n) { this.prepareLoading(e, t, { reload: !0 }, n) } }, { key: "loadOne", value: function (e) { var t = this, n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "", r = e.split("|"), o = r[0], i = r[1]; this.read(o, i, "read", void 0, void 0, function (r, a) { r && t.logger.warn("".concat(n, "loading namespace ").concat(i, " for language ").concat(o, " failed"), r), !r && a && t.logger.log("".concat(n, "loaded namespace ").concat(i, " for language ").concat(o), a), t.loaded(e, r, a) }) } }, { key: "saveMissing", value: function (e, t, n, r, o) { var i = arguments.length > 5 && void 0 !== arguments[5] ? arguments[5] : {}; this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(t) ? this.logger.warn('did not save key "'.concat(n, '" as the namespace "').concat(t, '" was not yet loaded'), "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!") : null != n && "" !== n && (this.backend && this.backend.create && this.backend.create(e, t, n, r, null, X(X({}, i), {}, { isUpdate: o })), e && e[0] && this.store.addResource(e[0], t, n, r)) } }]), i }(); function te(e) { return "string" == typeof e.ns && (e.ns = [e.ns]), "string" == typeof e.fallbackLng && (e.fallbackLng = [e.fallbackLng]), "string" == typeof e.fallbackNS && (e.fallbackNS = [e.fallbackNS]), e.supportedLngs && e.supportedLngs.indexOf("cimode") < 0 && (e.supportedLngs = e.supportedLngs.concat(["cimode"])), e } function ne(e, t) { var n = Object.keys(e); if (Object.getOwnPropertySymbols) { var r = Object.getOwnPropertySymbols(e); t && (r = r.filter(function (t) { return Object.getOwnPropertyDescriptor(e, t).enumerable })), n.push.apply(n, r) } return n } function re(e) { for (var t = 1; t < arguments.length; t++) { var n = null != arguments[t] ? arguments[t] : {}; t % 2 ? ne(Object(n), !0).forEach(function (t) { c(e, t, n[t]) }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : ne(Object(n)).forEach(function (t) { Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t)) }) } return e } function oe(e) { var t = function () { if ("undefined" == typeof Reflect || !Reflect.construct) return !1; if (Reflect.construct.sham) return !1; if ("function" == typeof Proxy) return !0; try { return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () { })), !0 } catch (e) { return !1 } }(); return function () { var n, r = u(e); if (t) { var o = u(this).constructor; n = Reflect.construct(r, arguments, o) } else n = r.apply(this, arguments); return s(this, n) } } function ie() { } var ae = function (n) { a(u, h); var i = oe(u); function u() { var e, n, r = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, a = arguments.length > 1 ? arguments[1] : void 0; if (t(this, u), e = i.call(this), S && h.call(o(e)), e.options = te(r), e.services = {}, e.logger = g, e.modules = { external: [] }, n = o(e), Object.getOwnPropertyNames(Object.getPrototypeOf(n)).forEach(function (e) { "function" == typeof n[e] && (n[e] = n[e].bind(n)) }), a && !e.isInitialized && !r.isClone) { if (!e.options.initImmediate) return e.init(r, a), s(e, o(e)); setTimeout(function () { e.init(r, a) }, 0) } return e } return r(u, [{ key: "init", value: function () { var t = this, n = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, r = arguments.length > 1 ? arguments[1] : void 0; "function" == typeof n && (r = n, n = {}), !n.defaultNS && n.ns && ("string" == typeof n.ns ? n.defaultNS = n.ns : n.ns.indexOf("translation") < 0 && (n.defaultNS = n.ns[0])); var o = { debug: !1, initImmediate: !0, ns: ["translation"], defaultNS: ["translation"], fallbackLng: ["dev"], fallbackNS: !1, supportedLngs: !1, nonExplicitSupportedLngs: !1, load: "all", preload: !1, simplifyPluralSuffix: !0, keySeparator: ".", nsSeparator: ":", pluralSeparator: "_", contextSeparator: "_", partialBundledLanguages: !1, saveMissing: !1, updateMissing: !1, saveMissingTo: "fallback", saveMissingPlurals: !0, missingKeyHandler: !1, missingInterpolationHandler: !1, postProcess: !1, postProcessPassResolved: !1, returnNull: !0, returnEmptyString: !0, returnObjects: !1, joinArrays: !1, returnedObjectHandler: !1, parseMissingKeyHandler: !1, appendNamespaceToMissingKey: !1, appendNamespaceToCIMode: !1, overloadTranslationOptionHandler: function (t) { var n = {}; if ("object" === e(t[1]) && (n = t[1]), "string" == typeof t[1] && (n.defaultValue = t[1]), "string" == typeof t[2] && (n.tDescription = t[2]), "object" === e(t[2]) || "object" === e(t[3])) { var r = t[3] || t[2]; Object.keys(r).forEach(function (e) { n[e] = r[e] }) } return n }, interpolation: { escapeValue: !0, format: function (e, t, n, r) { return e }, prefix: "{{", suffix: "}}", formatSeparator: ",", unescapePrefix: "-", nestingPrefix: "$t(", nestingSuffix: ")", nestingOptionsSeparator: ",", maxReplaces: 1e3, skipOnVariables: !0 } }; function i(e) { return e ? "function" == typeof e ? new e : e : null } if (this.options = re(re(re({}, o), this.options), te(n)), "v1" !== this.options.compatibilityAPI && (this.options.interpolation = re(re({}, o.interpolation), this.options.interpolation)), void 0 !== n.keySeparator && (this.options.userDefinedKeySeparator = n.keySeparator), void 0 !== n.nsSeparator && (this.options.userDefinedNsSeparator = n.nsSeparator), !this.options.isClone) { var a; this.modules.logger ? g.init(i(this.modules.logger), this.options) : g.init(null, this.options), this.modules.formatter ? a = this.modules.formatter : "undefined" != typeof Intl && (a = G); var s = new T(this.options); this.store = new N(this.options.resources, this.options); var u = this.services; u.logger = g, u.resourceStore = this.store, u.languageUtils = s, u.pluralResolver = new H(s, { prepend: this.options.pluralSeparator, compatibilityJSON: this.options.compatibilityJSON, simplifyPluralSuffix: this.options.simplifyPluralSuffix }), !a || this.options.interpolation.format && this.options.interpolation.format !== o.interpolation.format || (u.formatter = i(a), u.formatter.init(u, this.options), this.options.interpolation.format = u.formatter.format.bind(u.formatter)), u.interpolator = new _(this.options), u.utils = { hasLoadedNamespace: this.hasLoadedNamespace.bind(this) }, u.backendConnector = new ee(i(this.modules.backend), u.resourceStore, u, this.options), u.backendConnector.on("*", function (e) { for (var n = arguments.length, r = new Array(n > 1 ? n - 1 : 0), o = 1; o < n; o++)r[o - 1] = arguments[o]; t.emit.apply(t, [e].concat(r)) }), this.modules.languageDetector && (u.languageDetector = i(this.modules.languageDetector), u.languageDetector.init(u, this.options.detection, this.options)), this.modules.i18nFormat && (u.i18nFormat = i(this.modules.i18nFormat), u.i18nFormat.init && u.i18nFormat.init(this)), this.translator = new A(this.services, this.options), this.translator.on("*", function (e) { for (var n = arguments.length, r = new Array(n > 1 ? n - 1 : 0), o = 1; o < n; o++)r[o - 1] = arguments[o]; t.emit.apply(t, [e].concat(r)) }), this.modules.external.forEach(function (e) { e.init && e.init(t) }) } if (this.format = this.options.interpolation.format, r || (r = ie), this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { var c = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); c.length > 0 && "dev" !== c[0] && (this.options.lng = c[0]) } this.services.languageDetector || this.options.lng || this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"].forEach(function (e) { t[e] = function () { var n; return (n = t.store)[e].apply(n, arguments) } });["addResource", "addResources", "addResourceBundle", "removeResourceBundle"].forEach(function (e) { t[e] = function () { var n; return (n = t.store)[e].apply(n, arguments), t } }); var l = d(), f = function () { var e = function (e, n) { t.isInitialized && !t.initializedStoreOnce && t.logger.warn("init: i18next is already initialized. You should call init just once!"), t.isInitialized = !0, t.options.isClone || t.logger.log("initialized", t.options), t.emit("initialized", t.options), l.resolve(n), r(e, n) }; if (t.languages && "v1" !== t.options.compatibilityAPI && !t.isInitialized) return e(null, t.t.bind(t)); t.changeLanguage(t.options.lng, e) }; return this.options.resources || !this.options.initImmediate ? f() : setTimeout(f, 0), l } }, { key: "loadResources", value: function (e) { var t = this, n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : ie, r = "string" == typeof e ? e : this.language; if ("function" == typeof e && (n = e), !this.options.resources || this.options.partialBundledLanguages) { if (r && "cimode" === r.toLowerCase()) return n(); var o = [], i = function (e) { e && t.services.languageUtils.toResolveHierarchy(e).forEach(function (e) { o.indexOf(e) < 0 && o.push(e) }) }; if (r) i(r); else this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(function (e) { return i(e) }); this.options.preload && this.options.preload.forEach(function (e) { return i(e) }), this.services.backendConnector.load(o, this.options.ns, function (e) { e || t.resolvedLanguage || !t.language || t.setResolvedLanguage(t.language), n(e) }) } else n(null) } }, { key: "reloadResources", value: function (e, t, n) { var r = d(); return e || (e = this.languages), t || (t = this.options.ns), n || (n = ie), this.services.backendConnector.reload(e, t, function (e) { r.resolve(), n(e) }), r } }, { key: "use", value: function (e) { if (!e) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()"); if (!e.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()"); return "backend" === e.type && (this.modules.backend = e), ("logger" === e.type || e.log && e.warn && e.error) && (this.modules.logger = e), "languageDetector" === e.type && (this.modules.languageDetector = e), "i18nFormat" === e.type && (this.modules.i18nFormat = e), "postProcessor" === e.type && C.addPostProcessor(e), "formatter" === e.type && (this.modules.formatter = e), "3rdParty" === e.type && this.modules.external.push(e), this } }, { key: "setResolvedLanguage", value: function (e) { if (e && this.languages && !(["cimode", "dev"].indexOf(e) > -1)) for (var t = 0; t < this.languages.length; t++) { var n = this.languages[t]; if (!(["cimode", "dev"].indexOf(n) > -1) && this.store.hasLanguageSomeTranslations(n)) { this.resolvedLanguage = n; break } } } }, { key: "changeLanguage", value: function (e, t) { var n = this; this.isLanguageChangingTo = e; var r = d(); this.emit("languageChanging", e); var o = function (e) { n.language = e, n.languages = n.services.languageUtils.toResolveHierarchy(e), n.resolvedLanguage = void 0, n.setResolvedLanguage(e) }, i = function (i) { e || i || !n.services.languageDetector || (i = []); var a = "string" == typeof i ? i : n.services.languageUtils.getBestMatchFromCodes(i); a && (n.language || o(a), n.translator.language || n.translator.changeLanguage(a), n.services.languageDetector && n.services.languageDetector.cacheUserLanguage(a)), n.loadResources(a, function (e) { !function (e, i) { i ? (o(i), n.translator.changeLanguage(i), n.isLanguageChangingTo = void 0, n.emit("languageChanged", i), n.logger.log("languageChanged", i)) : n.isLanguageChangingTo = void 0, r.resolve(function () { return n.t.apply(n, arguments) }), t && t(e, function () { return n.t.apply(n, arguments) }) }(e, a) }) }; return e || !this.services.languageDetector || this.services.languageDetector.async ? !e && this.services.languageDetector && this.services.languageDetector.async ? this.services.languageDetector.detect(i) : i(e) : i(this.services.languageDetector.detect()), r } }, { key: "getFixedT", value: function (t, n, r) { var o = this, i = function t(n, i) { var a; if ("object" !== e(i)) { for (var s = arguments.length, u = new Array(s > 2 ? s - 2 : 0), c = 2; c < s; c++)u[c - 2] = arguments[c]; a = o.options.overloadTranslationOptionHandler([n, i].concat(u)) } else a = re({}, i); a.lng = a.lng || t.lng, a.lngs = a.lngs || t.lngs, a.ns = a.ns || t.ns; var l = o.options.keySeparator || ".", f = r ? "".concat(r).concat(l).concat(n) : n; return o.t(f, a) }; return "string" == typeof t ? i.lng = t : i.lngs = t, i.ns = n, i.keyPrefix = r, i } }, { key: "t", value: function () { var e; return this.translator && (e = this.translator).translate.apply(e, arguments) } }, { key: "exists", value: function () { var e; return this.translator && (e = this.translator).exists.apply(e, arguments) } }, { key: "setDefaultNamespace", value: function (e) { this.options.defaultNS = e } }, { key: "hasLoadedNamespace", value: function (e) { var t = this, n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; if (!this.isInitialized) return this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages), !1; if (!this.languages || !this.languages.length) return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages), !1; var r = this.resolvedLanguage || this.languages[0], o = !!this.options && this.options.fallbackLng, i = this.languages[this.languages.length - 1]; if ("cimode" === r.toLowerCase()) return !0; var a = function (e, n) { var r = t.services.backendConnector.state["".concat(e, "|").concat(n)]; return -1 === r || 2 === r }; if (n.precheck) { var s = n.precheck(this, a); if (void 0 !== s) return s } return !!this.hasResourceBundle(r, e) || (!(this.services.backendConnector.backend && (!this.options.resources || this.options.partialBundledLanguages)) || !(!a(r, e) || o && !a(i, e))) } }, { key: "loadNamespaces", value: function (e, t) { var n = this, r = d(); return this.options.ns ? ("string" == typeof e && (e = [e]), e.forEach(function (e) { n.options.ns.indexOf(e) < 0 && n.options.ns.push(e) }), this.loadResources(function (e) { r.resolve(), t && t(e) }), r) : (t && t(), Promise.resolve()) } }, { key: "loadLanguages", value: function (e, t) { var n = d(); "string" == typeof e && (e = [e]); var r = this.options.preload || [], o = e.filter(function (e) { return r.indexOf(e) < 0 }); return o.length ? (this.options.preload = r.concat(o), this.loadResources(function (e) { n.resolve(), t && t(e) }), n) : (t && t(), Promise.resolve()) } }, { key: "dir", value: function (e) { if (e || (e = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language)), !e) return "rtl"; return ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"].indexOf(this.services.languageUtils.getLanguagePartFromCode(e)) > -1 || e.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr" } }, { key: "cloneInstance", value: function () { var e = this, t = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : ie, r = re(re(re({}, this.options), t), { isClone: !0 }), o = new u(r); return ["store", "services", "language"].forEach(function (t) { o[t] = e[t] }), o.services = re({}, this.services), o.services.utils = { hasLoadedNamespace: o.hasLoadedNamespace.bind(o) }, o.translator = new A(o.services, o.options), o.translator.on("*", function (e) { for (var t = arguments.length, n = new Array(t > 1 ? t - 1 : 0), r = 1; r < t; r++)n[r - 1] = arguments[r]; o.emit.apply(o, [e].concat(n)) }), o.init(r, n), o.translator.options = o.options, o.translator.backendConnector.services.utils = { hasLoadedNamespace: o.hasLoadedNamespace.bind(o) }, o } }, { key: "toJSON", value: function () { return { options: this.options, store: this.store, language: this.language, languages: this.languages, resolvedLanguage: this.resolvedLanguage } } }]), u }(); c(ae, "createInstance", function () { var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, t = arguments.length > 1 ? arguments[1] : void 0; return new ae(e, t) }); var se = ae.createInstance(); return se.createInstance = ae.createInstance, se });
//Included:lib/011.vue-i18next-v0.15.2.js
// ~$ npm install @panter/vue-i18next@0.15.2
(function (factory) {
// Only navigators:
if (typeof window === 'undefined') return;
// General boilerplate:
if (typeof window !== "undefined") {
if ("VueI18n" in window) return window.VueI18n;
}
if (typeof global !== "undefined") {
if ("VueI18n" in global) return global.VueI18n;
}
const output = factory();
if (typeof module === 'object' && typeof module.exports === 'object') module.exports = output;
if (typeof define === 'function' && define.amd) define([], factory);
if (typeof exports === 'object') exports["VueI18n"] = output;
if (typeof window !== "undefined") {
if (typeof window !== 'undefined') window.VueI18n = output;
}
if (typeof global !== "undefined") {
if (typeof global !== 'undefined') global.VueI18n = output;
}
return output;
}(function () {
'use strict';
var isMergeableObject = function isMergeableObject(value) {
return isNonNullObject(value)
&& !isSpecial(value)
};
function isNonNullObject(value) {
return !!value && typeof value === 'object'
}
function isSpecial(value) {
var stringValue = Object.prototype.toString.call(value);
return stringValue === '[object RegExp]'
|| stringValue === '[object Date]'
|| isReactElement(value)
}
// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
function isReactElement(value) {
return value.$$typeof === REACT_ELEMENT_TYPE
}
function emptyTarget(val) {
return Array.isArray(val) ? [] : {}
}
function cloneUnlessOtherwiseSpecified(value, options) {
return (options.clone !== false && options.isMergeableObject(value))
? deepmerge(emptyTarget(value), value, options)
: value
}
function defaultArrayMerge(target, source, options) {
return target.concat(source).map(function (element) {
return cloneUnlessOtherwiseSpecified(element, options)
})
}
function mergeObject(target, source, options) {
var destination = {};
if (options.isMergeableObject(target)) {
Object.keys(target).forEach(function (key) {
destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
});
}
Object.keys(source).forEach(function (key) {
if (!options.isMergeableObject(source[key]) || !target[key]) {
destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
} else {
destination[key] = deepmerge(target[key], source[key], options);
}
});
return destination
}
function deepmerge(target, source, options) {
options = options || {};
options.arrayMerge = options.arrayMerge || defaultArrayMerge;
options.isMergeableObject = options.isMergeableObject || isMergeableObject;
var sourceIsArray = Array.isArray(source);
var targetIsArray = Array.isArray(target);
var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
if (!sourceAndTargetTypesMatch) {
return cloneUnlessOtherwiseSpecified(source, options)
} else if (sourceIsArray) {
return options.arrayMerge(target, source, options)
} else {
return mergeObject(target, source, options)
}
}
deepmerge.all = function deepmergeAll(array, options) {
if (!Array.isArray(array)) {
throw new Error('first argument should be an array')
}
return array.reduce(function (prev, next) {
return deepmerge(prev, next, options)
}, {})
};
var deepmerge_1 = deepmerge;
var component = {
name: 'i18next',
functional: true,
props: {
tag: {
type: String,
default: 'span'
},
path: {
type: String,
required: true
},
options: {
type: Object
}
},
render: function render(h, ref) {
var props = ref.props;
var data = ref.data;
var children = ref.children;
var parent = ref.parent;
var i18next = parent.$i18n;
var $t = parent.$t.bind(parent);
if (!i18next || !$t) {
return h(props.tag, data, children);
}
var path = props.path;
var options = props.options || {};
var REGEXP = i18next.i18next.services.interpolator.regexp;
var i18nextOptions = Object.assign({}, options,
{ interpolation: { prefix: '#$?', suffix: '?$#' } });
var format = $t(path, i18nextOptions);
var tchildren = [];
format.split(REGEXP).reduce(function (memo, match, index) {
var child;
if (index % 2 === 0) {
if (match.length === 0) { return memo; }
child = match;
} else {
var place = match.trim();
// eslint-disable-next-line no-restricted-globals
if (isNaN(parseFloat(place)) || !isFinite(place)) {
children.forEach(function (e) {
if (
!child &&
e.data.attrs &&
e.data.attrs.place &&
e.data.attrs.place === place
) {
child = e;
}
});
} else {
child = children[parseInt(match, 10)];
}
}
memo.push(child);
return memo;
}, tchildren);
return h(props.tag, data, tchildren);
}
};
/* eslint-disable import/prefer-default-export */
function log(message) {
if (typeof console !== 'undefined') {
console.warn(message); // eslint-disable-line no-console
}
}
function warn(message) {
log(("[vue-i18next warn]: " + message));
}
function deprecate(message) {
log(("[vue-i18next deprecated]: " + message));
}
/* eslint-disable no-param-reassign, no-unused-vars */
function equalLanguage(el, vnode) {
var vm = vnode.context;
return el._i18nLanguage === vm.$i18n.i18next.language;
}
function equalValue(value, oldValue) {
if (value === oldValue) {
return true;
}
if (value && oldValue) {
return (
value.path === oldValue.path &&
value.language === oldValue.language &&
value.args === oldValue.args
);
}
}
function assert(vnode) {
var vm = vnode.context;
if (!vm.$i18n) {
warn('No VueI18Next instance found in the Vue instance');
return false;
}
return true;
}
function parseValue(value) {
var assign;
var path;
var language;
var args;
if (typeof value === 'string') {
path = value;
} else if (toString.call(value) === '[object Object]') {
((assign = value, path = assign.path, language = assign.language, args = assign.args));
}
return { path: path, language: language, args: args };
}
function t(el, binding, vnode) {
var value = binding.value;
var ref = parseValue(value);
var path = ref.path;
var language = ref.language;
var args = ref.args;
if (!path && !language && !args) {
warn('v-t: invalid value');
return;
}
if (!path) {
warn('v-t: "path" is required');
return;
}
if (language) {
deprecate("v-t: \"language\" is deprecated.Use the \"lng\" property in args.\n https://www.i18next.com/overview/configuration-options#configuration-options");
}
var vm = vnode.context;
el.textContent = vm.$i18n.i18next.t(path, Object.assign({}, (language ? { lng: language } : {}),
args));
el._i18nLanguage = vm.$i18n.i18next.language;
}
function bind(el, binding, vnode) {
if (!assert(vnode)) {
return;
}
t(el, binding, vnode);
}
function update(el, binding, vnode, oldVNode) {
if (equalLanguage(el, vnode) && equalValue(binding.value, binding.oldValue)) {
return;
}
t(el, binding, vnode);
}
var directive = {
bind: bind,
update: update
};
/* eslint-disable no-param-reassign, no-unused-vars */
function assert$1(vnode) {
var vm = vnode.context;
if (!vm.$i18n) {
warn('No VueI18Next instance found in the Vue instance');
return false;
}
return true;
}
function waitForIt(el, vnode) {
if (vnode.context.$i18n.i18next.isInitialized) {
el.hidden = false;
} else {
el.hidden = true;
var initialized = function () {
vnode.context.$forceUpdate();
// due to emitter removing issue in i18next we need to delay remove
setTimeout(function () {
if (vnode.context && vnode.context.$i18n) {
vnode.context.$i18n.i18next.off('initialized', initialized);
}
}, 1000);
};
vnode.context.$i18n.i18next.on('initialized', initialized);
}
}
function bind$1(el, binding, vnode) {
if (!assert$1(vnode)) {
return;
}
waitForIt(el, vnode);
}
function update$1(el, binding, vnode, oldVNode) {
if (vnode.context.$i18n.i18next.isInitialized) {
el.hidden = false;
}
}
var waitDirective = {
bind: bind$1,
update: update$1
};
/* eslint-disable import/no-mutable-exports */
var Vue;
function install(_Vue) {
if (install.installed) {
return;
}
install.installed = true;
Vue = _Vue;
var getByKey = function (i18nOptions, i18nextOptions) {
return function (key) {
if (
i18nOptions &&
i18nOptions.keyPrefix &&
!key.includes(i18nextOptions.nsSeparator)
) {
return ((i18nOptions.keyPrefix) + "." + key);
}
return key;
};
};
var getComponentNamespace = function (vm) {
var namespace = vm.$options.name || vm.$options._componentTag;
if (namespace) {
return {
namespace: namespace,
loadNamespace: true
};
}
return {
namespace: ("" + (Math.random()))
};
};
Vue.mixin({
beforeCreate: function beforeCreate() {
var this$1 = this;
var options = this.$options;
if (options.i18n) {
this._i18n = options.i18n;
} else if (options.parent && options.parent.$i18n) {
this._i18n = options.parent.$i18n;
}
var inlineTranslations = {};
if (this._i18n) {
var getNamespace =
this._i18n.options.getComponentNamespace || getComponentNamespace;
var ref = getNamespace(this);
var namespace = ref.namespace;
var loadNamespace = ref.loadNamespace;
if (options.__i18n) {
options.__i18n.forEach(function (resource) {
inlineTranslations = deepmerge_1(
inlineTranslations,
JSON.parse(resource)
);
});
}
if (options.i18nOptions) {
var ref$1 = this.$options.i18nOptions;
var lng = ref$1.lng; if (lng === void 0) lng = null;
var keyPrefix = ref$1.keyPrefix; if (keyPrefix === void 0) keyPrefix = null;
var messages = ref$1.messages;
var ref$2 = this.$options.i18nOptions;
var namespaces = ref$2.namespaces;
namespaces = namespaces || this._i18n.i18next.options.defaultNS;
if (typeof namespaces === 'string') { namespaces = [namespaces]; }
var namespacesToLoad = namespaces.concat([namespace]);
if (messages) {
inlineTranslations = deepmerge_1(inlineTranslations, messages);
}
this._i18nOptions = { lng: lng, namespaces: namespacesToLoad, keyPrefix: keyPrefix };
this._i18n.i18next.loadNamespaces(namespaces);
} else if (options.parent && options.parent._i18nOptions) {
this._i18nOptions = Object.assign({}, options.parent._i18nOptions);
this._i18nOptions.namespaces = [
namespace].concat(this._i18nOptions.namespaces
);
} else if (options.__i18n) {
this._i18nOptions = { namespaces: [namespace] };
}
if (loadNamespace && this._i18n.options.loadComponentNamespace) {
this._i18n.i18next.loadNamespaces([namespace]);
}
var languages = Object.keys(inlineTranslations);
languages.forEach(function (lang) {
this$1._i18n.i18next.addResourceBundle(
lang,
namespace,
Object.assign({}, inlineTranslations[lang]),
true,
false
);
});
}
var getKey = getByKey(
this._i18nOptions,
this._i18n ? this._i18n.i18next.options : {}
);
if (this._i18nOptions && this._i18nOptions.namespaces) {
var ref$3 = this._i18nOptions;
var lng$1 = ref$3.lng;
var namespaces$1 = ref$3.namespaces;
var fixedT = this._i18n.i18next.getFixedT(lng$1, namespaces$1);
this._getI18nKey = function (key, i18nextOptions) { return fixedT(getKey(key), i18nextOptions, this$1._i18n.i18nLoadedAt); };
} else {
this._getI18nKey = function (key, i18nextOptions) { return this$1._i18n.t(getKey(key), i18nextOptions, this$1._i18n.i18nLoadedAt); };
}
}
});
// extend Vue.js
if (!Object.prototype.hasOwnProperty.call(Vue.prototype, '$i18n')) {
Object.defineProperty(Vue.prototype, '$i18n', {
get: function get() {
return this._i18n;
}
});
}
Vue.prototype.$t = function t(key, options) {
return this._getI18nKey(key, options);
};
Vue.component(component.name, component);
Vue.directive('t', directive);
Vue.directive('waitForT', waitDirective);
}
var VueI18n = function VueI18n(i18next, opts) {
if (opts === void 0) opts = {};
var options = Object.assign({}, {
bindI18n: 'languageChanged loaded',
bindStore: 'added removed',
loadComponentNamespace: false
},
opts);
this._vm = null;
this.i18next = i18next;
this.options = options;
this.onI18nChanged = this.onI18nChanged.bind(this);
if (options.bindI18n) {
this.i18next.on(options.bindI18n, this.onI18nChanged);
}
if (options.bindStore && this.i18next.store) {
this.i18next.store.on(options.bindStore, this.onI18nChanged);
}
this.resetVM({ i18nLoadedAt: new Date() });
};
var prototypeAccessors = { i18nLoadedAt: { configurable: true } };
VueI18n.prototype.resetVM = function resetVM(data) {
var oldVM = this._vm;
var ref = Vue.config;
var silent = ref.silent;
Vue.config.silent = true;
this._vm = new Vue({ data: data });
Vue.config.silent = silent;
if (oldVM) {
Vue.nextTick(function () { return oldVM.$destroy(); });
}
};
prototypeAccessors.i18nLoadedAt.get = function () {
return this._vm.$data.i18nLoadedAt;
};
prototypeAccessors.i18nLoadedAt.set = function (date) {
this._vm.$set(this._vm, 'i18nLoadedAt', date);
};
VueI18n.prototype.t = function t(key, options) {
return this.i18next.t(key, options);
};
VueI18n.prototype.onI18nChanged = function onI18nChanged() {
this.i18nLoadedAt = new Date();
};
Object.defineProperties(VueI18n.prototype, prototypeAccessors);
VueI18n.install = install;
VueI18n.version = "0.15.2";
/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(VueI18n);
}
return VueI18n;
}));
//Included:lib/012.ranas-db-v0.0.1.part.js
(() => { var t = { 363: function (t) { t.exports = function () { class t { static that(...t) { return new this(...t) } constructor(t, n = "?", e = "xxxxx") { this.target = t, this.targetID = n, this.errorID = e, this.and = this } equals(t, n) { if (this.target === t) return this; throw new Error("Expected <" + this.targetID + "> to equal <" + (n || t) + "> [ERROR:" + this.errorID + "]") } isUndefined() { if (void 0 === this.target) return this; throw new Error("Expected <" + this.targetID + "> to be undefined [ERROR:" + this.errorID + "]") } isNotUndefined() { if (void 0 !== this.target) return this; throw new Error("Expected <" + this.targetID + "> to not be undefined [ERROR:" + this.errorID + "]") } isNumber() { if ("number" == typeof this.target) return this; throw new Error("Expected <" + this.targetID + "> to be a number [ERROR:" + this.errorID + "]") } isString() { if ("string" == typeof this.target) return this; throw new Error("Expected <" + this.targetID + "> to be a string [ERROR:" + this.errorID + "]") } isObject() { if ("object" == typeof this.target) return this; throw new Error("Expected <" + this.targetID + "> to be an object [ERROR:" + this.errorID + "]") } isFunction() { if ("function" == typeof this.target) return this; throw new Error("Expected <" + this.targetID + "> to be a function [ERROR:" + this.errorID + "]") } isArray() { if (Array.isArray(this.target)) return this; throw new Error("Expected <" + this.targetID + "> to be an array [ERROR:" + this.errorID + "]") } isGreaterThan(t, n) { try { if (this.target > t) return this } catch (e) { throw new Error("Expected <" + this.targetID + "> to be -comparable as- greater than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to be greater than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } isLowerThan(t, n) { try { if (this.target < t) return this } catch (e) { throw new Error("Expected <" + this.targetID + "> to be -comparable as- lower than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to be lower than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } isInstanceOf(t, n = !1) { try { if (this.target instanceof t) return this } catch (e) { throw new Error("Expected <" + this.targetID + "> to be -comparable as- instance of <" + (n || t) + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to be an instance of <" + (n || t) + "> [ERROR:" + this.errorID + "]") } isDate() { try { if (this.target instanceof Date) return this } catch (t) { throw new Error("Expected <" + this.targetID + "> to be -comparable as- a date [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to be a date [ERROR:" + this.errorID + "]") } hasLengthGreaterThan(t, n) { try { if (this.target.length > t) return this } catch (e) { throw new Error("Expected <" + this.targetID + "> to have a length -comparable as- greater than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to have a length greater than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } hasLengthLowerThan(t, n) { try { if (this.target.length < t) return this } catch (e) { throw new Error("Expected <" + this.targetID + "> to have a length -comparable as- lower than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to have a length lower than <" + (n || t) + "> [ERROR:" + this.errorID + "]") } can(t, n = "?") { try { if ("function" == typeof t && !0 === t(this.target, this)) return this } catch (t) { throw new Error("Expected <" + this.targetID + "> to -be called and to- be able to <" + n + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to be able to <" + n + "> [ERROR:" + this.errorID + "]") } cannot(t, n = "?") { try { if ("function" == typeof t && !1 === t(this.target, this)) return this } catch (t) { throw new Error("Expected <" + this.targetID + "> to -be called and to- not be able to <" + n + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to not be able to <" + n + "> [ERROR:" + this.errorID + "]") } throwsOn(t, n = "?") { if ("function" == typeof t) { try { t(this.target, this) } catch (t) { return this } throw new Error("Expected <" + this.targetID + "> to throw errors on <" + n + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to -be called and to- throw errors on <" + n + "> [ERROR:" + this.errorID + "]") } doesNotThrowOn(t, n = "?") { try { if ("function" == typeof t) return t(this.target, this), this } catch (t) { throw new Error("Expected <" + this.targetID + "> to not throw errors on <" + n + "> [ERROR:" + this.errorID + "]") } throw new Error("Expected <" + this.targetID + "> to -be called and to- not throw errors on <" + n + "> [ERROR:" + this.errorID + "]") } } return t.default = t, t }() }, 534: function (t, n, e) { t.exports = function (t) { "use strict"; t = "default" in t ? t.default : t; var n = function (t) { this.schema = t }; function e(t) { return null != t && ("string" == typeof t || "number" == typeof t || t instanceof Date || Array.isArray(t) && t.every(e)) } n.prototype.getForeignKeys = function () { var t = this, n = {}; return Object.keys(this.schema).forEach((function (e) { var r = t.schema[e].split(","); n[e] = r.filter((function (t) { return -1 !== t.indexOf("->") })).map((function (t) { var n = t.split("->").map((function (t) { return t.trim() })), e = n[0], r = n[1]; return { index: e, targetTable: r.split(".")[0], targetIndex: r.split(".")[1] } })) })), n }, n.prototype.getCleanedSchema = function () { var t = this, n = {}; return Object.keys(this.schema).forEach((function (e) { var r = t.schema[e].split(","); n[e] = r.map((function (t) { return t.split("->")[0].trim() })).join(",") })), n }; var r = function (r) { var i = t.Promise; r.Table.prototype.with = function (t) { return this.toCollection().with(t) }, r.Collection.prototype.with = function (t) { var n = this, o = this._ctx.table.name, a = r._allTables, u = []; return Object.keys(t).forEach((function (e) { var r = t[e], i = n._ctx.table.schema.idxByName[r]; if (i && i.hasOwnProperty("foreignKey")) { var s = i; u.push({ column: e, index: s.foreignKey.targetIndex, tableName: s.foreignKey.targetTable, targetIndex: s.foreignKey.index, oneToOne: !0 }) } else { var c = r; if (!a.hasOwnProperty(c)) throw new Error("Relationship table " + c + " doesn't exist."); if (!a[c].schema.hasOwnProperty("foreignKeys")) throw new Error("Relationship table " + c + " doesn't have foreign keys set."); var f = a[c].schema.foreignKeys.filter((function (t) { return t.targetTable === o })); f.length > 0 && u.push({ column: e, index: f[0].index, tableName: c, targetIndex: f[0].targetIndex }) } })), this.toArray().then((function (t) { var n = u.map((function (n) { var r = n.tableName, i = t.map((function (t) { return t[n.targetIndex] })).filter(e); return a[r].where(n.index).anyOf(i) })).map((function (t) { return t.toArray() })); return i.all(n).then((function (n) { u.forEach((function (e, r) { var i = e.tableName, a = n[r], u = e.targetIndex, s = e.index, c = e.column, f = {}; a.forEach((function (t) { var n = t[s]; e.oneToOne ? f[n] = t : (f[n] = f[n] || []).push(t) })), t.forEach((function (t) { var n = t[u], e = f[n] || []; if (null != n && !e) throw new Error("Could not lookup foreign key where " + i + "." + s + " == " + o + "." + c + ". The content of the failing key was: " + JSON.stringify(n) + "."); Object.defineProperty(t, c, { value: e, enumerable: !1, configurable: !0, writable: !0 }) })) })) })).then((function () { return t })) })) }, r.Version.prototype._parseStoresSpec = t.override(r.Version.prototype._parseStoresSpec, (function (t) { return function (e, r) { var i = new n(e), o = i.getForeignKeys(), a = t.call(this, i.getCleanedSchema(), r); return Object.keys(r).forEach((function (t) { o.hasOwnProperty(t) && (r[t].foreignKeys = o[t], o[t].forEach((function (n) { r[t].idxByName[n.index].foreignKey = n }))) })), a } })) }; return r.default = r, r }(e(128)) }, 128: (t, n, e) => { "use strict"; e.r(n), e.d(n, { default: () => Mn }); var r = Object.keys, i = Array.isArray, o = "undefined" != typeof self ? self : "undefined" != typeof window ? window : e.g; function a(t, n) { return "object" != typeof n || r(n).forEach((function (e) { t[e] = n[e] })), t } var u = Object.getPrototypeOf, s = {}.hasOwnProperty; function c(t, n) { return s.call(t, n) } function f(t, n) { "function" == typeof n && (n = n(u(t))), r(n).forEach((function (e) { l(t, e, n[e]) })) } var h = Object.defineProperty; function l(t, n, e, r) { h(t, n, a(e && c(e, "get") && "function" == typeof e.get ? { get: e.get, set: e.set, configurable: !0 } : { value: e, configurable: !0, writable: !0 }, r)) } function d(t) { return { from: function (n) { return t.prototype = Object.create(n.prototype), l(t.prototype, "constructor", t), { extend: f.bind(null, t.prototype) } } } } var p = Object.getOwnPropertyDescriptor; function v(t, n) { var e; return p(t, n) || (e = u(t)) && v(e, n) } var g = [].slice; function y(t, n, e) { return g.call(t, n, e) } function m(t, n) { return n(t) } function b(t) { if (!t) throw new Error("Assertion Failed") } function w(t) { o.setImmediate ? setImmediate(t) : setTimeout(t, 0) } function _(t, n) { return t.reduce((function (t, e, r) { var i = n(e, r); return i && (t[i[0]] = i[1]), t }), {}) } function x(t, n, e) { try { t.apply(null, e) } catch (t) { n && n(t) } } function E(t, n) { if (c(t, n)) return t[n]; if (!n) return t; if ("string" != typeof n) { for (var e = [], r = 0, i = n.length; r < i; ++r) { var o = E(t, n[r]); e.push(o) } return e } var a = n.indexOf("."); if (-1 !== a) { var u = t[n.substr(0, a)]; return void 0 === u ? void 0 : E(u, n.substr(a + 1)) } } function k(t, n, e) { if (t && void 0 !== n && (!("isFrozen" in Object) || !Object.isFrozen(t))) if ("string" != typeof n && "length" in n) { b("string" != typeof e && "length" in e); for (var r = 0, i = n.length; r < i; ++r)k(t, n[r], e[r]) } else { var o = n.indexOf("."); if (-1 !== o) { var a = n.substr(0, o), u = n.substr(o + 1); if ("" === u) void 0 === e ? delete t[a] : t[a] = e; else { var s = t[a]; s || (s = t[a] = {}), k(s, u, e) } } else void 0 === e ? delete t[n] : t[n] = e } } function D(t) { var n = {}; for (var e in t) c(t, e) && (n[e] = t[e]); return n } var I = [].concat; function O(t) { return I.apply([], t) } var R = "Boolean,String,Date,RegExp,Blob,File,FileList,ArrayBuffer,DataView,Uint8ClampedArray,ImageData,Map,Set".split(",").concat(O([8, 16, 32, 64].map((function (t) { return ["Int", "Uint", "Float"].map((function (n) { return n + t + "Array" })) })))).filter((function (t) { return o[t] })).map((function (t) { return o[t] })); function j(t) { if (!t || "object" != typeof t) return t; var n; if (i(t)) { n = []; for (var e = 0, r = t.length; e < r; ++e)n.push(j(t[e])) } else if (R.indexOf(t.constructor) >= 0) n = t; else for (var o in n = t.constructor ? Object.create(t.constructor.prototype) : {}, t) c(t, o) && (n[o] = j(t[o])); return n } function P(t, n, e, i) { return e = e || {}, i = i || "", r(t).forEach((function (r) { if (c(n, r)) { var o = t[r], a = n[r]; "object" == typeof o && "object" == typeof a && o && a && "" + o.constructor == "" + a.constructor ? P(o, a, e, i + r + ".") : o !== a && (e[i + r] = n[r]) } else e[i + r] = void 0 })), r(n).forEach((function (r) { c(t, r) || (e[i + r] = n[r]) })), e } var S = "undefined" != typeof Symbol && Symbol.iterator, A = S ? function (t) { var n; return null != t && (n = t[S]) && n.apply(t) } : function () { return null }, T = {}; function C(t) { var n, e, r, o; if (1 === arguments.length) { if (i(t)) return t.slice(); if (this === T && "string" == typeof t) return [t]; if (o = A(t)) { for (e = []; !(r = o.next()).done;)e.push(r.value); return e } if (null == t) return [t]; if ("number" == typeof (n = t.length)) { for (e = new Array(n); n--;)e[n] = t[n]; return e } return [t] } for (n = arguments.length, e = new Array(n); n--;)e[n] = arguments[n]; return e } var K = "undefined" != typeof location && /^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href); function B(t, n) { K = t, F = n } var F = function () { return !0 }, N = !new Error("").stack; function M() { if (N) try { throw M.arguments, new Error } catch (t) { return t } return new Error } function q(t, n) { var e = t.stack; return e ? (n = n || 0, 0 === e.indexOf(t.name) && (n += (t.name + t.message).split("\n").length), e.split("\n").slice(n).filter(F).map((function (t) { return "\n" + t })).join("")) : "" } var U = ["Unknown", "Constraint", "Data", "TransactionInactive", "ReadOnly", "Version", "NotFound", "InvalidState", "InvalidAccess", "Abort", "Timeout", "QuotaExceeded", "Syntax", "DataClone"], L = ["Modify", "Bulk", "OpenFailed", "VersionChange", "Schema", "Upgrade", "InvalidTable", "MissingAPI", "NoSuchDatabase", "InvalidArgument", "SubTransaction", "Unsupported", "Internal", "DatabaseClosed", "PrematureCommit", "ForeignAwait"].concat(U), V = { VersionChanged: "Database version changed by other database connection", DatabaseClosed: "Database has been closed", Abort: "Transaction aborted", TransactionInactive: "Transaction has already completed or failed" }; function z(t, n) { this._e = M(), this.name = t, this.message = n } function W(t, n, e, r) { this._e = M(), this.failures = n, this.failedKeys = r, this.successCount = e } function $(t, n) { this._e = M(), this.name = "BulkError", this.failures = n, this.message = function (t, n) { return t + ". Errors: " + n.map((function (t) { return t.toString() })).filter((function (t, n, e) { return e.indexOf(t) === n })).join("\n") }(t, n) } d(z).from(Error).extend({ stack: { get: function () { return this._stack || (this._stack = this.name + ": " + this.message + q(this._e, 2)) } }, toString: function () { return this.name + ": " + this.message } }), d(W).from(z), d($).from(z); var G = L.reduce((function (t, n) { return t[n] = n + "Error", t }), {}), Q = z, H = L.reduce((function (t, n) { var e = n + "Error"; function r(t, r) { this._e = M(), this.name = e, t ? "string" == typeof t ? (this.message = t, this.inner = r || null) : "object" == typeof t && (this.message = t.name + " " + t.message, this.inner = t) : (this.message = V[n] || e, this.inner = null) } return d(r).from(Q), t[n] = r, t }), {}); H.Syntax = SyntaxError, H.Type = TypeError, H.Range = RangeError; var J = U.reduce((function (t, n) { return t[n + "Error"] = H[n], t }), {}), Y = L.reduce((function (t, n) { return -1 === ["Syntax", "Type", "Range"].indexOf(n) && (t[n + "Error"] = H[n]), t }), {}); function X() { } function Z(t) { return t } function tt(t, n) { return null == t || t === Z ? n : function (e) { return n(t(e)) } } function nt(t, n) { return function () { t.apply(this, arguments), n.apply(this, arguments) } } function et(t, n) { return t === X ? n : function () { var e = t.apply(this, arguments); void 0 !== e && (arguments[0] = e); var r = this.onsuccess, i = this.onerror; this.onsuccess = null, this.onerror = null; var o = n.apply(this, arguments); return r && (this.onsuccess = this.onsuccess ? nt(r, this.onsuccess) : r), i && (this.onerror = this.onerror ? nt(i, this.onerror) : i), void 0 !== o ? o : e } } function rt(t, n) { return t === X ? n : function () { t.apply(this, arguments); var e = this.onsuccess, r = this.onerror; this.onsuccess = this.onerror = null, n.apply(this, arguments), e && (this.onsuccess = this.onsuccess ? nt(e, this.onsuccess) : e), r && (this.onerror = this.onerror ? nt(r, this.onerror) : r) } } function it(t, n) { return t === X ? n : function (e) { var r = t.apply(this, arguments); a(e, r); var i = this.onsuccess, o = this.onerror; this.onsuccess = null, this.onerror = null; var u = n.apply(this, arguments); return i && (this.onsuccess = this.onsuccess ? nt(i, this.onsuccess) : i), o && (this.onerror = this.onerror ? nt(o, this.onerror) : o), void 0 === r ? void 0 === u ? void 0 : u : a(r, u) } } function ot(t, n) { return t === X ? n : function () { return !1 !== n.apply(this, arguments) && t.apply(this, arguments) } } function at(t, n) { return t === X ? n : function () { var e = t.apply(this, arguments); if (e && "function" == typeof e.then) { for (var r = this, i = arguments.length, o = new Array(i); i--;)o[i] = arguments[i]; return e.then((function () { return n.apply(r, o) })) } return n.apply(this, arguments) } } Y.ModifyError = W, Y.DexieError = z, Y.BulkError = $; var ut = {}, st = function () { try { return new Function("let F=async ()=>{},p=F();return [p,Object.getPrototypeOf(p),Promise.resolve(),F.constructor];")() } catch (n) { var t = o.Promise; return t ? [t.resolve(), t.prototype, t.resolve()] : [] } }(), ct = st[0], ft = st[1], ht = st[2], lt = ft && ft.then, dt = ct && ct.constructor, pt = st[3], vt = !!ht, gt = !1, yt = ht ? function () { ht.then(qt) } : o.setImmediate ? setImmediate.bind(null, qt) : o.MutationObserver ? function () { var t = document.createElement("div"); new MutationObserver((function () { qt(), t = null })).observe(t, { attributes: !0 }), t.setAttribute("i", "1") } : function () { setTimeout(qt, 0) }, mt = function (t, n) { Ot.push([t, n]), wt && (yt(), wt = !1) }, bt = !0, wt = !0, _t = [], xt = [], Et = null, kt = Z, Dt = { id: "global", global: !0, ref: 0, unhandleds: [], onunhandled: hn, pgp: !1, env: {}, finalize: function () { this.unhandleds.forEach((function (t) { try { hn(t[0], t[1]) } catch (t) { } })) } }, It = Dt, Ot = [], Rt = 0, jt = []; function Pt(t) { if ("object" != typeof this) throw new TypeError("Promises must be constructed via new"); this._listeners = [], this.onuncatched = X, this._lib = !1; var n = this._PSD = It; if (K && (this._stackHolder = M(), this._prev = null, this._numPrev = 0), "function" != typeof t) { if (t !== ut) throw new TypeError("Not a function"); return this._state = arguments[1], this._value = arguments[2], void (!1 === this._state && Ct(this, this._value)) } this._state = null, this._value = null, ++n.ref, Tt(this, t) } var St = { get: function () { var t = It, n = Jt; function e(e, r) { var i = this, o = !t.global && (t !== It || n !== Jt); o && tn(); var a = new Pt((function (n, a) { Bt(i, new At(sn(e, t, o), sn(r, t, o), n, a, t)) })); return K && Mt(a, this), a } return e.prototype = ut, e }, set: function (t) { l(this, "then", t && t.prototype === ut ? St : { get: function () { return t }, set: St.set }) } }; function At(t, n, e, r, i) { this.onFulfilled = "function" == typeof t ? t : null, this.onRejected = "function" == typeof n ? n : null, this.resolve = e, this.reject = r, this.psd = i } function Tt(t, n) { try { n((function (n) { if (null === t._state) { if (n === t) throw new TypeError("A promise cannot be resolved with itself."); var e = t._lib && Ut(); n && "function" == typeof n.then ? Tt(t, (function (t, e) { n instanceof Pt ? n._then(t, e) : n.then(t, e) })) : (t._state = !0, t._value = n, Kt(t)), e && Lt() } }), Ct.bind(null, t)) } catch (n) { Ct(t, n) } } function Ct(t, n) { if (xt.push(n), null === t._state) { var e = t._lib && Ut(); n = kt(n), t._state = !1, t._value = n, K && null !== n && "object" == typeof n && !n._promise && x((function () { var e = v(n, "stack"); n._promise = t, l(n, "stack", { get: function () { return gt ? e && (e.get ? e.get.apply(n) : e.value) : t.stack } }) })), function (t) { _t.some((function (n) { return n._value === t._value })) || _t.push(t) }(t), Kt(t), e && Lt() } } function Kt(t) { var n = t._listeners; t._listeners = []; for (var e = 0, r = n.length; e < r; ++e)Bt(t, n[e]); var i = t._PSD; --i.ref || i.finalize(), 0 === Rt && (++Rt, mt((function () { 0 == --Rt && Vt() }), [])) } function Bt(t, n) { if (null !== t._state) { var e = t._state ? n.onFulfilled : n.onRejected; if (null === e) return (t._state ? n.resolve : n.reject)(t._value); ++n.psd.ref, ++Rt, mt(Ft, [e, t, n]) } else t._listeners.push(n) } function Ft(t, n, e) { try { Et = n; var r, i = n._value; n._state ? r = t(i) : (xt.length && (xt = []), r = t(i), -1 === xt.indexOf(i) && function (t) { for (var n = _t.length; n;)if (_t[--n]._value === t._value) return void _t.splice(n, 1) }(n)), e.resolve(r) } catch (t) { e.reject(t) } finally { Et = null, 0 == --Rt && Vt(), --e.psd.ref || e.psd.finalize() } } function Nt(t, n, e) { if (n.length === e) return n; var r = ""; if (!1 === t._state) { var i, o, a = t._value; null != a ? (i = a.name || "Error", o = a.message || a, r = q(a, 0)) : (i = a, o = ""), n.push(i + (o ? ": " + o : "") + r) } return K && ((r = q(t._stackHolder, 2)) && -1 === n.indexOf(r) && n.push(r), t._prev && Nt(t._prev, n, e)), n } function Mt(t, n) { var e = n ? n._numPrev + 1 : 0; e < 100 && (t._prev = n, t._numPrev = e) } function qt() { Ut() && Lt() } function Ut() { var t = bt; return bt = !1, wt = !1, t } function Lt() { var t, n, e; do { for (; Ot.length > 0;)for (t = Ot, Ot = [], e = t.length, n = 0; n < e; ++n) { var r = t[n]; r[0].apply(null, r[1]) } } while (Ot.length > 0); bt = !0, wt = !0 } function Vt() { var t = _t; _t = [], t.forEach((function (t) { t._PSD.onunhandled.call(null, t._value, t) })); for (var n = jt.slice(0), e = n.length; e;)n[--e]() } function zt(t) { return new Pt(ut, !1, t) } function Wt(t, n) { var e = It; return function () { var r = Ut(), i = It; try { return on(e, !0), t.apply(this, arguments) } catch (t) { n && n(t) } finally { on(i, !1), r && Lt() } } } f(Pt.prototype, { then: St, _then: function (t, n) { Bt(this, new At(null, null, t, n, It)) }, catch: function (t) { if (1 === arguments.length) return this.then(null, t); var n = arguments[0], e = arguments[1]; return "function" == typeof n ? this.then(null, (function (t) { return t instanceof n ? e(t) : zt(t) })) : this.then(null, (function (t) { return t && t.name === n ? e(t) : zt(t) })) }, finally: function (t) { return this.then((function (n) { return t(), n }), (function (n) { return t(), zt(n) })) }, stack: { get: function () { if (this._stack) return this._stack; try { gt = !0; var t = Nt(this, [], 20).join("\nFrom previous: "); return null !== this._state && (this._stack = t), t } finally { gt = !1 } } }, timeout: function (t, n) { var e = this; return t < 1 / 0 ? new Pt((function (r, i) { var o = setTimeout((function () { return i(new H.Timeout(n)) }), t); e.then(r, i).finally(clearTimeout.bind(null, o)) })) : this } }), "undefined" != typeof Symbol && Symbol.toStringTag && l(Pt.prototype, Symbol.toStringTag, "Promise"), Dt.env = an(), f(Pt, { all: function () { var t = C.apply(null, arguments).map(nn); return new Pt((function (n, e) { 0 === t.length && n([]); var r = t.length; t.forEach((function (i, o) { return Pt.resolve(i).then((function (e) { t[o] = e, --r || n(t) }), e) })) })) }, resolve: function (t) { if (t instanceof Pt) return t; if (t && "function" == typeof t.then) return new Pt((function (n, e) { t.then(n, e) })); var n = new Pt(ut, !0, t); return Mt(n, Et), n }, reject: zt, race: function () { var t = C.apply(null, arguments).map(nn); return new Pt((function (n, e) { t.map((function (t) { return Pt.resolve(t).then(n, e) })) })) }, PSD: { get: function () { return It }, set: function (t) { return It = t } }, newPSD: Xt, usePSD: un, scheduler: { get: function () { return mt }, set: function (t) { mt = t } }, rejectionMapper: { get: function () { return kt }, set: function (t) { kt = t } }, follow: function (t, n) { return new Pt((function (e, r) { return Xt((function (n, e) { var r = It; r.unhandleds = [], r.onunhandled = e, r.finalize = nt((function () { var t = this; jt.push((function r() { 0 === t.unhandleds.length ? n() : e(t.unhandleds[0]), jt.splice(jt.indexOf(r), 1) })), ++Rt, mt((function () { 0 == --Rt && Vt() }), []) }), r.finalize), t() }), n, e, r) })) } }); var $t = { awaits: 0, echoes: 0, id: 0 }, Gt = 0, Qt = [], Ht = 0, Jt = 0, Yt = 0; function Xt(t, n, e, r) { var i = It, o = Object.create(i); o.parent = i, o.ref = 0, o.global = !1, o.id = ++Yt; var u = Dt.env; o.env = vt ? { Promise: Pt, PromiseProp: { value: Pt, configurable: !0, writable: !0 }, all: Pt.all, race: Pt.race, resolve: Pt.resolve, reject: Pt.reject, nthen: cn(u.nthen, o), gthen: cn(u.gthen, o) } : {}, n && a(o, n), ++i.ref, o.finalize = function () { --this.parent.ref || this.parent.finalize() }; var s = un(o, t, e, r); return 0 === o.ref && o.finalize(), s } function Zt() { return $t.id || ($t.id = ++Gt), ++$t.awaits, $t.echoes += 7, $t.id } function tn(t) { !$t.awaits || t && t !== $t.id || (0 == --$t.awaits && ($t.id = 0), $t.echoes = 7 * $t.awaits) } function nn(t) { return $t.echoes && t && t.constructor === dt ? (Zt(), t.then((function (t) { return tn(), t }), (function (t) { return tn(), ln(t) }))) : t } function en(t) { ++Jt, $t.echoes && 0 != --$t.echoes || ($t.echoes = $t.id = 0), Qt.push(It), on(t, !0) } function rn() { var t = Qt[Qt.length - 1]; Qt.pop(), on(t, !1) } function on(t, n) { var e, r = It; if ((n ? !$t.echoes || Ht++ && t === It : !Ht || --Ht && t === It) || (e = n ? en.bind(null, t) : rn, lt.call(ct, e)), t !== It && (It = t, r === Dt && (Dt.env = an()), vt)) { var i = Dt.env.Promise, a = t.env; ft.then = a.nthen, i.prototype.then = a.gthen, (r.global || t.global) && (Object.defineProperty(o, "Promise", a.PromiseProp), i.all = a.all, i.race = a.race, i.resolve = a.resolve, i.reject = a.reject) } } function an() { var t = o.Promise; return vt ? { Promise: t, PromiseProp: Object.getOwnPropertyDescriptor(o, "Promise"), all: t.all, race: t.race, resolve: t.resolve, reject: t.reject, nthen: ft.then, gthen: t.prototype.then } : {} } function un(t, n, e, r, i) { var o = It; try { return on(t, !0), n(e, r, i) } finally { on(o, !1) } } function sn(t, n, e) { return "function" != typeof t ? t : function () { var r = It; e && Zt(), on(n, !0); try { return t.apply(this, arguments) } finally { on(r, !1) } } } function cn(t, n) { return function (e, r) { return t.call(this, sn(e, n, !1), sn(r, n, !1)) } } var fn = "unhandledrejection"; function hn(t, n) { var e; try { e = n.onuncatched(t) } catch (t) { } if (!1 !== e) try { var r, i = { promise: n, reason: t }; if (o.document && document.createEvent ? ((r = document.createEvent("Event")).initEvent(fn, !0, !0), a(r, i)) : o.CustomEvent && a(r = new CustomEvent(fn, { detail: i }), i), r && o.dispatchEvent && (dispatchEvent(r), !o.PromiseRejectionEvent && o.onunhandledrejection)) try { o.onunhandledrejection(r) } catch (t) { } r.defaultPrevented || console.warn("Unhandled rejection: " + (t.stack || t)) } catch (t) { } } var ln = Pt.reject; function dn(t) { var n = {}, e = function (e, r) { if (r) { for (var i = arguments.length, o = new Array(i - 1); --i;)o[i - 1] = arguments[i]; return n[e].subscribe.apply(null, o), t } if ("string" == typeof e) return n[e] }; e.addEventType = u; for (var o = 1, a = arguments.length; o < a; ++o)u(arguments[o]); return e; function u(t, r, i) { if ("object" == typeof t) return s(t); r || (r = ot), i || (i = X); var o = { subscribers: [], fire: i, subscribe: function (t) { -1 === o.subscribers.indexOf(t) && (o.subscribers.push(t), o.fire = r(o.fire, t)) }, unsubscribe: function (t) { o.subscribers = o.subscribers.filter((function (n) { return n !== t })), o.fire = o.subscribers.reduce(r, i) } }; return n[t] = e[t] = o, o } function s(t) { r(t).forEach((function (n) { var e = t[n]; if (i(e)) u(n, t[n][0], t[n][1]); else { if ("asap" !== e) throw new H.InvalidArgument("Invalid event config"); var r = u(n, Z, (function () { for (var t = arguments.length, n = new Array(t); t--;)n[t] = arguments[t]; r.subscribers.forEach((function (t) { w((function () { t.apply(null, n) })) })) })) } })) } } var pn, vn = "{version}", gn = String.fromCharCode(65535), yn = function () { try { return IDBKeyRange.only([[]]), [[]] } catch (t) { return gn } }(), mn = -1 / 0, bn = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.", wn = "String expected.", _n = [], xn = "undefined" != typeof navigator && /(MSIE|Trident|Edge)/.test(navigator.userAgent), En = xn, kn = xn, Dn = function (t) { return !/(dexie\.js|dexie\.min\.js)/.test(t) }; function In(t, n) { var e, u, s, h, d, p = In.dependencies, v = a({ addons: In.addons, autoOpen: !0, indexedDB: p.indexedDB, IDBKeyRange: p.IDBKeyRange }, n), g = v.addons, w = v.autoOpen, I = v.indexedDB, R = v.IDBKeyRange, S = this._dbSchema = {}, A = [], B = [], F = {}, N = null, U = null, L = !1, V = null, z = !1, G = "readonly", Q = "readwrite", J = this, Y = new Pt((function (t) { e = t })), nt = new Pt((function (t, n) { u = n })), ot = !0, ut = !!Nn(I); function st(t) { this._cfg = { version: t, storesSource: null, dbschema: {}, tables: {}, contentUpgrade: null }, this.stores({}) } function ct(t, n, e, r) { var i = t.db.createObjectStore(n, e.keyPath ? { keyPath: e.keyPath, autoIncrement: e.auto } : { autoIncrement: e.auto }); return r.forEach((function (t) { ft(i, t) })), i } function ft(t, n) { t.createIndex(n.name, n.keyPath, { unique: n.unique, multiEntry: n.multi }) } function ht(t, n, e) { if (z || It.letThrough) { var r = J._createTransaction(t, n, S); try { r.create() } catch (t) { return ln(t) } return r._promise(t, (function (t, n) { return Xt((function () { return It.trans = r, e(t, n, r) })) })).then((function (t) { return r._completion.then((function () { return t })) })) } if (!L) { if (!w) return ln(new H.DatabaseClosed); J.open().catch(X) } return Y.then((function () { return ht(t, n, e) })) } function lt(t, n, e) { var r = arguments.length; if (r < 2) throw new H.InvalidArgument("Too few arguments"); for (var i = new Array(r - 1); --r;)i[r - 1] = arguments[r]; e = i.pop(); var o = O(i); return [t, o, e] } function vt(t, n, e) { this.name = t, this.schema = n, this._tx = e, this.hook = F[t] ? F[t].hook : dn(null, { creating: [et, X], reading: [tt, Z], updating: [it, X], deleting: [rt, X] }) } function gt(t, n, e) { return (e ? An : Pn)((function (e) { t.push(e), n && n() })) } function yt(t, n, e, r, i) { return new Pt((function (o, a) { var u = e.length, s = u - 1; if (0 === u) return o(); if (r) { var c, f = An(a), h = jn(null); x((function () { for (var r = 0; r < u; ++r) { c = { onsuccess: null, onerror: null }; var a = e[r]; i.call(c, a[0], a[1], n); var l = t.delete(a[0]); l._hookCtx = c, l.onerror = f, l.onsuccess = r === s ? jn(o) : h } }), (function (t) { throw c.onerror && c.onerror(t), t })) } else for (var l = 0; l < u; ++l) { var d = t.delete(e[l]); d.onerror = Pn(a), l === s && (d.onsuccess = Wt((function () { return o() }))) } })) } function mt(t, n, e, r) { var i = this; this.db = J, this.mode = t, this.storeNames = n, this.idbtrans = null, this.on = dn(this, "complete", "error", "abort"), this.parent = r || null, this.active = !0, this._reculock = 0, this._blockedFuncs = [], this._resolve = null, this._reject = null, this._waitingFor = null, this._waitingQueue = null, this._spinCount = 0, this._completion = new Pt((function (t, n) { i._resolve = t, i._reject = n })), this._completion.then((function () { i.active = !1, i.on.complete.fire() }), (function (t) { var n = i.active; return i.active = !1, i.on.error.fire(t), i.parent ? i.parent._reject(t) : n && i.idbtrans && i.idbtrans.abort(), ln(t) })) } function bt(t, n, e) { this._ctx = { table: t, index: ":id" === n ? null : n, or: e } } function wt(t, n) { var e = null, r = null; if (n) try { e = n() } catch (t) { r = t } var i = t._ctx, o = i.table; this._ctx = { table: o, index: i.index, isPrimKey: !i.index || o.schema.primKey.keyPath && i.index === o.schema.primKey.name, range: e, keysOnly: !1, dir: "next", unique: "", algorithm: null, filter: null, replayFilter: null, justLimit: !0, isMatch: null, offset: 0, limit: 1 / 0, error: r, or: i.or, valueMapper: o.hook.reading.fire } } function _t(t, n) { return !(t.filter || t.algorithm || t.or) && (n ? t.justLimit : !t.replayFilter) } function xt(t, n) { return t._cfg.version - n._cfg.version } function Et(t, n, e) { n.forEach((function (n) { var r = e[n]; t.forEach((function (t) { n in t || (t === mt.prototype || t instanceof mt ? l(t, n, { get: function () { return this.table(n) } }) : t[n] = new vt(n, r)) })) })) } function kt(t, n, e, r, i, o) { var a = Wt(o ? function (t, n, r) { return e(o(t), n, r) } : e, i); t.onerror || (t.onerror = Pn(i)), t.onsuccess = function (t, n) { return function () { try { t.apply(this, arguments) } catch (t) { n(t) } } }(n ? function () { var e = t.result; if (e) { var o = function () { e.continue() }; n(e, (function (t) { o = t }), r, i) && a(e.value, e, (function (t) { o = t })), o() } else r() } : function () { var n = t.result; if (n) { var e = function () { n.continue() }; a(n.value, n, (function (t) { e = t })), e() } else r() }, i) } function Dt(t, n) { return I.cmp(t, n) } function Ot(t, n) { return Dt(t, n) > 0 ? t : n } function Rt(t, n) { return I.cmp(t, n) } function jt(t, n) { return I.cmp(n, t) } function St(t, n) { return t < n ? -1 : t === n ? 0 : 1 } function At(t, n) { return t > n ? -1 : t === n ? 0 : 1 } function Tt(t, n) { return t ? n ? function () { return t.apply(this, arguments) && n.apply(this, arguments) } : t : n } function Ct(t, n) { for (var e = n.db.objectStoreNames, r = 0; r < e.length; ++r) { var i = e[r], a = n.objectStore(i); s = "getAll" in a; for (var u = 0; u < a.indexNames.length; ++u) { var c = a.indexNames[u], f = a.index(c).keyPath, h = "string" == typeof f ? f : "[" + y(f).join("+") + "]"; if (t[i]) { var l = t[i].idxByName[h]; l && (l.name = c) } } } /Safari/.test(navigator.userAgent) && !/(Chrome\/|Edge\/)/.test(navigator.userAgent) && o.WorkerGlobalScope && o instanceof o.WorkerGlobalScope && [].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1] < 604 && (s = !1) } function Kt(t) { J.on("blocked").fire(t), _n.filter((function (t) { return t.name === J.name && t !== J && !t._vcFired })).map((function (n) { return n.on("versionchange").fire(t) })) } this.version = function (t) { if (N || L) throw new H.Schema("Cannot add version when database is open"); this.verno = Math.max(this.verno, t); var n = A.filter((function (n) { return n._cfg.version === t }))[0]; return n || (n = new st(t), A.push(n), A.sort(xt), ot = !1, n) }, a(st.prototype, { stores: function (t) { this._cfg.storesSource = this._cfg.storesSource ? a(this._cfg.storesSource, t) : t; var n = {}; A.forEach((function (t) { a(n, t._cfg.storesSource) })); var e = this._cfg.dbschema = {}; return this._parseStoresSpec(n, e), S = J._dbSchema = e, [F, J, mt.prototype].forEach((function (t) { for (var n in t) t[n] instanceof vt && delete t[n] })), Et([F, J, mt.prototype, this._cfg.tables], r(e), e), B = r(e), this }, upgrade: function (t) { return this._cfg.contentUpgrade = t, this }, _parseStoresSpec: function (t, n) { r(t).forEach((function (e) { if (null !== t[e]) { var r = {}, o = function (t) { var n = []; return t.split(",").forEach((function (t) { var e = (t = t.trim()).replace(/([&*]|\+\+)/g, ""), r = /^\[/.test(e) ? e.match(/^\[(.*)\]$/)[1].split("+") : e; n.push(new Kn(e, r || null, /\&/.test(t), /\*/.test(t), /\+\+/.test(t), i(r), /\./.test(t))) })), n }(t[e]), a = o.shift(); if (a.multi) throw new H.Schema("Primary key cannot be multi-valued"); a.keyPath && k(r, a.keyPath, a.auto ? 0 : a.keyPath), o.forEach((function (t) { if (t.auto) throw new H.Schema("Only primary key can be marked as autoIncrement (++)"); if (!t.keyPath) throw new H.Schema("Index must have a name and cannot be an empty string"); k(r, t.keyPath, t.compound ? t.keyPath.map((function () { return "" })) : "") })), n[e] = new Bn(e, a, o, r) } })) } }), this._allTables = F, this._createTransaction = function (t, n, e, r) { return new mt(t, n, e, r) }, this._whenReady = function (t) { return z || It.letThrough ? t() : new Pt((function (t, n) { if (!L) { if (!w) return void n(new H.DatabaseClosed); J.open().catch(X) } Y.then(t, n) })).then(t) }, this.verno = 0, this.open = function () { if (L || N) return Y.then((function () { return U ? ln(U) : J })); K && (nt._stackHolder = M()), L = !0, U = null, z = !1; var n = e, i = null; return Pt.race([nt, new Pt((function (n, e) { if (!I) throw new H.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using old Safari versions, make sure to include indexedDB polyfill."); var o = ot ? I.open(t) : I.open(t, Math.round(10 * J.verno)); if (!o) throw new H.MissingAPI("IndexedDB API not available"); o.onerror = Pn(e), o.onblocked = Wt(Kt), o.onupgradeneeded = Wt((function (n) { if (i = o.transaction, ot && !J._allowEmptyDB) { o.onerror = Tn, i.abort(), o.result.close(); var a = I.deleteDatabase(t); a.onsuccess = a.onerror = Wt((function () { e(new H.NoSuchDatabase("Database " + t + " doesnt exist")) })) } else i.onerror = Pn(e), function (t, n, e) { var i = J._createTransaction(Q, B, S); i.create(n), i._completion.catch(e); var o = i._reject.bind(i); Xt((function () { It.trans = i, 0 === t ? (r(S).forEach((function (t) { ct(n, t, S[t].primKey, S[t].indexes) })), Pt.follow((function () { return J.on.populate.fire(i) })).catch(o)) : function (t, n, e) { var i = [], o = A.filter((function (n) { return n._cfg.version === t }))[0]; if (!o) throw new H.Upgrade("Dexie specification of currently installed DB version is missing"); S = J._dbSchema = o._cfg.dbschema; var a = !1; return A.filter((function (n) { return n._cfg.version > t })).forEach((function (t) { i.push((function () { var r = S, i = t._cfg.dbschema; Ct(r, e), Ct(i, e), S = J._dbSchema = i; var o = function (t, n) { var e = { del: [], add: [], change: [] }; for (var r in t) n[r] || e.del.push(r); for (r in n) { var i = t[r], o = n[r]; if (i) { var a = { name: r, def: o, recreate: !1, del: [], add: [], change: [] }; if (i.primKey.src !== o.primKey.src) a.recreate = !0, e.change.push(a); else { var u = i.idxByName, s = o.idxByName; for (var c in u) s[c] || a.del.push(c); for (c in s) { var f = u[c], h = s[c]; f ? f.src !== h.src && a.change.push(h) : a.add.push(h) } (a.del.length > 0 || a.add.length > 0 || a.change.length > 0) && e.change.push(a) } } else e.add.push([r, o]) } return e }(r, i); if (o.add.forEach((function (t) { ct(e, t[0], t[1].primKey, t[1].indexes) })), o.change.forEach((function (t) { if (t.recreate) throw new H.Upgrade("Not yet support for changing primary key"); var n = e.objectStore(t.name); t.add.forEach((function (t) { ft(n, t) })), t.change.forEach((function (t) { n.deleteIndex(t.name), ft(n, t) })), t.del.forEach((function (t) { n.deleteIndex(t) })) })), t._cfg.contentUpgrade) return a = !0, Pt.follow((function () { t._cfg.contentUpgrade(n) })) })), i.push((function (n) { a && En || function (t, n) { for (var e = 0; e < n.db.objectStoreNames.length; ++e) { var r = n.db.objectStoreNames[e]; null == t[r] && n.db.deleteObjectStore(r) } }(t._cfg.dbschema, n) })) })), function t() { return i.length ? Pt.resolve(i.shift()(n.idbtrans)).then(t) : Pt.resolve() }().then((function () { !function (t, n) { r(t).forEach((function (e) { n.db.objectStoreNames.contains(e) || ct(n, e, t[e].primKey, t[e].indexes) })) }(S, e) })) }(t, i, n).catch(o) })) }((n.oldVersion > Math.pow(2, 62) ? 0 : n.oldVersion) / 10, i, e) }), e), o.onsuccess = Wt((function () { if (i = null, N = o.result, _n.push(J), ot) !function () { if (J.verno = N.version / 10, J._dbSchema = S = {}, 0 !== (B = y(N.objectStoreNames, 0)).length) { var t = N.transaction(Fn(B), "readonly"); B.forEach((function (n) { for (var e = t.objectStore(n), r = e.keyPath, i = r && "string" == typeof r && -1 !== r.indexOf("."), o = new Kn(r, r || "", !1, !1, !!e.autoIncrement, r && "string" != typeof r, i), a = [], u = 0; u < e.indexNames.length; ++u) { var s = e.index(e.indexNames[u]); i = (r = s.keyPath) && "string" == typeof r && -1 !== r.indexOf("."); var c = new Kn(s.name, r, !!s.unique, !!s.multiEntry, !1, r && "string" != typeof r, i); a.push(c) } S[n] = new Bn(n, o, a, {}) })), Et([F], r(S), S) } }(); else if (N.objectStoreNames.length > 0) try { Ct(S, N.transaction(Fn(N.objectStoreNames), G)) } catch (t) { } N.onversionchange = Wt((function (t) { J._vcFired = !0, J.on("versionchange").fire(t) })), ut || "__dbnames" === t || pn.dbnames.put({ name: t }).catch(X), n() }), e) }))]).then((function () { return V = [], Pt.resolve(In.vip(J.on.ready.fire)).then((function t() { if (V.length > 0) { var n = V.reduce(at, X); return V = [], Pt.resolve(In.vip(n)).then(t) } })) })).finally((function () { V = null })).then((function () { return L = !1, J })).catch((function (t) { try { i && i.abort() } catch (t) { } return L = !1, J.close(), ln(U = t) })).finally((function () { z = !0, n() })) }, this.close = function () { var t = _n.indexOf(J); if (t >= 0 && _n.splice(t, 1), N) { try { N.close() } catch (t) { } N = null } w = !1, U = new H.DatabaseClosed, L && u(U), Y = new Pt((function (t) { e = t })), nt = new Pt((function (t, n) { u = n })) }, this.delete = function () { var n = arguments.length > 0; return new Pt((function (e, r) { if (n) throw new H.InvalidArgument("Arguments not allowed in db.delete()"); function i() { J.close(); var n = I.deleteDatabase(t); n.onsuccess = Wt((function () { ut || pn.dbnames.delete(t).catch(X), e() })), n.onerror = Pn(r), n.onblocked = Kt } L ? Y.then(i) : i() })) }, this.backendDB = function () { return N }, this.isOpen = function () { return null !== N }, this.hasBeenClosed = function () { return U && U instanceof H.DatabaseClosed }, this.hasFailed = function () { return null !== U }, this.dynamicallyOpened = function () { return ot }, this.name = t, f(this, { tables: { get: function () { return r(F).map((function (t) { return F[t] })) } } }), this.on = dn(this, "populate", "blocked", "versionchange", { ready: [at, X] }), this.on.ready.subscribe = m(this.on.ready.subscribe, (function (t) { return function (n, e) { In.vip((function () { z ? (U || Pt.resolve().then(n), e && t(n)) : V ? (V.push(n), e && t(n)) : (t(n), e || t((function t() { J.on.ready.unsubscribe(n), J.on.ready.unsubscribe(t) }))) })) } })), this.transaction = function () { var t = lt.apply(this, arguments); return this._transaction.apply(this, t) }, this._transaction = function (t, n, e) { var r = It.trans; r && r.db === J && -1 === t.indexOf("!") || (r = null); var i = -1 !== t.indexOf("?"); t = t.replace("!", "").replace("?", ""); try { var o = n.map((function (t) { var n = t instanceof vt ? t.name : t; if ("string" != typeof n) throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed"); return n })); if ("r" == t || t == G) t = G; else { if ("rw" != t && t != Q) throw new H.InvalidArgument("Invalid transaction mode: " + t); t = Q } if (r) { if (r.mode === G && t === Q) { if (!i) throw new H.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY"); r = null } r && o.forEach((function (t) { if (r && -1 === r.storeNames.indexOf(t)) { if (!i) throw new H.SubTransaction("Table " + t + " not included in parent transaction."); r = null } })), i && r && !r.active && (r = null) } } catch (t) { return r ? r._promise(null, (function (n, e) { e(t) })) : ln(t) } return r ? r._promise(t, a, "lock") : It.trans ? un(It.transless, (function () { return J._whenReady(a) })) : J._whenReady(a); function a() { return Pt.resolve().then((function () { var n, i = It.transless || It, a = J._createTransaction(t, o, S, r), u = { trans: a, transless: i }; r ? a.idbtrans = r.idbtrans : a.create(), e.constructor === pt && Zt(); var s = Pt.follow((function () { if (n = e.call(a, a)) if (n.constructor === dt) { var t = tn.bind(null, null); n.then(t, t) } else "function" == typeof n.next && "function" == typeof n.throw && (n = Cn(n)) }), u); return (n && "function" == typeof n.then ? Pt.resolve(n).then((function (t) { return a.active ? t : ln(new H.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn")) })) : s.then((function () { return n }))).then((function (t) { return r && a._resolve(), a._completion.then((function () { return t })) })).catch((function (t) { return a._reject(t), ln(t) })) })) } }, this.table = function (t) { if (!c(F, t)) throw new H.InvalidTable("Table " + t + " does not exist"); return F[t] }, f(vt.prototype, { _trans: function (t, n, e) { var r = this._tx || It.trans; return r && r.db === J ? r === It.trans ? r._promise(t, n, e) : Xt((function () { return r._promise(t, n, e) }), { trans: r, transless: It.transless || It }) : ht(t, [this.name], n) }, _idbstore: function (t, n, e) { var r = this.name; return this._trans(t, (function (t, e, i) { if (-1 === i.storeNames.indexOf(r)) throw new H.NotFound("Table" + r + " not part of transaction"); return n(t, e, i.idbtrans.objectStore(r), i) }), e) }, get: function (t, n) { if (t && t.constructor === Object) return this.where(t).first(n); var e = this; return this._idbstore(G, (function (n, r, i) { var o = i.get(t); o.onerror = Pn(r), o.onsuccess = Wt((function () { n(e.hook.reading.fire(o.result)) }), r) })).then(n) }, where: function (t) { if ("string" == typeof t) return new bt(this, t); if (i(t)) return new bt(this, "[" + t.join("+") + "]"); var n = r(t); if (1 === n.length) return this.where(n[0]).equals(t[n[0]]); var e = this.schema.indexes.concat(this.schema.primKey).filter((function (t) { return t.compound && n.every((function (n) { return t.keyPath.indexOf(n) >= 0 })) && t.keyPath.every((function (t) { return n.indexOf(t) >= 0 })) }))[0]; if (e && yn !== gn) return this.where(e.name).equals(e.keyPath.map((function (n) { return t[n] }))); e || console.warn("The query " + JSON.stringify(t) + " on " + this.name + " would benefit of a compound index [" + n.join("+") + "]"); var o = this.schema.idxByName, a = n.reduce((function (n, e) { return [n[0] || o[e], n[0] || !o[e] ? Tt(n[1], (function (n) { return "" + E(n, e) == "" + t[e] })) : n[1]] }), [null, null]), u = a[0]; return u ? this.where(u.name).equals(t[u.keyPath]).filter(a[1]) : e ? this.filter(a[1]) : this.where(n).equals("") }, count: function (t) { return this.toCollection().count(t) }, offset: function (t) { return this.toCollection().offset(t) }, limit: function (t) { return this.toCollection().limit(t) }, reverse: function () { return this.toCollection().reverse() }, filter: function (t) { return this.toCollection().and(t) }, each: function (t) { return this.toCollection().each(t) }, toArray: function (t) { return this.toCollection().toArray(t) }, orderBy: function (t) { return new wt(new bt(this, i(t) ? "[" + t.join("+") + "]" : t)) }, toCollection: function () { return new wt(new bt(this)) }, mapToClass: function (t, n) { this.schema.mappedClass = t; var e = Object.create(t.prototype); n && Rn(e, n), this.schema.instanceTemplate = e; var r = function (n) { if (!n) return n; var e = Object.create(t.prototype); for (var r in n) if (c(n, r)) try { e[r] = n[r] } catch (t) { } return e }; return this.schema.readHook && this.hook.reading.unsubscribe(this.schema.readHook), this.schema.readHook = r, this.hook("reading", r), t }, defineClass: function (t) { return this.mapToClass(In.defineClass(t), t) }, bulkDelete: function (t) { return this.hook.deleting.fire === X ? this._idbstore(Q, (function (n, e, r, i) { n(yt(r, i, t, !1, X)) })) : this.where(":id").anyOf(t).delete().then((function () { })) }, bulkPut: function (t, n) { var e = this; return this._idbstore(Q, (function (r, i, o) { if (!o.keyPath && !e.schema.primKey.auto && !n) throw new H.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument"); if (o.keyPath && n) throw new H.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys"); if (n && n.length !== t.length) throw new H.InvalidArgument("Arguments objects and keys must have the same length"); if (0 === t.length) return r(); var a, u, s = function (t) { 0 === c.length ? r(t) : i(new $(e.name + ".bulkPut(): " + c.length + " of " + f + " operations failed", c)) }, c = [], f = t.length, h = e; if (e.hook.creating.fire === X && e.hook.updating.fire === X) { u = gt(c); for (var l = 0, d = t.length; l < d; ++l)(a = n ? o.put(t[l], n[l]) : o.put(t[l])).onerror = u; a.onerror = gt(c, s), a.onsuccess = Sn(s) } else { var p = n || o.keyPath && t.map((function (t) { return E(t, o.keyPath) })), v = p && _(p, (function (n, e) { return null != n && [n, t[e]] })), g = p ? h.where(":id").anyOf(p.filter((function (t) { return null != t }))).modify((function () { this.value = v[this.primKey], v[this.primKey] = null })).catch(W, (function (t) { c = t.failures })).then((function () { for (var e = [], r = n && [], i = p.length - 1; i >= 0; --i) { var o = p[i]; (null == o || v[o]) && (e.push(t[i]), n && r.push(o), null != o && (v[o] = null)) } return e.reverse(), n && r.reverse(), h.bulkAdd(e, r) })).then((function (t) { var n = p[p.length - 1]; return null != n ? n : t })) : h.bulkAdd(t); g.then(s).catch($, (function (t) { c = c.concat(t.failures), s() })).catch(i) } }), "locked") }, bulkAdd: function (t, n) { var e = this, r = this.hook.creating.fire; return this._idbstore(Q, (function (i, o, a, u) { if (!a.keyPath && !e.schema.primKey.auto && !n) throw new H.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument"); if (a.keyPath && n) throw new H.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys"); if (n && n.length !== t.length) throw new H.InvalidArgument("Arguments objects and keys must have the same length"); if (0 === t.length) return i(); function s(t) { 0 === l.length ? i(t) : o(new $(e.name + ".bulkAdd(): " + l.length + " of " + d + " operations failed", l)) } var c, f, h, l = [], d = t.length; if (r !== X) { var p, v = a.keyPath; f = gt(l, null, !0), h = jn(null), x((function () { for (var e = 0, i = t.length; e < i; ++e) { p = { onerror: null, onsuccess: null }; var o = n && n[e], s = t[e], l = n ? o : v ? E(s, v) : void 0, d = r.call(p, l, s, u); null == l && null != d && (v ? k(s = j(s), v, d) : o = d), (c = null != o ? a.add(s, o) : a.add(s))._hookCtx = p, e < i - 1 && (c.onerror = f, p.onsuccess && (c.onsuccess = h)) } }), (function (t) { throw p.onerror && p.onerror(t), t })), c.onerror = gt(l, s, !0), c.onsuccess = jn(s) } else { f = gt(l); for (var g = 0, y = t.length; g < y; ++g)(c = n ? a.add(t[g], n[g]) : a.add(t[g])).onerror = f; c.onerror = gt(l, s), c.onsuccess = Sn(s) } })) }, add: function (t, n) { var e = this.hook.creating.fire; return this._idbstore(Q, (function (r, i, o, a) { var u = { onsuccess: null, onerror: null }; if (e !== X) { var s = null != n ? n : o.keyPath ? E(t, o.keyPath) : void 0, c = e.call(u, s, t, a); null == s && null != c && (o.keyPath ? k(t, o.keyPath, c) : n = c) } try { var f = null != n ? o.add(t, n) : o.add(t); f._hookCtx = u, f.onerror = An(i), f.onsuccess = jn((function (n) { var e = o.keyPath; e && k(t, e, n), r(n) })) } catch (t) { throw u.onerror && u.onerror(t), t } })) }, put: function (t, n) { var e = this, r = this.hook.creating.fire, i = this.hook.updating.fire; if (r !== X || i !== X) { var o = this.schema.primKey.keyPath, a = void 0 !== n ? n : o && E(t, o); return null == a ? this.add(t) : (t = j(t), this._trans(Q, (function () { return e.where(":id").equals(a).modify((function () { this.value = t })).then((function (r) { return 0 === r ? e.add(t, n) : a })) }), "locked")) } return this._idbstore(Q, (function (e, r, i) { var o = void 0 !== n ? i.put(t, n) : i.put(t); o.onerror = Pn(r), o.onsuccess = Wt((function (n) { var r = i.keyPath; r && k(t, r, n.target.result), e(o.result) })) })) }, delete: function (t) { return this.hook.deleting.subscribers.length ? this.where(":id").equals(t).delete() : this._idbstore(Q, (function (n, e, r) { var i = r.delete(t); i.onerror = Pn(e), i.onsuccess = Wt((function () { n(i.result) })) })) }, clear: function () { return this.hook.deleting.subscribers.length ? this.toCollection().delete() : this._idbstore(Q, (function (t, n, e) { var r = e.clear(); r.onerror = Pn(n), r.onsuccess = Wt((function () { t(r.result) })) })) }, update: function (t, n) { if ("object" != typeof n || i(n)) throw new H.InvalidArgument("Modifications must be an object."); if ("object" != typeof t || i(t)) return this.where(":id").equals(t).modify(n); r(n).forEach((function (e) { k(t, e, n[e]) })); var e = E(t, this.schema.primKey.keyPath); return void 0 === e ? ln(new H.InvalidArgument("Given object does not contain its primary key")) : this.where(":id").equals(e).modify(n) } }), f(mt.prototype, { _lock: function () { return b(!It.global), ++this._reculock, 1 !== this._reculock || It.global || (It.lockOwnerFor = this), this }, _unlock: function () { if (b(!It.global), 0 == --this._reculock) for (It.global || (It.lockOwnerFor = null); this._blockedFuncs.length > 0 && !this._locked();) { var t = this._blockedFuncs.shift(); try { un(t[1], t[0]) } catch (t) { } } return this }, _locked: function () { return this._reculock && It.lockOwnerFor !== this }, create: function (t) { var n = this; if (!this.mode) return this; if (b(!this.idbtrans), !t && !N) switch (U && U.name) { case "DatabaseClosedError": throw new H.DatabaseClosed(U); case "MissingAPIError": throw new H.MissingAPI(U.message, U); default: throw new H.OpenFailed(U) }if (!this.active) throw new H.TransactionInactive; return b(null === this._completion._state), (t = this.idbtrans = t || N.transaction(Fn(this.storeNames), this.mode)).onerror = Wt((function (e) { Tn(e), n._reject(t.error) })), t.onabort = Wt((function (e) { Tn(e), n.active && n._reject(new H.Abort(t.error)), n.active = !1, n.on("abort").fire(e) })), t.oncomplete = Wt((function () { n.active = !1, n._resolve() })), this }, _promise: function (t, n, e) { var r = this; if (t === Q && this.mode !== Q) return ln(new H.ReadOnly("Transaction is readonly")); if (!this.active) return ln(new H.TransactionInactive); if (this._locked()) return new Pt((function (i, o) { r._blockedFuncs.push([function () { r._promise(t, n, e).then(i, o) }, It]) })); if (e) return Xt((function () { var t = new Pt((function (t, e) { r._lock(); var i = n(t, e, r); i && i.then && i.then(t, e) })); return t.finally((function () { return r._unlock() })), t._lib = !0, t })); var i = new Pt((function (t, e) { var i = n(t, e, r); i && i.then && i.then(t, e) })); return i._lib = !0, i }, _root: function () { return this.parent ? this.parent._root() : this }, waitFor: function (t) { var n = this._root(); if (t = Pt.resolve(t), n._waitingFor) n._waitingFor = n._waitingFor.then((function () { return t })); else { n._waitingFor = t, n._waitingQueue = []; var e = n.idbtrans.objectStore(n.storeNames[0]); !function t() { for (++n._spinCount; n._waitingQueue.length;)n._waitingQueue.shift()(); n._waitingFor && (e.get(-1 / 0).onsuccess = t) }() } var r = n._waitingFor; return new Pt((function (e, i) { t.then((function (t) { return n._waitingQueue.push(Wt(e.bind(null, t))) }), (function (t) { return n._waitingQueue.push(Wt(i.bind(null, t))) })).finally((function () { n._waitingFor === r && (n._waitingFor = null) })) })) }, abort: function () { this.active && this._reject(new H.Abort), this.active = !1 }, tables: { get: (h = "Transaction.tables", d = function () { return F }, function () { return console.warn(h + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + q(M(), 1)), d.apply(this, arguments) }) }, table: function (t) { return new vt(t, J.table(t).schema, this) } }), f(bt.prototype, (function () { function t(t, n, e) { var r = t instanceof bt ? new wt(t) : t; return r._ctx.error = e ? new e(n) : new TypeError(n), r } function n(t) { return new wt(t, (function () { return R.only("") })).limit(0) } function e(t, n, e, r, i, o) { for (var a = Math.min(t.length, r.length), u = -1, s = 0; s < a; ++s) { var c = n[s]; if (c !== r[s]) return i(t[s], e[s]) < 0 ? t.substr(0, s) + e[s] + e.substr(s + 1) : i(t[s], r[s]) < 0 ? t.substr(0, s) + r[s] + e.substr(s + 1) : u >= 0 ? t.substr(0, u) + n[u] + e.substr(u + 1) : null; i(t[s], c) < 0 && (u = s) } return a < r.length && "next" === o ? t + e.substr(t.length) : a < t.length && "prev" === o ? t.substr(0, e.length) : u < 0 ? null : t.substr(0, u) + r[u] + e.substr(u + 1) } function r(n, r, i, o) { var a, u, s, c, f, h, l, d = i.length; if (!i.every((function (t) { return "string" == typeof t }))) return t(n, wn); function p(t) { a = function (t) { return "next" === t ? function (t) { return t.toUpperCase() } : function (t) { return t.toLowerCase() } }(t), u = function (t) { return "next" === t ? function (t) { return t.toLowerCase() } : function (t) { return t.toUpperCase() } }(t), s = "next" === t ? St : At; var n = i.map((function (t) { return { lower: u(t), upper: a(t) } })).sort((function (t, n) { return s(t.lower, n.lower) })); c = n.map((function (t) { return t.upper })), f = n.map((function (t) { return t.lower })), h = t, l = "next" === t ? "" : o } p("next"); var v = new wt(n, (function () { return R.bound(c[0], f[d - 1] + o) })); v._ondirectionchange = function (t) { p(t) }; var g = 0; return v._addAlgorithm((function (t, n, i) { var o = t.key; if ("string" != typeof o) return !1; var a = u(o); if (r(a, f, g)) return !0; for (var p = null, v = g; v < d; ++v) { var y = e(o, a, c[v], f[v], s, h); null === y && null === p ? g = v + 1 : (null === p || s(p, y) > 0) && (p = y) } return n(null !== p ? function () { t.continue(p + l) } : i), !1 })), v } return { between: function (e, r, i, o) { i = !1 !== i, o = !0 === o; try { return Dt(e, r) > 0 || 0 === Dt(e, r) && (i || o) && (!i || !o) ? n(this) : new wt(this, (function () { return R.bound(e, r, !i, !o) })) } catch (n) { return t(this, bn) } }, equals: function (t) { return new wt(this, (function () { return R.only(t) })) }, above: function (t) { return new wt(this, (function () { return R.lowerBound(t, !0) })) }, aboveOrEqual: function (t) { return new wt(this, (function () { return R.lowerBound(t) })) }, below: function (t) { return new wt(this, (function () { return R.upperBound(t, !0) })) }, belowOrEqual: function (t) { return new wt(this, (function () { return R.upperBound(t) })) }, startsWith: function (n) { return "string" != typeof n ? t(this, wn) : this.between(n, n + gn, !0, !0) }, startsWithIgnoreCase: function (t) { return "" === t ? this.startsWith(t) : r(this, (function (t, n) { return 0 === t.indexOf(n[0]) }), [t], gn) }, equalsIgnoreCase: function (t) { return r(this, (function (t, n) { return t === n[0] }), [t], "") }, anyOfIgnoreCase: function () { var t = C.apply(T, arguments); return 0 === t.length ? n(this) : r(this, (function (t, n) { return -1 !== n.indexOf(t) }), t, "") }, startsWithAnyOfIgnoreCase: function () { var t = C.apply(T, arguments); return 0 === t.length ? n(this) : r(this, (function (t, n) { return n.some((function (n) { return 0 === t.indexOf(n) })) }), t, gn) }, anyOf: function () { var e = C.apply(T, arguments), r = Rt; try { e.sort(r) } catch (n) { return t(this, bn) } if (0 === e.length) return n(this); var i = new wt(this, (function () { return R.bound(e[0], e[e.length - 1]) })); i._ondirectionchange = function (t) { r = "next" === t ? Rt : jt, e.sort(r) }; var o = 0; return i._addAlgorithm((function (t, n, i) { for (var a = t.key; r(a, e[o]) > 0;)if (++o === e.length) return n(i), !1; return 0 === r(a, e[o]) || (n((function () { t.continue(e[o]) })), !1) })), i }, notEqual: function (t) { return this.inAnyRange([[mn, t], [t, yn]], { includeLowers: !1, includeUppers: !1 }) }, noneOf: function () { var n = C.apply(T, arguments); if (0 === n.length) return new wt(this); try { n.sort(Rt) } catch (n) { return t(this, bn) } var e = n.reduce((function (t, n) { return t ? t.concat([[t[t.length - 1][1], n]]) : [[mn, n]] }), null); return e.push([n[n.length - 1], yn]), this.inAnyRange(e, { includeLowers: !1, includeUppers: !1 }) }, inAnyRange: function (e, r) { if (0 === e.length) return n(this); if (!e.every((function (t) { return void 0 !== t[0] && void 0 !== t[1] && Rt(t[0], t[1]) <= 0 }))) return t(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", H.InvalidArgument); var i, o = !r || !1 !== r.includeLowers, a = r && !0 === r.includeUppers, u = Rt; function s(t, n) { return u(t[0], n[0]) } try { i = e.reduce((function (t, n) { for (var e = 0, r = t.length; e < r; ++e) { var i = t[e]; if (Dt(n[0], i[1]) < 0 && Dt(n[1], i[0]) > 0) { i[0] = Dt(o = i[0], a = n[0]) < 0 ? o : a, i[1] = Ot(i[1], n[1]); break } } var o, a; return e === r && t.push(n), t }), []), i.sort(s) } catch (n) { return t(this, bn) } var c = 0, f = a ? function (t) { return Rt(t, i[c][1]) > 0 } : function (t) { return Rt(t, i[c][1]) >= 0 }, h = o ? function (t) { return jt(t, i[c][0]) > 0 } : function (t) { return jt(t, i[c][0]) >= 0 }, l = f, d = new wt(this, (function () { return R.bound(i[0][0], i[i.length - 1][1], !o, !a) })); return d._ondirectionchange = function (t) { "next" === t ? (l = f, u = Rt) : (l = h, u = jt), i.sort(s) }, d._addAlgorithm((function (t, n, e) { for (var r = t.key; l(r);)if (++c === i.length) return n(e), !1; return !!function (t) { return !f(t) && !h(t) }(r) || (0 === Dt(r, i[c][1]) || 0 === Dt(r, i[c][0]) || n((function () { u === Rt ? t.continue(i[c][0]) : t.continue(i[c][1]) })), !1) })), d }, startsWithAnyOf: function () { var e = C.apply(T, arguments); return e.every((function (t) { return "string" == typeof t })) ? 0 === e.length ? n(this) : this.inAnyRange(e.map((function (t) { return [t, t + gn] }))) : t(this, "startsWithAnyOf() only works with strings") } } })), f(wt.prototype, (function () { function t(t, n) { t.filter = Tt(t.filter, n) } function n(t, n, e) { var r = t.replayFilter; t.replayFilter = r ? function () { return Tt(r(), n()) } : n, t.justLimit = e && !r } function e(t, n) { if (t.isPrimKey) return n; var e = t.table.schema.idxByName[t.index]; if (!e) throw new H.Schema("KeyPath " + t.index + " on object store " + n.name + " is not indexed"); return n.index(e.name) } function i(t, n) { var r = e(t, n); return t.keysOnly && "openKeyCursor" in r ? r.openKeyCursor(t.range || null, t.dir + t.unique) : r.openCursor(t.range || null, t.dir + t.unique) } function o(t, n, e, r, o) { var a = t.replayFilter ? Tt(t.filter, t.replayFilter()) : t.filter; t.or ? function () { var u = {}, s = 0; function f() { 2 == ++s && e() } function h(t, e, i) { if (!a || a(e, i, f, r)) { var o = e.primaryKey, s = "" + o; "[object ArrayBuffer]" === s && (s = "" + new Uint8Array(o)), c(u, s) || (u[s] = !0, n(t, e, i)) } } t.or._iterate(h, f, r, o), kt(i(t, o), t.algorithm, h, f, r, !t.keysOnly && t.valueMapper) }() : kt(i(t, o), Tt(t.algorithm, a), n, e, r, !t.keysOnly && t.valueMapper) } return { _read: function (t, n) { var e = this._ctx; return e.error ? e.table._trans(null, ln.bind(null, e.error)) : e.table._idbstore(G, t).then(n) }, _write: function (t) { var n = this._ctx; return n.error ? n.table._trans(null, ln.bind(null, n.error)) : n.table._idbstore(Q, t, "locked") }, _addAlgorithm: function (t) { var n = this._ctx; n.algorithm = Tt(n.algorithm, t) }, _iterate: function (t, n, e, r) { return o(this._ctx, t, n, e, r) }, clone: function (t) { var n = Object.create(this.constructor.prototype), e = Object.create(this._ctx); return t && a(e, t), n._ctx = e, n }, raw: function () { return this._ctx.valueMapper = null, this }, each: function (t) { var n = this._ctx; return this._read((function (e, r, i) { o(n, t, e, r, i) })) }, count: function (t) { var n = this._ctx; if (_t(n, !0)) return this._read((function (t, r, i) { var o = e(n, i), a = n.range ? o.count(n.range) : o.count(); a.onerror = Pn(r), a.onsuccess = function (e) { t(Math.min(e.target.result, n.limit)) } }), t); var r = 0; return this._read((function (t, e, i) { o(n, (function () { return ++r, !1 }), (function () { t(r) }), e, i) }), t) }, sortBy: function (t, n) { var e = t.split(".").reverse(), r = e[0], i = e.length - 1; function o(t, n) { return n ? o(t[e[n]], n - 1) : t[r] } var a = "next" === this._ctx.dir ? 1 : -1; function u(t, n) { var e = o(t, i), r = o(n, i); return e < r ? -a : e > r ? a : 0 } return this.toArray((function (t) { return t.sort(u) })).then(n) }, toArray: function (t) { var n = this._ctx; return this._read((function (t, r, i) { if (s && "next" === n.dir && _t(n, !0) && n.limit > 0) { var a = n.table.hook.reading.fire, u = e(n, i), c = n.limit < 1 / 0 ? u.getAll(n.range, n.limit) : u.getAll(n.range); c.onerror = Pn(r), c.onsuccess = Sn(a === Z ? t : function (n) { try { t(n.map(a)) } catch (t) { r(t) } }) } else { var f = []; o(n, (function (t) { f.push(t) }), (function () { t(f) }), r, i) } }), t) }, offset: function (t) { var e = this._ctx; return t <= 0 || (e.offset += t, _t(e) ? n(e, (function () { var n = t; return function (t, e) { return 0 === n || (1 === n ? (--n, !1) : (e((function () { t.advance(n), n = 0 })), !1)) } })) : n(e, (function () { var n = t; return function () { return --n < 0 } }))), this }, limit: function (t) { return this._ctx.limit = Math.min(this._ctx.limit, t), n(this._ctx, (function () { var n = t; return function (t, e, r) { return --n <= 0 && e(r), n >= 0 } }), !0), this }, until: function (n, e) { return t(this._ctx, (function (t, r, i) { return !n(t.value) || (r(i), e) })), this }, first: function (t) { return this.limit(1).toArray((function (t) { return t[0] })).then(t) }, last: function (t) { return this.reverse().first(t) }, filter: function (n) { return t(this._ctx, (function (t) { return n(t.value) })), function (t, n) { t.isMatch = Tt(t.isMatch, n) }(this._ctx, n), this }, and: function (t) { return this.filter(t) }, or: function (t) { return new bt(this._ctx.table, t, this) }, reverse: function () { return this._ctx.dir = "prev" === this._ctx.dir ? "next" : "prev", this._ondirectionchange && this._ondirectionchange(this._ctx.dir), this }, desc: function () { return this.reverse() }, eachKey: function (t) { var n = this._ctx; return n.keysOnly = !n.isMatch, this.each((function (n, e) { t(e.key, e) })) }, eachUniqueKey: function (t) { return this._ctx.unique = "unique", this.eachKey(t) }, eachPrimaryKey: function (t) { var n = this._ctx; return n.keysOnly = !n.isMatch, this.each((function (n, e) { t(e.primaryKey, e) })) }, keys: function (t) { var n = this._ctx; n.keysOnly = !n.isMatch; var e = []; return this.each((function (t, n) { e.push(n.key) })).then((function () { return e })).then(t) }, primaryKeys: function (t) { var n = this._ctx; if (s && "next" === n.dir && _t(n, !0) && n.limit > 0) return this._read((function (t, r, i) { var o = e(n, i), a = n.limit < 1 / 0 ? o.getAllKeys(n.range, n.limit) : o.getAllKeys(n.range); a.onerror = Pn(r), a.onsuccess = Sn(t) })).then(t); n.keysOnly = !n.isMatch; var r = []; return this.each((function (t, n) { r.push(n.primaryKey) })).then((function () { return r })).then(t) }, uniqueKeys: function (t) { return this._ctx.unique = "unique", this.keys(t) }, firstKey: function (t) { return this.limit(1).keys((function (t) { return t[0] })).then(t) }, lastKey: function (t) { return this.reverse().firstKey(t) }, distinct: function () { var n = this._ctx, e = n.index && n.table.schema.idxByName[n.index]; if (!e || !e.multi) return this; var r = {}; return t(this._ctx, (function (t) { var n = t.primaryKey.toString(), e = c(r, n); return r[n] = !0, !e })), this }, modify: function (t) { var n = this, e = this._ctx.table.hook, i = e.updating.fire, o = e.deleting.fire; return this._write((function (e, u, s, f) { var h; if ("function" == typeof t) h = i === X && o === X ? t : function (n) { var e = j(n); if (!1 === t.call(this, n, this)) return !1; if (c(this, "value")) { var a = P(e, this.value), u = i.call(this, a, this.primKey, e, f); u && (n = this.value, r(u).forEach((function (t) { k(n, t, u[t]) }))) } else o.call(this, this.primKey, n, f) }; else if (i === X) { var l = r(t), d = l.length; h = function (n) { for (var e = !1, r = 0; r < d; ++r) { var i = l[r], o = t[i]; E(n, i) !== o && (k(n, i, o), e = !0) } return e } } else { var p = t; t = D(p), h = function (n) { var e = !1, o = i.call(this, t, this.primKey, j(n), f); return o && a(t, o), r(t).forEach((function (r) { var i = t[r]; E(n, r) !== i && (k(n, r, i), e = !0) })), o && (t = D(p)), e } } var v = 0, g = 0, y = !1, m = [], b = [], w = null; function _(t) { return t && (m.push(t), b.push(w)), u(new W("Error modifying one or more objects", m, g, b)) } function I() { y && g + m.length === v && (m.length > 0 ? _() : e(g)) } n.clone().raw()._iterate((function (t, n) { w = n.primaryKey; var e = { primKey: n.primaryKey, value: t, onsuccess: null, onerror: null }; function r(t) { return m.push(t), b.push(e.primKey), I(), !0 } if (!1 !== h.call(e, t, e)) { var i = !c(e, "value"); ++v, x((function () { var t = i ? n.delete() : n.update(e.value); t._hookCtx = e, t.onerror = An(r), t.onsuccess = jn((function () { ++g, I() })) }), r) } else e.onsuccess && e.onsuccess(e.value) }), (function () { y = !0, I() }), _, s) })) }, delete: function () { var t = this, n = this._ctx, e = n.range, r = n.table.hook.deleting.fire, i = r !== X; if (!i && _t(n) && (n.isPrimKey && !kn || !e)) return this._write((function (t, n, r) { var i = Pn(n), o = e ? r.count(e) : r.count(); o.onerror = i, o.onsuccess = function () { var a = o.result; x((function () { var n = e ? r.delete(e) : r.clear(); n.onerror = i, n.onsuccess = function () { return t(a) } }), (function (t) { return n(t) })) } })); var o = i ? 2e3 : 1e4; return this._write((function (e, a, u, s) { var c = 0, f = t.clone({ keysOnly: !n.isMatch && !i }).distinct().limit(o).raw(), h = [], l = function () { return f.each(i ? function (t, n) { h.push([n.primaryKey, n.value]) } : function (t, n) { h.push(n.primaryKey) }).then((function () { return i ? h.sort((function (t, n) { return Rt(t[0], n[0]) })) : h.sort(Rt), yt(u, s, h, i, r) })).then((function () { var t = h.length; return c += t, h = [], t < o ? c : l() })) }; e(l()) })) } } })), a(this, { Collection: wt, Table: vt, Transaction: mt, Version: st, WhereClause: bt }), J.on("versionchange", (function (t) { t.newVersion > 0 ? console.warn("Another connection wants to upgrade database '" + J.name + "'. Closing db now to resume the upgrade.") : console.warn("Another connection wants to delete database '" + J.name + "'. Closing db now to resume the delete request."), J.close() })), J.on("blocked", (function (t) { !t.newVersion || t.newVersion < t.oldVersion ? console.warn("Dexie.delete('" + J.name + "') was blocked") : console.warn("Upgrade '" + J.name + "' blocked by other connection holding version " + t.oldVersion / 10) })), g.forEach((function (t) { t(J) })) } function On(t) { if ("function" == typeof t) return new t; if (i(t)) return [On(t[0])]; if (t && "object" == typeof t) { var n = {}; return Rn(n, t), n } return t } function Rn(t, n) { return r(n).forEach((function (e) { var r = On(n[e]); t[e] = r })), t } function jn(t) { return Wt((function (n) { var e = n.target, r = e._hookCtx, i = r.value || e.result, o = r && r.onsuccess; o && o(i), t && t(i) }), t) } function Pn(t) { return Wt((function (n) { return Tn(n), t(n.target.error), !1 })) } function Sn(t) { return Wt((function (n) { t(n.target.result) })) } function An(t) { return Wt((function (n) { var e = n.target, r = e.error, i = e._hookCtx, o = i && i.onerror; return o && o(r), Tn(n), t(r), !1 })) } function Tn(t) { t.stopPropagation && t.stopPropagation(), t.preventDefault && t.preventDefault() } function Cn(t) { var n = function (n) { return t.next(n) }, e = o(n), r = o((function (n) { return t.throw(n) })); function o(t) { return function (n) { var o = t(n), a = o.value; return o.done ? a : a && "function" == typeof a.then ? a.then(e, r) : i(a) ? Pt.all(a).then(e, r) : e(a) } } return o(n)() } function Kn(t, n, e, r, i, o, a) { this.name = t, this.keyPath = n, this.unique = e, this.multi = r, this.auto = i, this.compound = o, this.dotted = a; var u = "string" == typeof n ? n : n && "[" + [].join.call(n, "+") + "]"; this.src = (e ? "&" : "") + (r ? "*" : "") + (i ? "++" : "") + u } function Bn(t, n, e, r) { this.name = t, this.primKey = n || new Kn, this.indexes = e || [new Kn], this.instanceTemplate = r, this.mappedClass = null, this.idxByName = _(e, (function (t) { return [t.name, t] })) } function Fn(t) { return 1 === t.length ? t[0] : t } function Nn(t) { var n = t && (t.getDatabaseNames || t.webkitGetDatabaseNames); return n && n.bind(t) } B(K, Dn), f(In, Y), f(In, { delete: function (t) { var n = new In(t), e = n.delete(); return e.onblocked = function (t) { return n.on("blocked", t), this }, e }, exists: function (t) { return new In(t).open().then((function (t) { return t.close(), !0 })).catch(In.NoSuchDatabaseError, (function () { return !1 })) }, getDatabaseNames: function (t) { var n = Nn(In.dependencies.indexedDB); return n ? new Pt((function (t, e) { var r = n(); r.onsuccess = function (n) { t(y(n.target.result, 0)) }, r.onerror = Pn(e) })).then(t) : pn.dbnames.toCollection().primaryKeys(t) }, defineClass: function () { return function (t) { t && a(this, t) } }, applyStructure: Rn, ignoreTransaction: function (t) { return It.trans ? un(It.transless, t) : t() }, vip: function (t) { return Xt((function () { return It.letThrough = !0, t() })) }, async: function (t) { return function () { try { var n = Cn(t.apply(this, arguments)); return n && "function" == typeof n.then ? n : Pt.resolve(n) } catch (t) { return ln(t) } } }, spawn: function (t, n, e) { try { var r = Cn(t.apply(e, n || [])); return r && "function" == typeof r.then ? r : Pt.resolve(r) } catch (t) { return ln(t) } }, currentTransaction: { get: function () { return It.trans || null } }, waitFor: function (t, n) { var e = Pt.resolve("function" == typeof t ? In.ignoreTransaction(t) : t).timeout(n || 6e4); return It.trans ? It.trans.waitFor(e) : e }, Promise: Pt, debug: { get: function () { return K }, set: function (t) { B(t, "dexie" === t ? function () { return !0 } : Dn) } }, derive: d, extend: a, props: f, override: m, Events: dn, getByKeyPath: E, setByKeyPath: k, delByKeyPath: function (t, n) { "string" == typeof n ? k(t, n, void 0) : "length" in n && [].map.call(n, (function (n) { k(t, n, void 0) })) }, shallowClone: D, deepClone: j, getObjectDiff: P, asap: w, maxKey: yn, minKey: mn, addons: [], connections: _n, MultiModifyError: H.Modify, errnames: G, IndexSpec: Kn, TableSchema: Bn, dependencies: function () { try { return { indexedDB: o.indexedDB || o.mozIndexedDB || o.webkitIndexedDB || o.msIndexedDB, IDBKeyRange: o.IDBKeyRange || o.webkitIDBKeyRange } } catch (t) { return { indexedDB: null, IDBKeyRange: null } } }(), semVer: vn, version: vn.split(".").map((function (t) { return parseInt(t) })).reduce((function (t, n, e) { return t + n / Math.pow(10, 2 * e) })), default: In, Dexie: In }), Pt.rejectionMapper = function (t, n) { if (!t || t instanceof z || t instanceof TypeError || t instanceof SyntaxError || !t.name || !J[t.name]) return t; var e = new J[t.name](n || t.message, t); return "stack" in t && l(e, "stack", { get: function () { return this.inner.stack } }), e }, (pn = new In("__dbnames")).version(1).stores({ dbnames: "name" }), function () { var t = "Dexie.DatabaseNames"; try { void 0 !== typeof localStorage && void 0 !== o.document && (JSON.parse(localStorage.getItem(t) || "[]").forEach((function (t) { return pn.dbnames.put({ name: t }).catch(X) })), localStorage.removeItem(t)) } catch (t) { } }(); const Mn = In } }, n = {}; function e(r) { var i = n[r]; if (void 0 !== i) return i.exports; var o = n[r] = { exports: {} }; return t[r].call(o.exports, o, o.exports, e), o.exports } e.n = t => { var n = t && t.__esModule ? () => t.default : () => t; return e.d(n, { a: n }), n }, e.d = (t, n) => { for (var r in n) e.o(n, r) && !e.o(t, r) && Object.defineProperty(t, r, { enumerable: !0, get: n[r] }) }, e.g = function () { if ("object" == typeof globalThis) return globalThis; try { return this || new Function("return this")() } catch (t) { if ("object" == typeof window) return window } }(), e.o = (t, n) => Object.prototype.hasOwnProperty.call(t, n), e.r = t => { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, (() => { "use strict"; var t = e(128), n = e(534), r = e.n(n), i = e(363), o = e.n(i); const a = { debug: !1 }; /* console.log("[*] Cargando RanasDB..."); */ class u { static get Dexie() { return t.default } static get DexieRelationships() { return r() } static get Check() { return o() } static create(t, n, e, r) { return new u(t, n, e, r) } static connect(t, n, e, r) { return new u(t, n, e, r).initialize() } static dropDatabase(t) { return u.Dexie.delete(t) } static dropDatabaseIfExists(t) { try { return u.Dexie.delete(t) } catch (t) { } } static get defaultOptions() { return a } constructor(n = "Base_de_datos_por_defecto_de_ranas_db", e = [], i = this.constructor.defaultOptions, a = {}) { o().that(n).isString(), o().that(e).isArray(); for (let t = 0; t < e.length; t++) { const n = e[t]; o().that(n).isArray().hasLengthGreaterThan(1), o().that(n[0]).isObject(), o().that(n[1]).isFunction() } this.options = i, this.databaseID = n, this.versionation = e, this.dexieDB = new t.default(this.databaseID, { addons: [r()] }) } debug(...t) { "function" == typeof this.options.debug && this.options.debug(...t) } initialize() { if (this.debug(`Initializing: #${this.databaseID}`), !this.dexieDB.isOpen()) for (let t = 0; t < this.versionation.length; t++) { const [n, e] = this.versionation[t], r = this.dexieDB.version(t + 1).stores(n); e && r.upgrade(e) } return this } select(t, n = (() => !0), e = []) { this.debug(`Selecting on: #${this.databaseID} » ${t}`, { table: t, filter: n, joins: e }), o().that(t).isString(), o().that(n).isFunction(); let r = this.dexieDB.table(t).filter(n); for (let t = 0; t < e.length; t++) { let n = e[t]; r = r.with({ [n]: n }) } return r.toArray() } insert(t, n) { return this.debug(`Inserting on: #${this.databaseID} » ${t}`, { table: t, item: n }), o().that(t).isString(), o().that(n).isObject(), this.dexieDB.table(t).add(n) } update(t, n, e) { return this.debug(`Updating on: #${this.databaseID} » ${t}`, { table: t, id: n, value: e }), o().that(t).isString(), o().that(n).isNumber(), o().that(e).isObject(), this.dexieDB.table(t).update(n, e) } delete(t, n) { return this.debug(`Deleting on: #${this.databaseID} » ${t}`, { table: t, id: n }), o().that(t).isString(), o().that(n).isNumber(), this.dexieDB.table(t).delete(n) } } "undefined" != typeof window && (window.RanasDB = u), void 0 !== e.g && (e.g.RanasDB = u) })() })();
//Included:lib/013.rest-v0.0.1.part.js
//RestUtils.require("fs").writeFileSync(__dirname + "/../process.json", "" + process.pid, "utf8");
(function (scope, factory) {
const jsmodule = factory();
if (typeof window !== "undefined") {
window.Automatic_http_rest_api_interface = jsmodule;
}
if (typeof global !== "undefined") {
global.Automatic_http_rest_api_interface = jsmodule;
}
if (typeof define === "function") {
define("Automatic_http_rest_api_interface", jsmodule);
}
if (typeof module !== "undefined") {
module.exports = jsmodule;
}
return jsmodule;
})(this, () => function (factoryParameters) {
const defaultConfigurations = {
platform: "node", // "browser"
environment: "production", // "development", "testing"
debug: true,
debugSQL: true,
debugErrors: true,
responseWrapper: {
app: {
title: "Automatic HTTP REST API development",
author: {
name: "allnulled",
telephone: "+34 619 98 26 22",
url: "https://www.github.com/allnulled",
}
}
},
traceCallback: function (id) {
if (configurations.debug) {
if (configurations.platform === "node") {
console.log("\u001b[32m[TRACE]\u001b[0m " + id);
} else {
console.log("[TRACE] " + id);
}
}
},
traceSQLCallback: function (id) {
if (configurations.debugSQL) {
if (configurations.platform === "node") {
console.log("\u001b[33m[·SQL·]\u001b[0m " + id.split("\n").join("\n "));
} else {
console.log("[·SQL·] " + id);
}
}
},
traceErrorCallback: function (error) {
try {
if (configurations.debugErrors) {
let id = undefined;
if (typeof error === "string") {
id = error;
} else if (error instanceof Error) {
id = error.name + ": " + error.message + "\n " + error.stack + "";
}
if (configurations.platform === "node") {
console.log("\u001b[31m[ERROR]\u001b[0m " + id.split("\n").join("\n "));
} else {
console.log("[ERROR] " + id);
}
}
} catch (error) {
console.log(error);
}
},
};
const configurations = Object.assign(defaultConfigurations, factoryParameters);
const trace = configurations.traceCallback;
const traceSQL = configurations.traceSQLCallback;
const traceError = configurations.traceErrorCallback;
const RestClient = function (baseUrl, client = {}) {
Object.assign(client, {
defaults: {
headers: {
common: {
// @CONFIGURABLE
}
}
},
request: (method, url, requestArgs = {}, requestConfigArgs = {}, responseArgs = {}, ...args) => {
trace("DataServer.prototype.createClient:request");
const parsedUrl = RestUtils.require("url").parse(url);
trace("RestClient is requesting: " + url);
const requestParameters = Object.assign({}, requestArgs);
const responseParameters = Object.assign({}, responseArgs);
if (configurations.platform === "browser") {
const queryParameters = Object.assign({}, requestParameters);
requestParameters.headers = Object.assign({}, client.defaults.headers.common, requestConfigArgs.headers || {});
requestParameters.query = queryParameters;
if (parsedUrl.pathname.startsWith(client.server.basePathForData)) {
return client.server.dispatchSelf(method, url, requestParameters, responseParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForAuth)) {
return client.server.dispatchSelf(method, url, requestParameters, responseParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForProcess)) {
return client.server.dispatchSelf(method, url, requestParameters, responseParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForQuery)) {
return client.server.dispatchSelf(method, url, requestParameters, responseParameters, ...args);
} else {
throw new Error("Required parameter «url» to start as a valid basepath on browser in order to «createClient:request»");
}
} else if (configurations.platform === "node") {
const requestConfigParameters = Object.assign({}, { headers: {} }, requestConfigArgs);
Object.assign(requestConfigParameters.headers, client.defaults.headers.common,)
if (parsedUrl.pathname.startsWith(client.server.basePathForData)) {
return require("axios").create()[method](url, requestParameters, requestConfigParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForAuth)) {
return require("axios").create()[method](url, requestParameters, requestConfigParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForProcess)) {
return require("axios").create()[method](url, requestParameters, requestConfigParameters, ...args);
} else if (parsedUrl.pathname.startsWith(client.server.basePathForQuery)) {
return require("axios").create()[method](url, requestParameters, requestConfigParameters, ...args);
} else {
throw new Error("Required parameter «url» to start as a valid basepath on browser in order to «createClient:request»");
}
} else {
throw new Error("Required configuration «platform» to be a valid platform on node in order to «createClient:request»");
}
},
auth: {
login: (user, password) => {
trace("DataServer.prototype.createClient:auth:login");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/login");
return this.request("get", finalUrl + "?" + new URLSearchParams({
user,
password,
}).toString());
},
logout: (session_token) => {
trace("DataServer.prototype.createClient:auth:logout");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/logout");
return this.request("get", finalUrl + "?" + new URLSearchParams({
session_token: session_token,
}).toString());
},
register: (user, password, email) => {
trace("DataServer.prototype.createClient:auth:register");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/register");
return this.request("get", finalUrl + "?" + new URLSearchParams({
user,
password,
email,
}).toString());
},
confirm: (token) => {
trace("DataServer.prototype.createClient:auth:confirm");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/confirm");
return this.request("get", finalUrl + "?" + new URLSearchParams({
token,
}).toString());
},
forgot: (user) => {
trace("DataServer.prototype.createClient:auth:forgot");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/forgot");
return this.request("get", finalUrl + "?" + new URLSearchParams({
user,
}).toString());
},
recover: (token) => {
trace("DataServer.prototype.createClient:auth:recover");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/recover");
return this.request("get", finalUrl + "?" + new URLSearchParams({
token,
}).toString());
},
unregister: (user, password) => {
trace("DataServer.prototype.createClient:auth:unregister");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForAuth, "/unregister");
return this.request("get", finalUrl + "?" + new URLSearchParams({
user,
password,
}).toString());
},
},
rest: {
selectOne: (model, where) => {
trace("DataServer.prototype.createClient:rest:selectOne");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/select/one");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where)
}).toString());
},
selectMany: (model, where = [], order = [], group = [], pagination = []) => {
trace("DataServer.prototype.createClient:rest:selectMany");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/select/many");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where),
group: JSON.stringify(group),
order: JSON.stringify(order),
pagination: JSON.stringify(pagination)
}).toString());
},
insertOne: (model, item) => {
trace("DataServer.prototype.createClient:rest:insertOne");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/insert/one");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
item: JSON.stringify(item),
}).toString());
},
insertMany: (model, items) => {
trace("DataServer.prototype.createClient:rest:insertMany");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/insert/many");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
items: JSON.stringify(items),
}).toString());
},
updateOne: (model, where, values) => {
trace("DataServer.prototype.createClient:rest:updateOne");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/update/one");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where),
values: JSON.stringify(values),
}).toString());
},
updateMany: (model, where, values) => {
trace("DataServer.prototype.createClient:rest:updateMany");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/update/many");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where),
values: JSON.stringify(values),
}).toString());
},
deleteOne: (model, where) => {
trace("DataServer.prototype.createClient:rest:deleteOne");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/delete/one");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where),
}).toString());
},
deleteMany: (model, where) => {
trace("DataServer.prototype.createClient:rest:deleteMany");
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForData, model, "/delete/many");
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams({
where: JSON.stringify(where),
}).toString());
},
},
queries: client.server.queries.reduce((output, item) => {
output[item.id] = (parameters, ...args) => {
trace("DataServer.prototype.createClient:queries:" + item.id);
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForQuery, item.path);
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams(parameters), ...args);
};
return output;
}, {}),
processes: client.server.processes.reduce((output, item) => {
output[item.id] = (parameters, ...args) => {
trace("DataServer.prototype.createClient:processes:" + item.id);
const finalUrl = baseUrl + RestUtils.require("path").join(client.server.basePathForProcess, item.path);
trace(finalUrl);
return this.request("get", finalUrl + "?" + new URLSearchParams(parameters), ...args);
};
return output;
}, {})
});
return Object.assign(this, client);
};
////////////////////////////////////////////////////////////////////////
// -1. Hooks class:
const Hooks = function () {
this.hooks = {};
};
Hooks.create = function (...args) {
trace("Hooks.create");
return new Hooks(...args);
};
Hooks.prototype.addHook = function (selectorString, hookId, event) {
trace("Hooks.prototype.addHook");
if (typeof selectorString !== "string") {
throw new Error("Required argument «selectorString» to be an array in order to «addHook»");
} else if (selectorString.length === 0) {
throw new Error("Required argument «selectorString» to have one or more items in order to «addHook»");
}
if (typeof hookId !== "string") {
throw new Error("Required argument «hookId» to be a string in order to «addHook»");
}
if (typeof event !== "function") {
throw new Error("Required argument «event» to be a function in order to «addHook»");
}
if (!(selectorString in this.hooks)) {
this.hooks[selectorString] = [];
}
this.hooks[selectorString].push({
id: hookId,
event
});
return this;
};
Hooks.prototype.addHooks = function (selectorList, hookId, event) {
trace("Hooks.prototype.addHooks");
if (!Array.isArray(selectorList)) {
throw new Error("Required argument «selectorList» to be an array in order to «addHooks»");
} else if (selectorList.length === 0) {
throw new Error("Required argument «selectorList» to have one or more items in order to «addHooks»");
}
if (typeof hookId !== "string") {
throw new Error("Required argument «hookId» to be a string in order to «addHooks»");
}
if (typeof event !== "function") {
throw new Error("Required argument «event» to be a function in order to «addHooks»");
}
const selectors = Array.isArray(selectorList) ? selectorList : [selectorList];
for (let indexSelectors = 0; indexSelectors < selectors.length; indexSelectors++) {
const selector = selectors[indexSelectors];
this.addHook(selector, hookId, event);
}
return this;
};
Hooks.prototype.useHook = async function (selectorString, parameters = {}) {
trace("Hooks.prototype.useHook");
try {
trace("Throwing hook: " + selectorString);
if (typeof selectorString !== "string") {
throw new Error("Required argument «selectorString» to be a string in order to «useHook»");
}
if (typeof parameters !== "object") {
throw new Error("Required argument «parameters» to be an object or omitted in order to «useHook»");
}
if (!(selectorString in this.hooks)) {
return parameters;
}
const hookEvents = this.hooks[selectorString];
IteratingSelection:
for (let indexList = 0; indexList < hookEvents.length; indexList++) {
const hookEvent = hookEvents[indexList];
let hookFunction = undefined;
if (typeof hookEvent === "object") {
if (typeof hookEvent.event === "function") {
hookFunction = hookEvent.event;
} else throw new Error("Required hook «" + selectorString + "» on index «" + indexList + "» on property «event» to be a function in order to «useHook»");
} else throw new Error("Required hook «" + selectorString + "» on index «" + indexList + "» to be an object in order to «useHook»");
const result = await hookFunction(parameters);
if (typeof result !== "undefined") {
parameters = result;
}
}
return parameters;
} catch (error) {
this.onError(error);
}
};
Hooks.prototype.replaceHook = function (selectorString, hookId, eventSource) {
trace("Hooks.prototype.replaceHook");
try {
if (typeof selectorString !== "string") {
throw new Error("Required argument «selectorString» to be a string in order to «replaceHook»");
}
if (!(selectorString in this.hooks)) {
throw new Error("Required argument «selectorString» to be a valid hook id in order to «replaceHook»");
}
if (typeof hookId !== "string") {
throw new Error("Required argument «hookId» to be a string in order to «replaceHook»");
}
if (typeof eventSource !== "object") {
throw new Error("Required argument «eventSource» to be an object in order to «replaceHook»");
}
if (typeof eventSource.id !== "string") {
throw new Error("Required argument «eventSource.id» to be a string in order to «replaceHook»");
}
if (typeof eventSource.event !== "function") {
throw new Error("Required argument «eventSource.event» to be a function in order to «replaceHook»");
}
let count = 0;
const hookEvents = this.hooks[selectorString];
IteratingSelection:
for (let indexList = 0; indexList < hookEvents.length; indexList++) {
const hookEvent = hookEvents[indexList];
if (hookEvent.id === hookId) {
this.hooks[selectorString].splice(indexList, 1, eventSource);
count++;
}
}
return count;
} catch (error) {
this.onError(error);
}
};
Hooks.prototype.removeHook = function (selectorString, hookId) {
trace("Hooks.prototype.removeHook");
try {
if (typeof selectorString !== "string") {
throw new Error("Required argument «selectorString» to be a string in order to «removeHook»");
}
if (!(selectorString in this.hooks)) {
throw new Error("Required argument «selectorString» to be a valid hook id in order to «removeHook»");
}
if (typeof hookId !== "string") {
throw new Error("Required argument «hookId» to be an string in order to «removeHook»");
}
let count = 0;
const hookEvents = this.hooks[selectorString];
IteratingSelection:
for (let indexList = 0; indexList < hookEvents.length; indexList++) {
const hookEvent = hookEvents[indexList];
if (typeof hookEvent === "object") {
if (hookEvent.id === hookId) {
this.hooks[selectorString].splice(indexList, 1);
count++;
}
}
}
return count;
} catch (error) {
this.onError(error);
}
};
////////////////////////////////////////////////////////////////////////
// 0. RestUtils object:
const RestUtils = {
prototype: {},
modules: {},
modulePolyfills: {
"mysql2/promise": {
createConnection: function () {
trace("polyfill://require:mysql2/promise:createConnection");
return {
ping() {
trace("polyfill://require:mysql2/promise:createConnection:ping");
// throw new Error("Method ping must be overriden");
},
query(query, ...args) {
trace("polyfill://require:mysql2/promise:createConnection:query");
console.log("Function «RestUtils.modulePolyfills.mysql2/promises.createConnection.query» to be overwritten");
console.log(query);
return [[], []];
},
proxifiedQuery(query, ...args) {
trace("polyfill://require:mysql2/promise:createConnection:proxifiedQuery");
traceSQL(query);
return this.query(query, ...args);
}
}
}
},
"url": {
parse: function (parameter) {
trace("polyfill://require:url:parse x " + parameter);
return new URL(parameter);
},
},
"sqlstring": {
sanitize: function (arg) {
trace("polyfill://require:sqlstring:sanitize");
return arg;
},
sanitizeId: function (arg) {
trace("polyfill://require:sqlstring:sanitizeId");
return arg;
},
},
"path": {
resolve: function (...args) {
trace("polyfill://require:path:resolve");
return ["", ...args].map(i => i.replace(/^\//g, "").replace(/\/$/g, "")).join("/");
},
join: function (...args) {
trace("polyfill://require:path:join");
return ["", ...args].filter(i => typeof i !== "undefined").map(i => i.replace(/^\//g, "").replace(/\/$/g, "")).join("/");
},
},
"http": {
createServer: function (controller) {
trace("polyfill://require:http:createServer");
return {
listen: function (options, callback) {
trace("polyfill://require:http:createServer:listen");
setTimeout(callback, 0);
}
}
}
},
},
require: function (modulepath) {
trace("RestUtils.require");
if (modulepath in RestUtils.modules) {
return RestUtils.modules[modulepath];
}
if (configurations.platform === "browser") {
if (modulepath in RestUtils.modulePolyfills) {
return RestUtils.modulePolyfills[modulepath];
} else {
throw new Error("Not identified package: " + modulepath);
}
}
RestUtils.modules[modulepath] = require(modulepath);
return RestUtils.modules[modulepath];
},
define: function (name, value) {
trace("RestUtils.define");
RestUtils.modules[name] = value;
},
definePolyfill: function (name, value) {
trace("RestUtils.definePolyfill");
RestUtils.modulePolyfills[name] = value;
},
wrapResponse: function (data) {
trace("RestUtils.wrapResponse");
return {
...configurations.responseWrapper,
...data,
time: new Date().toString()
};
},
respondContext: function (context) {
trace("RestUtils.respondContext");
const response = context.output;
const responseWrapped = RestUtils.wrapResponse(response);
const responseJson = JSON.stringify(responseWrapped, null, 2);
context.response.writeHead(200, { "Content-type": "application/json" });
context.response.write(responseJson);
return context.response.end();
},
generateRandomToken: function (len, alphabet = "abcdefghijklmnopqrstuvwxyz0123456789") {
trace("RestUtils.generateRandomToken");
let output = "";
for (let index = 0; index < len; index++) {
output += alphabet[Math.floor(Math.random() * alphabet.length)];
}
return output;
},
generateOnErrorFunction: function (id) {
trace("RestUtils.generateOnErrorFunction");
return function (error, propagate = true) {
trace(id);
traceError(error);
if (propagate) {
throw error;
}
};
},
generateContextByRequestResponseFactory: function (id) {
trace("RestUtils.generateContextByRequestResponseFactory");
return function (request, response) {
trace(id);
const parsedURL = RestUtils.require("url").parse(request.url, true);
return {
output: {},
parameters: {},
state: {},
input: {
url: parsedURL.pathname,
query: RestUtils.fromURLToQuerystringObject(request.url),
body: request.body,
params: request.params,
request,
response
},
request,
response,
};
};
},
generateOnDispatchErrorFunction: function (traceId) {
trace("RestUtils.generateOnDispatchErrorFunction");
return function (error, request, response) {
trace(traceId);
traceError(error);
response.writeHead(500, { "Content-Type": "application/json" });
const data = {
name: error.name,
message: error.message,
stack: Object.assign({}, error.stack.split(/\n /g))
};
const wrappedData = RestUtils.wrapResponse({
status: "error",
error: data
});
const wrappedJson = JSON.stringify(wrappedData, null, 2);
response.write(wrappedJson);
return response.end();
};
},
noop: function () { },
basicServiceFactory: function () {
trace("RestUtils.basicServiceFactory");
return function (modifications) {
trace("RestUtils.basicServiceFactory:Service");
Object.assign(this, modifications);
return this;
}
},
basicQueryFactory: function () {
trace("RestUtils.basicQueryFactory");
return function () {
trace("RestUtils.basicQueryFactory:Query");
return this;
}
},
basicProcessFactory: function () {
trace("RestUtils.basicProcessFactory");
return function () {
trace("RestUtils.basicProcessFactory:Process");
return this;
}
},
basicControllerFallback: function (request, response) {
trace("RestUtils.basicControllerFallback");
response.writeHead(404);
response.write("Error 404: Page was not found.");
return response.end();
},
sanitize: function (value) {
trace("RestUtils.sanitize");
return RestUtils.require("sqlstring").escape(value);
},
sanitizeId: function (id) {
trace("RestUtils.sanitizeId");
return RestUtils.require("sqlstring").escapeId(id);
},
availableOperators: {
"<": "<",
"<=": "<=",
">": ">",
">=": ">=",
"=": "=",
"!=": "!=",
"in": "IN",
"!in": "NOT IN",
// "contains": "contains",
// "!contains": "!contains",
},
validateStaticServiceInterface: function (staticInterface) {
trace("RestUtils.validateStaticServiceInterface");
if (typeof staticInterface !== "function") {
throw new Error("Required parameter «staticInterface» to be an function in order to «validateStaticServiceInterface»")
}
if (typeof staticInterface.table !== "string") {
throw new Error("Required parameter «staticInterface.table» to be a string in order to «validateStaticServiceInterface»")
}
if (typeof staticInterface.path !== "string") {
throw new Error("Required parameter «staticInterface.path» to be a string in order to «validateStaticServiceInterface»")
}
if (typeof staticInterface.creationScript !== "string") {
throw new Error("Required parameter «staticInterface.creationScript» to be a string in order to «validateStaticServiceInterface»")
}
if (typeof staticInterface.schema !== "object") {
throw new Error("Required parameter «staticInterface.schema» to be an object in order to «validateStaticServiceInterface»")
}
return true;
},
validateDynamicServiceInterface: function (dynamicInterface) {
trace("RestUtils.validateDynamicServiceInterface");
return true;
},
validateStaticQueryInterface: function (staticInterface) {
trace("RestUtils.validateStaticQueryInterface");
if (typeof staticInterface.path !== "string") {
throw new Error("Required parameter «staticInterface.path» to be a string in order to «validateStaticQueryInterface»")
}
if (typeof staticInterface.query !== "function") {
throw new Error("Required parameter «staticInterface.query» to be a function in order to «validateStaticQueryInterface»")
}
return true;
},
validateDynamicQueryInterface: function (dynamicInterface) {
trace("RestUtils.validateDynamicQueryInterface");
return true;
},
validateStaticProcessInterface: function (staticInterface) {
trace("RestUtils.validateStaticProcessInterface");
if (typeof staticInterface.path !== "string") {
throw new Error("Required parameter «staticInterface.path» to be a string in order to «validateStaticProcessInterface»")
}
if (typeof staticInterface.process !== "function") {
throw new Error("Required parameter «staticInterface.process» to be a function in order to «validateStaticProcessInterface»")
}
return true;
},
validateDynamicProcessInterface: function (dynamicInterface) {
trace("RestUtils.validateDynamicProcessInterface");
return true;
},
expandConnection: function (connection) {
trace("RestUtils.expandConnection");
connection.proxifiedQuery = function (query) {
trace("RestUtils.expandConnection:connection.proxifiedQuery");
traceSQL(query);
return this.query(query);
}
return connection;
},
formatTableFromRequest: function (context, { start, end }) {
trace("RestUtils.formatTableFromRequest");
return RestUtils.require("url").parse(context.request.url).pathname
.replace(start, "")
.split("")
.reverse()
.join("")
.replace(end.split("").reverse().join(""), "")
.split("")
.reverse()
.join("");
},
formatWhereFromRequest: function (context) {
trace("RestUtils.formatWhereFromRequest");
const where = context.input.query.where || "[]";
if (typeof where === "object") {
return where;
}
let whereData = undefined;
try {
whereData = JSON.parse(where);
} catch (error) {
throw new Error("Required parameter «where» to be a well-formed JSON object in order to «formatWhereFromRequest»");
}
if (!Array.isArray(whereData)) {
throw new Error("Required parameter «where» to be a JSON array in order to «formatWhereFromRequest»");
}
if (whereData.length === 0) {
return whereData;
}
for (let index = 0; index < whereData.length; index++) {
const whereRule = whereData[index];
if (!Array.isArray(whereRule)) {
throw new Error("Required parameter «where[" + index + "]» to be an array in order to «formatWhereFromRequest»");
}
if (whereRule.length < 3) {
throw new Error("Required parameter «where[" + index + "]» to be an array of 3 or more items in order to «formatWhereFromRequest»");
}
if (typeof whereRule[0] !== "string") {
throw new Error("Required parameter «where[" + index + "][0]» to be a string in order to «formatWhereFromRequest»");
}
if (typeof whereRule[1] !== "string") {
throw new Error("Required parameter «where[" + index + "][1]» to be a string in order to «formatWhereFromRequest»");
}
if (!(whereRule[1] in RestUtils.availableOperators)) {
throw new Error("Required parameter «where[" + index + "][1]» to be a valid query operator in order to «formatWhereFromRequest»");
}
}
return whereData;
},
formatOrderFromRequest: function (context) {
trace("RestUtils.formatOrderFromRequest");
const order = context.input.query.order || "[]";
let orderData = undefined;
if (typeof order === "object") {
orderData = order;
} else if (typeof order !== "string") {
throw new Error("Required parameter «context.input.query.order» to be an (optionally JSON) array in order to «formatOrderFromRequest»");
} else {
try {
orderData = JSON.parse(order);
} catch (error) {
throw new Error("Required parameter «order» to be a well-formed JSON object in order to «formatOrderFromRequest»");
}
}
if (!Array.isArray(orderData)) {
throw new Error("Required parameter «order» to be a JSON array in order to «formatOrderFromRequest»");
}
if (orderData.length === 0) {
orderData.push("id");
}
for (let index = 0; index < orderData.length; index++) {
const orderRule = orderData[index];
if (typeof orderRule !== "string") {
throw new Error("Required parameter «order[" + index + "]» to be a string in order to «formatOrderFromRequest»");
}
}
return orderData;
},
formatGroupFromRequest: function (context) {
trace("RestUtils.formatGroupFromRequest");
const group = context.input.query.group || "[]";
let groupData = undefined;
if (typeof group === "object") {
groupData = group;
} else if (typeof group !== "string") {
throw new Error("Required parameter «context.input.query.group» to be an (optionally JSON) array in order to «formatGroupFromRequest»");
} else {
try {
groupData = JSON.parse(group);
} catch (error) {
throw new Error("Required parameter «group» to be a well-formed JSON object in group to «formatGroupFromRequest»");
}
}
if (!Array.isArray(groupData)) {
throw new Error("Required parameter «group» to be a JSON array in group to «formatGroupFromRequest»");
}
if (groupData.length === 0) {
return groupData;
}
for (let index = 0; index < groupData.length; index++) {
const groupRule = groupData[index];
if (typeof groupRule !== "string") {
throw new Error("Required parameter «group[" + index + "]» to be a string in group to «formatGroupFromRequest»");
}
}
return groupData;
},
formatPaginationFromRequest: function (context) {
trace("RestUtils.formatPaginationFromRequest");
const pagination = context.input.query.pagination || "[1,20]";
let paginationData = undefined;
if (typeof pagination === "object") {
paginationData = pagination;
} else if (typeof pagination !== "string") {
throw new Error("Required parameter «context.input.query.pagination» to be an (optionally JSON) array in order to «formatPaginationFromRequest»");
} else {
try {
paginationData = JSON.parse(pagination);
} catch (error) {
throw new Error("Required parameter «pagination» to be a well-formed JSON object in pagination to «formatPaginationFromRequest»");
}
}
if (!Array.isArray(paginationData)) {
throw new Error("Required parameter «pagination» to be a JSON array in pagination to «formatPaginationFromRequest»");
}
if (paginationData.length === 0) {
return paginationData;
}
const [page = 1, items = 20] = paginationData;
if (typeof page !== "number") {
throw new Error("Required parameter «page» to be a number in order to «formatPaginationFromRequest»");
}
if (typeof items !== "number") {
throw new Error("Required parameter «items» to be a number in order to «formatPaginationFromRequest»");
}
if (page < 0) {
throw new Error("Required parameter «pagination[0]» to be a number higher or equal to 0 in order to «formatPaginationFromRequest»");
}
if (items < 1) {
throw new Error("Required parameter «pagination[1]» to be a number higher or equal to 1 in order to «formatPaginationFromRequest»");
}
return paginationData;
},
formatItemFromRequest: function (context) {
trace("RestUtils.formatItemFromRequest");
const item = context.input.query.item || "{}";
let itemData = undefined;
if (typeof item === "object") {
itemData = item;
} else if (typeof item !== "string") {
throw new Error("Required parameter «context.input.query.item» to be an (optionally JSON) object in order to «formatItemFromRequest»");
} else {
try {
itemData = JSON.parse(item);
} catch (error) {
throw new Error("Required parameter «item» to be a well-formed JSON object to «formatItemFromRequest»");
}
}
if (typeof itemData !== "object") {
throw new Error("Required parameter «item» to be a JSON object to «formatItemFromRequest»");
}
return itemData;
},
formatItemsFromRequest: function (context) {
trace("RestUtils.formatItemsFromRequest");
const items = context.input.query.items || "{}";
let itemsData = undefined;
if (typeof items === "object") {
itemsData = items;
} else if (typeof items !== "string") {
throw new Error("Required parameter «context.input.query.items» to be an (optionally JSON) object in order to «formatItemsFromRequest»");
} else {
try {
itemsData = JSON.parse(items);
} catch (error) {
throw new Error("Required parameter «item» to be a well-formed JSON object to «formatItemsFromRequest»");
}
}
if (!Array.isArray(itemsData)) {
throw new Error("Required parameter «items» to be an (optionally JSON) array in order to «formatItemsFromRequest»");
}
for (let index = 0; index < itemsData.length; index++) {
const itemData = itemsData[index];
if (typeof itemData !== "object") {
throw new Error("Required parameter «items[" + index + "]» to be a JSON object to «formatItemsFromRequest»");
}
}
return itemsData;
},
formatValuesFromRequest: function (context) {
trace("RestUtils.formatValuesFromRequest");
const values = context.input.query.values || "{}";
let valuesData = undefined;
if (typeof values === "object") {
valuesData = values;
} else if (typeof values !== "string") {
throw new Error("Required parameter «context.input.query.values» to be an (optionally JSON) object in order to «formatValuesFromRequest»");
} else {
try {
valuesData = JSON.parse(values);
} catch (error) {
throw new Error("Required parameter «values» to be a well-formed JSON object to «formatValuesFromRequest»");
}
}
if (Array.isArray(valuesData)) {
throw new Error("Required parameter «values» to be an object and not an array in order to «formatValuesFromRequest»");
} else if (typeof valuesData !== "object") {
throw new Error("Required parameter «values» to be an object in order to «formatValuesFromRequest»");
}
return valuesData;
},
fromWhereToSQL: function (where, wholeClause = false) {
trace("RestUtils.fromWhereToSQL");
if (!Array.isArray(where)) {
throw new Error("Required parameter «where» to be an array in order to «fromWhereToSQL»");
}
if (where.length === 0) {
return "# No filtering rules";
}
let query = where.map((whereRule, index) => {
const sanitizedSubject = RestUtils.sanitizeId(whereRule[0]);
const sanitizedOperation = RestUtils.availableOperators[whereRule[1]];
const unsanitizedObject = whereRule[2];
const thirdArgumentMode = whereRule[3] || "default";
let sanitizedObject = whereRule[2];
if (thirdArgumentMode === "default") {
if ((typeof unsanitizedObject !== "string") && (typeof unsanitizedObject !== "number")) {
throw new Error("Required argument «where[" + index + "][2]» to be a string or a number (on «default» mode) in order to «RestUtils.fromWhereToSQL»");
}
sanitizedObject = RestUtils.sanitize(unsanitizedObject);
} else if (thirdArgumentMode === "column") {
throw new Error("Required argument «where[" + index + "][3]» to be a valid mode and 'column' mode is not allowed in order to «RestUtils.fromWhereToSQL»");
sanitizedObject = RestUtils.sanitizeId(unsanitizedObject);
} else if (thirdArgumentMode === "null") {
sanitizedObject = "NULL";
} else if (thirdArgumentMode === "array") {
let parsedObject = undefined;
if (typeof unsanitizedObject === "string") {
try {
parsedObject = JSON.parse(unsanitizedObject);
} catch (error) {
throw new Error("Required argument «where[" + index + "][3]» to be a well-formed JSON in order to «RestUtils.fromWhereToSQL»");
}
} else if (Array.isArray(unsanitizedObject)) {
parsedObject = unsanitizedObject;
} else {
throw new Error("Required argument «where[" + index + "][2]» to be an (optionally JSON) array in order to «RestUtils.fromWhereToSQL»");
}
if (!Array.isArray(parsedObject)) {
throw new Error("Required argument «where[" + index + "][2]» to be a JSON array in order to «RestUtils.fromWhereToSQL»");
} else if (parsedObject.length === 0) {
throw new Error("Required argument «where[" + index + "][2]» to be a JSON array with 1 or more items in order to «RestUtils.fromWhereToSQL»");
}
sanitizedObject = "(" + parsedObject.map(item => RestUtils.sanitize(item)) + ")";
} else {
throw new Error("Required argument «where[" + index + "][3]» to be a a known mode in order to «RestUtils.fromWhereToSQL»");
}
return ` AND ${sanitizedSubject} ${sanitizedOperation} ${sanitizedObject}`;
}).join("\n");
if (wholeClause) {
query = query.replace(' AND ', ' WHERE ');
}
return query;
},
fromOrderToSQL: function (order, wholeClause = true) {
trace("RestUtils.fromOrderToSQL");
if (!Array.isArray(order)) {
throw new Error("Required parameter «order» to be an array in order to «fromOrderToSQL»");
}
if (order.length === 0) {
return "# No ordering rules";
}
let query = order.map((orderRule, index) => {
if (typeof orderRule !== "string") {
throw new Error("Required parameter «order[" + index + "]» to be a string in order «fromOrderToSQL»");
}
const isDescending = orderRule.startsWith("!");
const orderColumn = isDescending ? orderRule.substr(1) : orderRule;
return ", " + RestUtils.sanitizeId(orderColumn) + (isDescending ? ' DESC' : ' ASC');
}).join(", ");
if (wholeClause) {
query = query.replace(', ', ' ORDER BY ');
}
return query;
},
fromGroupToSQL: function (groups, wholeClause = true) {
trace("RestUtils.fromGroupToSQL");
if (!Array.isArray(groups)) {
throw new Error("Required parameter «groups» to be an array in order to «fromGroupToSQL»");
}
if (groups.length === 0) {
return "# No grouping rules";
}
let query = groups.map((groupsRule, index) => {
if (typeof groupsRule !== "string") {
throw new Error("Required parameter «groups[" + index + "]» to be a string in order «fromGroupToSQL»");
}
const isDescending = groupsRule.startsWith("!");
const groupsColumn = isDescending ? groupsRule.substr(1) : groupsRule;
return ", " + RestUtils.sanitizeId(groupsColumn) + (isDescending ? ' DESC' : ' ASC');
}).join(", ");
if (wholeClause) {
query = query.replace(', ', ' GROUP BY ');
}
return query;
},
fromPaginationToSQL: function (pagination = []) {
trace("RestUtils.fromPaginationToSQL");
if (!Array.isArray(pagination)) {
throw new Error("Required parameter «pagination» to be an array in order to «fromPaginationToSQL»");
}
const [page = 1, items = 20] = pagination;
if (typeof page !== "number") {
throw new Error("Required parameter «pagination[0]» to be an array in order to «fromPaginationToSQL»");
}
if (typeof items !== "number") {
throw new Error("Required parameter «pagination[1]» to be an array in order to «fromPaginationToSQL»");
}
if (page < 0) {
throw new Error("Required parameter «pagination[0]» to be a number higher or equal to 0 in order to «fromPaginationToSQL»");
}
if (items < 1) {
throw new Error("Required parameter «pagination[1]» to be a number higher or equal to 1 in order to «fromPaginationToSQL»");
}
if (page === 0) {
return "# No pagination rules";
}
const limit = items;
const offset = (page - 1) * items;
const query = [
` LIMIT ${limit}`,
` OFFSET ${offset}`,
].join("\n");
return query;
},
fromItemToKeysSQL: function (item, wholeToken = true) {
trace("RestUtils.fromItemToKeysSQL");
if (typeof item !== "object") {
throw new Error("Required argument «item» to be an object in order to «fromItemToKeysSQL»");
}
const keys = Object.keys(item);
const query = keys.map(key => RestUtils.sanitizeId(key)).join(", ");
if (wholeToken) {
return "(" + query + ")";
}
return query;
},
fromItemsToKeysSQL: function (items, wholeExpression = true) {
trace("RestUtils.fromItemsToKeysSQL");
if (typeof items !== "object") {
throw new Error("Required argument «items» to be an object in order to «fromItemsToKeysSQL»");
}
if (!Array.isArray(items)) {
throw new Error("Required argument «items» to be an array in order to «fromItemsToKeysSQL»");
}
if (items.length === 0) {
throw new Error("Required argument «items» to have one or more items in order to «fromItemsToKeysSQL»");
}
return this.fromItemToKeysSQL(items[0], wholeExpression);
},
fromItemToValuesSQL: function (item, wholeToken = true) {
trace("RestUtils.fromItemToValuesSQL");
if (typeof item !== "object") {
throw new Error("Required argument «item» to be an object in order to «fromItemToValuesSQL»");
}
const keys = Object.keys(item);
const query = keys.map(key => RestUtils.sanitize(item[key])).join(", ");
if (wholeToken) {
return "(" + query + ")";
}
return query;
},
fromItemToSettablesSQL: function (item, wholeToken = false) {
trace("RestUtils.fromItemToSettablesSQL");
if (typeof item !== "object") {
throw new Error("Required argument «item» to be an object in order to «fromItemToSettablesSQL»");
}
const keys = Object.keys(item);
const query = keys.map(key => "\n " + RestUtils.sanitizeId(key) + " = " + RestUtils.sanitize(item[key])).join(",");
if (wholeToken) {
return "(" + query + ")";
}
return query;
},
fromItemsToValuesSQL: function (items, wholeExpression = true) {
trace("RestUtils.fromItemsToValuesSQL");
const query = items.map((item, index) => {
if (typeof item !== "object") {
throw new Error("Required argument «items[" + index + "]» to be an object in order to «fromItemsToValuesSQL»");
}
const itemQuery = "(" + Object.keys(item).map((key, index) => {
return "\n " + RestUtils.sanitize(item[key]);
}).join(", ") + "\n )";
return itemQuery;
}).join(", ");
return query;
},
fromWhereToFilterFunction(whereRules) {
const allFilters = [];
for (let indexRules = 0; indexRules < whereRules.length; indexRules++) {
const whereRule = whereRules[indexRules];
const [subject, operator, target, targetType = "value"] = whereRule;
const t1 = subject;
const t2 = RestUtils.availableOperators[operator];
const t3 = targetType === "value" ? target : targetType === "array" ? JSON.parse(target) : target;
const partialFilter = item => {
// trace("RestUtils.fromWhereToFilterFunction:partialFilter");
if (!(t1 in item)) return false;
const s1 = item[t1];
const s2 = t2;
const s3 = t3;
switch (s2) {
case "<":
return s1 < s3;
case "<=":
return s1 <= s3;
case ">":
return s1 > s3;
case ">=":
return s1 >= s3;
case "!=":
return s1 !== s3;
case "=":
return s1 === s3;
case "!in":
return s3.indexOf(s1) === -1;
case "in":
return s3.indexOf(s1) !== -1;
}
return false;
};
allFilters.push((() => partialFilter)());
};
const finalFilter = function (item) {
// trace("RestUtils.fromWhereToFilterFunction:finalFilter");
for (let indexFilters = 0; indexFilters < allFilters.length; indexFilters++) {
const oneFilter = allFilters[indexFilters];
const result = oneFilter(item);
if (!result) {
return false;
}
}
return true;
};
return finalFilter;
},
fromURLToQuerystringObject(url) {
const output = {};
const searchParams = new URLSearchParams(this.require("url").parse(url).search);
searchParams.forEach((value, key) => {
output[key] = value;
});
return output;
}
};
////////////////////////////////////////////////////////////////////////
// 1. RestInterface class:
const RestInterface = function () { };
RestInterface.prototype.initialize = function () { throw new Error("Required method «initialize» to be overriden") };
RestInterface.prototype.selectMany = function (dataType, { where, order, groups, page, items }, authentication) { throw new Error("Required method «selectMany» to be overriden") };
RestInterface.prototype.selectOne = function (dataType, { where, order }, authentication) { throw new Error("Required method «selectOne» to be overriden") };
RestInterface.prototype.insertMany = function (dataType, { values }, authentication) { throw new Error("Required method «insertMany» to be overriden") };
RestInterface.prototype.insertOne = function (dataType, { value }, authentication) { throw new Error("Required method «insertOne» to be overriden") };
RestInterface.prototype.updateMany = function (dataType, { where, value }, authentication) { throw new Error("Required method «updateMany» to be overriden") };
RestInterface.prototype.updateOne = function (dataType, { where, value }, authentication) { throw new Error("Required method «updateOne» to be overriden") };
RestInterface.prototype.deleteMany = function (dataType, { where }, authentication) { throw new Error("Required method «deleteMany» to be overriden") };
RestInterface.prototype.deleteOne = function (dataType, { where }, authentication) { throw new Error("Required method «deleteOne» to be overriden") };
RestInterface.prototype.getFile = function (dataType, { id, column }, authentication) { throw new Error("Required method «getFile» to be overriden") };
RestInterface.prototype.setFile = function (dataType, { id, column, file }, authentication) { throw new Error("Required method «setFile» to be overriden") };
RestInterface.prototype.resetDatabase = function (authentication) { throw new Error("Required method «resetDatabase» to be overriden") };
////////////////////////////////////////////////////////////////////////
// 2. AuthInterface class:
const AuthInterface = function () { };
AuthInterface.prototype.initialize = function () { throw new Error("Required method «initialize» to be overriden") };
AuthInterface.prototype.authenticate = function (token) { throw new Error("Required method «authenticate» to be overriden") };
AuthInterface.prototype.login = function ({ user, password }) { throw new Error("Required method «login» to be overriden") };
AuthInterface.prototype.logout = function (token) { throw new Error("Required method «logout» to be overriden") };
AuthInterface.prototype.refresh = function (token) { throw new Error("Required method «refresh» to be overriden") };
AuthInterface.prototype.register = function ({ user, password, email }) { throw new Error("Required method «register» to be overriden") };
AuthInterface.prototype.confirm = function (confirmationToken) { throw new Error("Required method «confirm» to be overriden") };
AuthInterface.prototype.forgot = function () { throw new Error("Required method «forgot» to be overriden") };
AuthInterface.prototype.recover = function (recoverToken) { throw new Error("Required method «recover» to be overriden") };
AuthInterface.prototype.unregister = function () { throw new Error("Required method «unregister» to be overriden") };
AuthInterface.prototype.hasAuthorizationFor = function () { throw new Error("Required method «isAuthorizedFor» to be overriden") };
AuthInterface.prototype.resetAuth = function () { throw new Error("Required method «resetAuth» to be overriden") };
////////////////////////////////////////////////////////////////////////
// 4. DataServer class:
const DataServer = function (dynamicInterface = {}) {
trace("DataServer.constructor");
Object.assign(this, dynamicInterface);
this.client = configurations.platform === "node" ? require("axios").create() : {};
this.rest = undefined;
this.auth = undefined;
this.services = [];
this.queries = [];
this.processes = [];
this.hooks = Hooks.create();
this.basePathForData = "/rest/api/v1";
this.basePathForAuth = "/auth/api/v1";
this.basePathForQuery = "/query/api/v1";
this.basePathForProcess = "/process/api/v1";
return this;
};
DataServer.create = function (...args) {
trace("DataServer.create");
return new this(...args);
};
DataServer.initialize = function (...args) {
trace("DataServer.initialize");
return (new this(...args)).initialize();
};
DataServer.prototype.addService = function (...args) {
trace("DataServer.prototype.addService");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicServiceFactory()
const service = constructorFunction;
Object.assign(service, { ...DataService }, { ...staticInterface });
Object.assign(service.prototype, { ...DataService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticServiceInterface(service);
RestUtils.validateDynamicServiceInterface(service.prototype);
this.services.push(service);
return this;
};
DataServer.prototype.addQuery = function (...args) {
trace("DataServer.prototype.addQuery");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicQueryFactory()
const queryClass = constructorFunction;
Object.assign(queryClass, { ...QueryService }, { ...staticInterface });
Object.assign(queryClass.prototype, { ...QueryService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticQueryInterface(queryClass);
RestUtils.validateDynamicQueryInterface(queryClass.prototype);
this.queries.push(queryClass);
return this;
};
DataServer.prototype.addProcess = function (...args) {
trace("DataServer.prototype.addProcess");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicProcessFactory()
const processClass = constructorFunction;
Object.assign(processClass, { ...ProcessService }, { ...staticInterface });
Object.assign(processClass.prototype, { ...ProcessService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticProcessInterface(processClass);
RestUtils.validateDynamicProcessInterface(processClass.prototype);
this.processes.push(processClass);
return this;
};
const RequestPolyfill = function (method, url, others = {}) {
trace("RequestPolyfill.constructor");
this.method = method;
this.url = url;
Object.assign(this, others);
return this;
}
const ResponsePolyfill = function () {
trace("ResponsePolyfill.constructor");
this.output = { status: 200, headers: {}, data: "", json: true };
this.response_promise = new Promise((ok, fail) => {
this.solve_response = ok;
this.fail_response = fail;
}).then(finalResponse => {
if (finalResponse.status < 300 && finalResponse.status >= 200) {
return finalResponse;
}
throw finalResponse;
});
this.writeHead = (statusCode, headers = {}) => {
trace("ResponsePolyfill.prototype.writeHead");
this.output.status = statusCode;
Object.assign(this.output.headers, headers);
return this;
};
this.write = (contents) => {
trace("ResponsePolyfill.prototype.write");
this.output.data += contents;
return this;
};
this.end = (contents = "") => {
trace("ResponsePolyfill.prototype.end");
this.output.data += contents;
if (this.output.json === true) {
try {
this.output.data = JSON.parse(this.output.data);
} catch (error) {
}
}
if (this.output.status < 300 && this.output.status >= 200) {
this.output.statusText = "OK";
} else {
this.output.statusText = "Erroneous";
this.output.name = this.output.data.error.name;
this.output.message = this.output.data.error.message;
this.output.stack = this.output.data.error.stack;
}
this.output.response = Object.assign({}, this.output);
return this.solve_response(this.output);
};
return this;
}
DataServer.prototype.dispatch = function (request, response, fallback = RestUtils.basicControllerFallback) {
trace("DataServer.prototype.dispatch");
try {
const path = RestUtils.require("path");
const url = RestUtils.require("url");
const parsedUrl = url.parse(request.url);
if (parsedUrl.pathname.startsWith(this.basePathForData)) {
for (let index = 0; index < this.services.length; index++) {
const service = this.services[index];
const serviceUrl = path.join(this.basePathForData, service.path) + "/";
if (parsedUrl.pathname.startsWith(serviceUrl)) {
trace("Dispatching by data service on: " + parsedUrl.pathname);
const serviceInstance = service.create({
server: this
});
return serviceInstance.dispatch(request, response);
}
}
} else if (parsedUrl.pathname.startsWith(this.basePathForAuth)) {
trace("Dispatching by auth service on: " + parsedUrl.pathname);
return this.auth.dispatch(request, response, fallback);
} else if (parsedUrl.pathname.startsWith(this.basePathForQuery)) {
trace("Dispatching by query service on: " + parsedUrl.pathname);
const queryId = "/" + parsedUrl.pathname.replace(this.basePathForQuery, "").split("/").filter(it => it !== "").join("/");
const matchedServices = this.queries.filter(x => x.path === queryId);
if (matchedServices.length === 0) {
throw new Error("Required parameter «queryId» to be a known query in order to «DataServer.prototype.dispatch» (passed: «" + queryId + "») (available: «" + this.queries.map(x => x.path).join("» «") + "»)");
}
const [queryServiceClass] = matchedServices;
const queryService = queryServiceClass.create({ server: this });
return queryService.dispatch(request, response, fallback);
} else if (parsedUrl.pathname.startsWith(this.basePathForProcess)) {
trace("Dispatching by process service on: " + parsedUrl.pathname);
const processId = "/" + parsedUrl.pathname.replace(this.basePathForProcess, "").split("/").filter(it => it !== "").join("/");
const matchedServices = this.processes.filter(x => x.path === processId);
if (matchedServices.length === 0) {
throw new Error("Required parameter «processId» to be a known process in order to «DataServer.prototype.dispatch» (passed: «" + processId + "») (available: «" + this.processes.map(x => x.path).join("» «") + "»)");
}
const [processServiceClass] = matchedServices;
const processService = processServiceClass.create({ server: this });
return processService.dispatch(request, response, fallback);
}
trace("Dispatching by fallback on: " + serviceUrl);
return fallback(request, response);
} catch (error) {
return this.onDispatchError(error, request, response);
}
};
DataServer.prototype.createDispatcher = function (fallback = RestUtils.basicControllerFallback) {
trace("DataServer.prototype.createDispatcher");
return (request, response) => this.dispatch(request, response, fallback);
};
DataServer.prototype.createHttpServerController = function () {
trace("DataServer.prototype.createHttpServerController");
const dispatcher = this.createDispatcher();
return (request, response) => dispatcher(request, response);
};
DataServer.prototype.createHttpServer = function (fallback = RestUtils.basicControllerFallback) {
trace("DataServer.prototype.createHttpServer");
this.httpServer = RestUtils.require("http").createServer(this.createHttpServerController());
return this.httpServer;
};
DataServer.prototype.listen = function (options) {
trace("DataServer.prototype.listen");
return new Promise((ok, fail) => {
const httpServer = this.httpServer || this.createHttpServer();
try {
httpServer.listen(options, () => {
return ok(httpServer);
});
} catch (error) {
return fail(error);
}
});
};
DataServer.prototype.stopDatabaseConnection = function () {
trace("DataServer.prototype.stopDatabaseConnection");
return this.rest.connection.end();
};
DataServer.prototype.stopHttpServer = function () {
trace("DataServer.prototype.stopHttpServer");
return this.httpServer.close();
};
DataServer.prototype.resetDatabase = function () {
trace("DataServer.prototype.resetDatabase");
return this.rest.resetDatabase();
};
DataServer.prototype.resetAuth = function () {
trace("DataServer.prototype.resetAuth");
return this.auth.resetAuth();
};
DataServer.prototype.dispatchSelf = function (method = "get", url = "/", requestArgs = {}, responseArgs = {}) {
throw new Error("Required method «dispatchSelf» to be overriden");
};
DataServer.prototype.createClient = function (baseUrl = undefined) {
trace("DataServer.prototype.createClient");
if (typeof baseUrl !== "string") {
throw new Error("Required argument «baseUrl» to be a string in order to «createClient»");
}
return new RestClient(baseUrl, { server: this });
};
DataServer.prototype.initialize = async function () {
try {
trace("DataServer.prototype.initialize");
await this.initializeRest();
await this.initializeAuth();
return this;
} catch (error) {
this.onError(error);
}
};
DataServer.prototype.initializeRest = async function () {
try {
trace("DataServer.prototype.initializeRest");
let restAdapter = undefined;
if (typeof this.adapter !== "string") {
this.adapter = "mysql";
}
// @TOCONTINUE: continue adding other REST adapters on the following conditional:
if (this.adapter === "mysql") {
if (typeof this.credentials !== "object") {
throw new Error("Required parameter «this.credentials» to be an object in order to «initalizeRest» (on 'mysql' REST adapter)");
}
restAdapter = new RestByMySQL({
credentials: this.credentials,
}, {
...this.restExtension,
server: this,
});
} else {
throw new Error("Required configuration «this.adapter» to be a valid option in order to «initializeRest»");
}
// @OK!
this.rest = await restAdapter.initialize();
} catch (error) {
this.onError(error);
}
};
DataServer.prototype.initializeAuth = async function () {
try {
trace("DataServer.prototype.initializeAuth");
let authAdapter = undefined;
if (typeof this.adapter !== "string") {
this.adapter = "mysql";
}
// @TOCONTINUE: continue adding other AUTH adapters on the following conditional:
if (this.adapter === "mysql") {
if (typeof this.credentials !== "object") {
throw new Error("Required parameter «this.credentials» to be an object in order to «initializeAuth» (on 'mysql' REST adapter)");
}
authAdapter = new AuthByMySQL({
credentials: this.credentials,
}, {
...this.authExtension,
server: this,
});
} else {
throw new Error("Required parameter «adapter» to be a valid option in order to «initializeRest»");
}
// @OK!
this.auth = await authAdapter.initialize();
} catch (error) {
this.onError(error);
}
};
////////////////////////////////////////////////////////////////////////
// 5. DataService class:
const DataService = function (dynamicInterface = {}) {
trace("DataService.constructor");
Object.assign(this, dynamicInterface);
return this;
};
DataService.create = function (...args) {
trace("DataService.create");
return new this(...args);
};
DataService.initialize = function (...args) {
trace("DataService.initialize");
return (new this(...args)).initialize();
};
DataService.path = "/customize/path/here";
DataService.prototype.initialize = async function () {
try {
trace("DataService.prototype.initialize");
return this;
} catch (error) {
this.onError(error);
}
};
DataService.prototype.generateContext = RestUtils.generateContextByRequestResponseFactory("DataService.prototype.generateContext");
DataService.prototype.dispatch = function (request, response) {
trace("DataService.prototype.dispatch");
const parsedUrl = RestUtils.require("url").parse(request.url);
if (parsedUrl.pathname.startsWith(this.server.basePathForData)) {
const actionPath = parsedUrl.pathname.replace(this.server.basePathForData, "").replace(this.constructor.path, "");
if (false) {
return false;
} else if (actionPath === "/define") {
return this.dispatchDefine(request, response);
} else if (actionPath === "/select/one") {
return this.dispatchSelectOne(request, response);
} else if (actionPath === "/select/many") {
return this.dispatchSelectMany(request, response);
} else if (actionPath === "/insert/one") {
return this.dispatchInsertOne(request, response);
} else if (actionPath === "/insert/many") {
return this.dispatchInsertMany(request, response);
} else if (actionPath === "/update/one") {
return this.dispatchUpdateOne(request, response);
} else if (actionPath === "/update/many") {
return this.dispatchUpdateMany(request, response);
} else if (actionPath === "/delete/one") {
return this.dispatchDeleteOne(request, response);
} else if (actionPath === "/delete/many") {
return this.dispatchDeleteMany(request, response);
} else if (actionPath === "/get/file") {
return this.dispatchGetFile(request, response);
} else if (actionPath === "/set/file") {
return this.dispatchSetFile(request, response);
} else {
return this.onDispatchError(new Error("Required action path to be valid in order to «dispatch» (passed: «" + actionPath + "»)"), request, response);
}
} else {
return this.onDispatchError(new Error("Required url path to be valid in order to «dispatch» (passed: «" + parsedUrl.pathname + "»)"), request, response);
}
};
DataService.prototype.dispatchDefine = async function (request, response) {
try {
trace("DataService.prototype.dispatchDefine");
const context = this.generateContext(request, response);
await this.onDefine(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchSelectOne = async function (request, response) {
try {
trace("DataService.prototype.dispatchSelectOne");
const context = this.generateContext(request, response);
await this.onFormatParametersForSelectOne(context);
await this.onQueryForSelectOne(context);
await this.onFormatOutputForSelectOne(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchSelectMany = async function (request, response) {
try {
trace("DataService.prototype.dispatchSelectMany");
const context = this.generateContext(request, response);
await this.onFormatParametersForSelectMany(context);
await this.onQueryForSelectMany(context);
await this.onFormatOutputForSelectMany(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchInsertOne = async function (request, response) {
try {
trace("DataService.prototype.dispatchInsertOne");
const context = this.generateContext(request, response);
await this.onFormatParametersForInsertOne(context);
await this.onQueryForInsertOne(context);
await this.onFormatOutputForInsertOne(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchInsertMany = async function (request, response) {
try {
trace("DataService.prototype.dispatchInsertMany");
const context = this.generateContext(request, response);
await this.onFormatParametersForInsertMany(context);
await this.onQueryForInsertMany(context);
await this.onFormatOutputForInsertMany(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchUpdateOne = async function (request, response) {
try {
trace("DataService.prototype.dispatchUpdateOne");
const context = this.generateContext(request, response);
await this.onFormatParametersForUpdateOne(context);
await this.onQueryForUpdateOne(context);
await this.onFormatOutputForUpdateOne(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchUpdateMany = async function (request, response) {
try {
trace("DataService.prototype.dispatchUpdateMany");
const context = this.generateContext(request, response);
await this.onFormatParametersForUpdateMany(context);
await this.onQueryForUpdateMany(context);
await this.onFormatOutputForUpdateMany(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchDeleteOne = async function (request, response) {
try {
trace("DataService.prototype.dispatchDeleteOne");
const context = this.generateContext(request, response);
await this.onFormatParametersForDeleteOne(context);
await this.onQueryForDeleteOne(context);
await this.onFormatOutputForDeleteOne(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchDeleteMany = async function (request, response) {
try {
trace("DataService.prototype.dispatchDeleteMany");
const context = this.generateContext(request, response);
await this.onFormatParametersForDeleteMany(context);
await this.onQueryForDeleteMany(context);
await this.onFormatOutputForDeleteMany(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchGetFile = async function (request, response) {
try {
trace("DataService.prototype.dispatchGetFile");
const context = this.generateContext(request, response);
await this.onFormatParametersForGetFile(context);
await this.onQueryForGetFile(context);
await this.onServeFile(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
DataService.prototype.dispatchSetFile = async function (request, response) {
try {
trace("DataService.prototype.dispatchSetFile");
const context = this.generateContext(request, response);
await this.onFormatParametersForSetFile(context);
await this.onQueryForSetFile(context);
await this.onPersistFile(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
//////////////////////////////////////////////////////
// (01) Service for SELECT ONE:
DataService.prototype.onFormatParametersForSelectOne = async function (context) {
trace("DataService.prototype.onFormatParametersForSelectOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
return true;
};
DataService.prototype.onQueryForSelectOne = function (context) {
trace("DataService.prototype.onQueryForSelectOne");
return this.server.rest.selectOne(context.parameters.table, {
where: context.parameters.where
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForSelectOne = async function (context) {
trace("DataService.prototype.onFormatOutputForSelectOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/select/one",
model: this.constructor.table,
action: "/select/one",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (02) Service for SELECT MANY:
DataService.prototype.onFormatParametersForSelectMany = async function (context) {
trace("DataService.prototype.onFormatParametersForSelectMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
context.parameters.order = RestUtils.formatOrderFromRequest(context);
context.parameters.group = RestUtils.formatGroupFromRequest(context);
context.parameters.pagination = RestUtils.formatPaginationFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForSelectMany = function (context) {
trace("DataService.prototype.onQueryForSelectMany");
return this.server.rest.selectMany(context.parameters.table, {
where: context.parameters.where,
order: context.parameters.order,
group: context.parameters.group,
pagination: context.parameters.pagination,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForSelectMany = async function (context) {
trace("DataService.prototype.onFormatOutputForSelectMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/select/many",
model: this.constructor.table,
action: "/select/many",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (03) Service for INSERT ONE:
DataService.prototype.onFormatParametersForInsertOne = async function (context) {
trace("DataService.prototype.onFormatParametersForInsertOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.item = RestUtils.formatItemFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForInsertOne = function (context) {
trace("DataService.prototype.onQueryForInsertOne");
return this.server.rest.insertOne(context.parameters.table, {
item: context.parameters.item,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForInsertOne = async function (context) {
trace("DataService.prototype.onFormatOutputForInsertOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/insert/one",
model: this.constructor.table,
action: "/insert/one",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (04) Service for INSERT MANY:
DataService.prototype.onFormatParametersForInsertMany = async function (context) {
trace("DataService.prototype.onFormatParametersForInsertMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
console.log(context);
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.items = RestUtils.formatItemsFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForInsertMany = function (context) {
trace("DataService.prototype.onQueryForInsertMany");
return this.server.rest.insertMany(context.parameters.table, {
items: context.parameters.items,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForInsertMany = async function (context) {
trace("DataService.prototype.onFormatOutputForInsertMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/insert/many",
model: this.constructor.table,
action: "/insert/many",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (05) Service for UPDATE ONE:
DataService.prototype.onFormatParametersForUpdateOne = async function (context) {
trace("DataService.prototype.onFormatParametersForUpdateOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
context.parameters.values = RestUtils.formatValuesFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForUpdateOne = function (context) {
trace("DataService.prototype.onQueryForUpdateOne");
return this.server.rest.updateOne(context.parameters.table, {
where: context.parameters.where,
values: context.parameters.values,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForUpdateOne = async function (context) {
trace("DataService.prototype.onFormatOutputForUpdateOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/update/one",
model: this.constructor.table,
action: "/update/one",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (06) Service for UPDATE MANY:
DataService.prototype.onFormatParametersForUpdateMany = async function (context) {
trace("DataService.prototype.onFormatParametersForUpdateMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
context.parameters.values = RestUtils.formatValuesFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForUpdateMany = function (context) {
trace("DataService.prototype.onQueryForUpdateMany");
return this.server.rest.updateMany(context.parameters.table, {
where: context.parameters.where,
values: context.parameters.values,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForUpdateMany = async function (context) {
trace("DataService.prototype.onFormatOutputForUpdateMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/update/many",
model: this.constructor.table,
action: "/update/many",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (07) Service for DELETE ONE:
DataService.prototype.onFormatParametersForDeleteOne = async function (context) {
trace("DataService.prototype.onFormatParametersForDeleteOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForDeleteOne = function (context) {
trace("DataService.prototype.onQueryForDeleteOne");
return this.server.rest.deleteOne(context.parameters.table, {
where: context.parameters.where,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForDeleteOne = async function (context) {
trace("DataService.prototype.onFormatOutputForDeleteOne");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/delete/one",
model: this.constructor.table,
action: "/delete/one",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (08) Service for DELETE MANY:
DataService.prototype.onFormatParametersForDeleteMany = async function (context) {
trace("DataService.prototype.onFormatParametersForDeleteMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::before", { context });
context.parameters.table = this.constructor.table;
context.parameters.path = this.constructor.path;
context.parameters.where = RestUtils.formatWhereFromRequest(context);
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatParameters::after", { context });
};
DataService.prototype.onQueryForDeleteMany = function (context) {
trace("DataService.prototype.onQueryForDeleteMany");
return this.server.rest.deleteMany(context.parameters.table, {
where: context.parameters.where,
}).then(data => {
context.state.queryResults = data;
return data;
});
};
DataService.prototype.onFormatOutputForDeleteMany = async function (context) {
trace("DataService.prototype.onFormatOutputForDeleteMany");
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::before", { context });
context.output = {
data: context.state.queryResults,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/delete/many",
model: this.constructor.table,
action: "/delete/many",
}
};
await this.server.hooks.useHook("service://" + context.input.url.replace(/^\//g, "") + "@onFormatOutput::after", { context });
};
//////////////////////////////////////////////////////
// (09) Service for GET FILE:
DataService.prototype.onFormatParametersForGetFile = function (context) {
trace("DataService.prototype.onFormatParametersForGetFile");
};
DataService.prototype.onQueryForGetFile = function (context) {
trace("DataService.prototype.onQueryForGetFile");
};
DataService.prototype.onServeFile = function (context) {
trace("DataService.prototype.onServeFile");
throw new Error("Required «DataService.prototype.onServeFile» to be overriden");
};
//////////////////////////////////////////////////////
// (10) Service for SET FILE:
DataService.prototype.onFormatParametersForSetFile = function (context) {
trace("DataService.prototype.onFormatParametersForSetFile");
};
DataService.prototype.onQueryForSetFile = function (context) {
trace("DataService.prototype.onQueryForSetFile");
};
DataService.prototype.onPersistFile = function (context) {
trace("DataService.prototype.onPersistFile");
throw new Error("Required «DataService.prototype.onPersistFile» to be overriden");
};
DataService.prototype.onRespond = function (context) {
trace("DataService.prototype.onRespond");
return RestUtils.respondContext(context);
};
DataService.prototype.onDefine = function (context) {
trace("DataService.prototype.onDefine");
const publicFieldIds = this.constructor.publicFields || ["id", "path", "table", "class", "schema"];
const data = {};
for (let index = 0; index < publicFieldIds.length; index++) {
const publicFieldId = publicFieldIds[index];
data[publicFieldId] = this.constructor[publicFieldId];
}
context.output = {
data,
metadata: {
path: this.server.basePathForData + this.constructor.path + "/define",
model: this.constructor.table,
action: "/define",
}
};
};
DataService.prototype.setServer = function (server) {
trace("DataService.prototype.setServer");
this.server = server;
return this;
};
const QueryService = function (dynamicInterface = {}) {
trace("QueryService.constructor");
Object.assign(this, dynamicInterface);
return this;
};
QueryService.create = function (...args) {
return new this(...args);
};
QueryService.prototype = { ...DataService.prototype };
QueryService.prototype.getParametersByURL = function (url) {
trace("QueryService.prototype.getParametersByURL");
const parsedUrl = RestUtils.require("url").parse(url);
const urlStarter = RestUtils.require("path").join(this.server.basePathForQuery, this.constructor.path);
const extraPath = parsedUrl.pathname.replace(urlStarter, "");
return extraPath;
};
QueryService.prototype.serve = function (status, headers, body, response) {
trace("QueryService.prototype.serve");
const responseHeaders = Object.assign({ "Content-type": "application/json" }, headers);
response.writeHead(status, responseHeaders);
response.write(typeof body === "string" ? body : JSON.stringify(body));
return response.end();
};
QueryService.prototype.onDispatchQuery = function (request, response, fallback) {
trace("QueryService.prototype.onDispatchQuery");
return this.constructor.query.call(this, request, response, fallback);
};
QueryService.prototype.dispatch = function (request, response, fallback = RestUtils.noop) {
trace("QueryService.prototype.dispatch");
const parsedUrl = RestUtils.require("url").parse(request.url);
const urlStarter = RestUtils.require("path").join(this.server.basePathForQuery, this.constructor.path);
if (parsedUrl.pathname.startsWith(urlStarter)) {
return this.onDispatchQuery(request, response, fallback);
} else {
return this.onDispatchError(new Error("Required url path to be valid in order to «QueryService.prototype.dispatch» (passed: «" + parsedUrl.pathname + "») (valid: «" + urlStarter + "»)"), request, response);
}
};
const ProcessService = function (dynamicInterface = {}) {
trace("ProcessService.constructor");
Object.assign(this, dynamicInterface);
return this;
};
ProcessService.create = function (...args) {
return new this(...args);
};
ProcessService.prototype = { ...DataService.prototype };
ProcessService.prototype.getParametersByURL = function (url) {
trace("ProcessService.prototype.getParametersByURL");
const parsedUrl = RestUtils.require("url").parse(url);
const urlStarter = RestUtils.require("path").join(this.server.basePathForQuery, this.constructor.path);
const extraPath = parsedUrl.pathname.replace(urlStarter, "");
return extraPath;
};
ProcessService.prototype.serve = function (status, headers, body, response) {
trace("ProcessService.prototype.serve");
const responseHeaders = Object.assign({ "Content-type": "application/json" }, headers);
response.writeHead(status, responseHeaders);
response.write(typeof body === "string" ? body : JSON.stringify(body));
return response.end();
};
ProcessService.prototype.onDispatchProcess = function (request, response, fallback) {
trace("ProcessService.prototype.onDispatchProcess");
return this.constructor.process.call(this, request, response, fallback);
const parsedUrl = RestUtils.require("url").parse(request.url);
const urlStarter = RestUtils.require("path").join(this.server.basePathForProcess, this.constructor.path);
const extraPath = parsedUrl.pathname.replace(urlStarter, "");
response.writeHead(200, { "Content-Type": "application/json" });
response.write(JSON.stringify({
process: urlStarter,
subroute: extraPath
}));
return response.end();
};
ProcessService.prototype.dispatch = function (request, response, fallback = RestUtils.noop) {
trace("ProcessService.prototype.dispatch");
const parsedUrl = RestUtils.require("url").parse(request.url);
const urlStarter = RestUtils.require("path").join(this.server.basePathForProcess, this.constructor.path);
if (parsedUrl.pathname.startsWith(urlStarter)) {
return this.onDispatchProcess(request, response, fallback);
} else {
return this.onDispatchError(new Error("Required url path to be valid in order to «ProcessService.prototype.dispatch» (passed: «" + parsedUrl.pathname + "») (valid: «" + urlStarter + "»)"), request, response);
}
};
////////////////////////////////////////////////////////////////////////
// 7. RestByMySQL class:
const RestByMySQL = function (options, extensions = {}) {
trace("RestByMySQL.constructor");
if (typeof options !== "object") {
throw new Error("Required parameter «options» to be an object in order to «RestByMySQL.constructor»");
}
if (typeof options.credentials !== "object") {
throw new Error("Required parameter «options.credentials» to be an object in order to «RestByMySQL.constructor»");
}
if (typeof extensions !== "object") {
throw new Error("Required parameter «extensions» to be an object in order to «RestByMySQL.constructor»");
}
this.credentials = options.credentials;
Object.assign(this, extensions);
return this;
};
Object.assign(RestByMySQL.prototype, { ...RestInterface.prototype });
RestByMySQL.prototype.initialize = async function () {
try {
trace("RestByMySQL.prototype.initialize");
this.connection = await RestUtils.require("mysql2/promise").createConnection(this.credentials);
this.connection = RestUtils.expandConnection(this.connection);
await this.connection.ping();
return this;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.selectMany = async function (dataType, { where = [], order = [], groups = [], pagination = [1, 20] }, authentication) {
try {
trace("RestByMySQL.prototype.selectMany");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const sanitizedGroup = RestUtils.fromGroupToSQL(groups);
const sanitizedOrder = RestUtils.fromOrderToSQL(order);
const sanitizedPagination = RestUtils.fromPaginationToSQL(pagination);
const query = [
`# Select many query:`,
`SELECT * `,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
sanitizedGroup,
sanitizedOrder,
sanitizedPagination,
].join("\n");
const resultsReport = await this.connection.proxifiedQuery(query);
const [results] = resultsReport;
const context = { dataType, where, order, groups, pagination, authentication, query, results };
await this.server.hooks.useHook("api://rest.selectMany::after", { context });
await this.server.hooks.useHook("api://rest.selectMany:" + dataType + "::after", { context });
return results;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.selectOne = async function (dataType, { where = [] }, authentication) {
try {
trace("RestByMySQL.prototype.selectOne");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const query = [
`# Select one query:`,
`SELECT * `,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const resultsReport = await this.connection.proxifiedQuery(query);
const [results] = resultsReport;
if (results.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.selectOne»");
} else if (results.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.selectOne»");
}
const context = { dataType, where, authentication, query, results };
await this.server.hooks.useHook("api://rest.selectOne::after", { context });
await this.server.hooks.useHook("api://rest.selectOne:" + dataType + "::after", { context });
return results[0];
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.insertMany = async function (dataType, { items }, authentication) {
try {
trace("RestByMySQL.prototype.insertMany");
const sanitizedTable = dataType;
const sanitizedKeys = RestUtils.fromItemsToKeysSQL(items);
const sanitizedValues = RestUtils.fromItemsToValuesSQL(items);
const query = [
`# Insert many query:`,
`INSERT `,
` INTO ${sanitizedTable} ${sanitizedKeys}`,
` VALUES ${sanitizedValues}`,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
firstId: unsanitizedReport.insertId,
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, items, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.insertMany::after", { context });
await this.server.hooks.useHook("api://rest.insertMany:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.insertOne = async function (dataType, { item }, authentication) {
try {
trace("RestByMySQL.prototype.insertOne");
const sanitizedTable = dataType;
const sanitizedKeys = RestUtils.fromItemToKeysSQL(item);
const sanitizedValues = RestUtils.fromItemToValuesSQL(item);
const query = [
`# Insert one query:`,
`INSERT `,
` INTO ${sanitizedTable} ${sanitizedKeys}`,
` VALUES ${sanitizedValues}`,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
id: unsanitizedReport.insertId,
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, item, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.insertOne::after", { context });
await this.server.hooks.useHook("api://rest.insertOne:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.updateMany = async function (dataType, { where, values }, authentication) {
try {
trace("RestByMySQL.prototype.updateMany");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const sanitizedSettables = RestUtils.fromItemToSettablesSQL(values);
const query = [
`# Update many query:`,
`UPDATE ${sanitizedTable}`,
` SET ${sanitizedSettables}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, where, values, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.updateMany::after", { context });
await this.server.hooks.useHook("api://rest.updateMany:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.updateOne = async function (dataType, { where, values }, authentication) {
try {
trace("RestByMySQL.prototype.updateOne");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const sanitizedSettables = RestUtils.fromItemToSettablesSQL(values);
const querySelectOne = [
`# Select one query (in order to update one):`,
`SELECT * `,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const [selectionReport] = await this.connection.proxifiedQuery(querySelectOne);
if (selectionReport.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.updateOne»");
} else if (selectionReport.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.updateOne»");
}
const query = [
`# Update one query:`,
`UPDATE ${sanitizedTable}`,
` SET ${sanitizedSettables}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, where, values, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.updateOne::after", { context });
await this.server.hooks.useHook("api://rest.updateOne:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.deleteMany = async function (dataType, { where }, authentication) {
try {
trace("RestByMySQL.prototype.deleteMany");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const query = [
`# Delete many query:`,
`DELETE`,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, where, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.deleteMany::after", { context });
await this.server.hooks.useHook("api://rest.deleteMany:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.deleteOne = async function (dataType, { where }, authentication) {
try {
trace("RestByMySQL.prototype.deleteOne");
const sanitizedTable = dataType;
const sanitizedWhere = RestUtils.fromWhereToSQL(where);
const querySelectOne = [
`# Select one query (in order to delete one):`,
`SELECT * `,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const [selectionReport] = await this.connection.proxifiedQuery(querySelectOne);
if (selectionReport.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.deleteOne»");
} else if (selectionReport.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByMySQL.prototype.deleteOne»");
}
const query = [
`# Delete one query:`,
`DELETE`,
` FROM ${sanitizedTable}`,
` WHERE 1 = 1`,
sanitizedWhere,
].join("\n");
const results = await this.connection.proxifiedQuery(query);
const [unsanitizedReport] = results;
const sanitizedReport = {
rows: unsanitizedReport.affectedRows,
};
const context = { dataType, where, authentication, query, results, sanitizedReport };
await this.server.hooks.useHook("api://rest.deleteOne::after", { context });
await this.server.hooks.useHook("api://rest.deleteOne:" + dataType + "::after", { context });
return sanitizedReport;
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.getFile = async function (dataType, { id, column }, authentication) {
try {
trace("RestByMySQL.prototype.getFile");
// @TODO...
// @TODO...
// @TODO...
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.setFile = async function (dataType, { id, column, file }, authentication) {
try {
trace("RestByMySQL.prototype.setFile");
// @TODO...
// @TODO...
// @TODO...
} catch (error) {
this.onError(error);
}
};
RestByMySQL.prototype.resetDatabase = async function (authentication) {
try {
trace("RestByMySQL.prototype.resetDatabase");
await this.connection.proxifiedQuery([
`DROP DATABASE IF EXISTS ${this.credentials.database};`
].join("\n"));
await this.connection.proxifiedQuery([
`CREATE DATABASE ${this.credentials.database};`
].join("\n"));
await this.connection.proxifiedQuery([
`USE ${this.credentials.database};`
].join("\n"));
if (this.server.auth && this.server.auth.resetAuth) {
await this.server.auth.resetAuth();
}
const allServices = this.server.services;
for (let indexService = 0; indexService < allServices.length; indexService++) {
const serviceClass = allServices[indexService];
await (async (serviceClass) => {
if (typeof serviceClass.creationScript === "string") {
await this.connection.proxifiedQuery(serviceClass.creationScript);
}
})(serviceClass);
}
if (typeof this.seeder === "function") {
await this.seeder(authentication);
}
} catch (error) {
this.onError(error);
}
};
////////////////////////////////////////////////////////////////////////
// 10. AuthByMySQL class:
const AuthByMySQL = function (options, extensions = {}) {
trace("AuthByMySQL.constructor");
if (typeof options !== "object") {
throw new Error("Required parameter «options» to be an object in order to «AuthByMySQL.constructor»");
}
if (typeof options.credentials !== "object") {
throw new Error("Required parameter «options.credentials» to be an object in order to «AuthByMySQL.constructor»");
}
if (typeof extensions !== "object") {
throw new Error("Required parameter «extensions» to be an object in order to «AuthByMySQL.constructor»");
}
this.credentials = options.credentials;
Object.assign(this, extensions);
return this;
};
Object.assign(AuthByMySQL.prototype, { ...AuthInterface });
AuthByMySQL.prototype.initialize = async function () {
try {
trace("AuthByMySQL.prototype.initialize");
// @TODO...
// @TODO...
// @TODO...
return this;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onRespond = function (context) {
trace("AuthByMySQL.prototype.onRespond");
return RestUtils.respondContext(context);
};
AuthByMySQL.prototype.dispatch = async function (request, response, fallback = RestUtils.basicControllerFallback) {
trace("AuthByMySQL.prototype.dispatch");
const parsedUrl = RestUtils.require("url").parse(request.url);
if (parsedUrl.pathname.startsWith(this.server.basePathForAuth)) {
const actionPath = parsedUrl.pathname.replace(this.server.basePathForAuth, "").replace(this.constructor.path, "");
if (false) {
return false;
} else if (actionPath === "/register") {
return this.dispatchRegister(request, response);
} else if (actionPath === "/confirm") {
return this.dispatchConfirm(request, response);
} else if (actionPath === "/login") {
return this.dispatchLogin(request, response);
} else if (actionPath === "/logout") {
return this.dispatchLogout(request, response);
} else if (actionPath === "/forgot") {
return this.dispatchForgot(request, response);
} else if (actionPath === "/recover") {
return this.dispatchRecover(request, response);
} else if (actionPath === "/unregister") {
return this.dispatchUnregister(request, response);
} else if (actionPath === "/modify") {
return this.dispatchModify(request, response);
} else {
return this.onDispatchError(new Error("Required action path to be valid (and «" + actionPath + "» is not valid as auth service) in order to «dispatch»"), request, response);
}
}
return fallback(request, response);
};
AuthByMySQL.prototype.generateContext = RestUtils.generateContextByRequestResponseFactory("AuthByMySQL.prototype.generateContext");
AuthByMySQL.prototype.authenticate = async function (token) {
try {
trace("AuthByMySQL.prototype.authenticate");
const sanitizedToken = RestUtils.sanitize(token);
const [matchedSessions] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_sessions WHERE token = ${sanitizedToken};`
].join("\n"));
if (matchedSessions.length === 0) {
throw new Error("Required parameter «session_token» to be session a session token in order to «authenticate»");
} else if (matchedSessions.length !== 1) {
throw new Error("Data corrupted by duplication of session token");
}
const [matchedSession] = matchedSessions;
const sanitizedUserId = RestUtils.sanitize(matchedSession.id_user);
const [matchedUsers] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE id = ${sanitizedUserId};`
].join("\n"));
if (matchedUsers.length === 0) {
throw new Error("Required parameter «session_token» to be session a session token in order to «authenticate»");
} else if (matchedUsers.length !== 1) {
throw new Error("Data corrupted by duplication of session token");
}
const [matchedUser] = matchedUsers;
let matchedGroups = undefined;
let matchedPrivileges = undefined;
const [matchedGroups1] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_groups WHERE auth_groups.id IN (SELECT DISTINCT id_group FROM auth_groups_of_users WHERE auth_groups_of_users.id_user IN (${sanitizedUserId}));`
].join("\n"));
matchedGroups = matchedGroups1;
if (matchedGroups.length) {
const sanitizedGroupIds = matchedGroups.map(item => RestUtils.sanitize(item.id)).join(", ");
const [matchedPrivileges1] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_privileges WHERE auth_privileges.id IN (SELECT DISTINCT id_privilege FROM auth_privileges_of_groups WHERE auth_privileges_of_groups.id_group IN (${sanitizedGroupIds}));`
].join("\n"));
matchedPrivileges = matchedPrivileges1;
}
return {
session: matchedSession,
user: matchedUser,
groups: matchedGroups,
privileges: matchedPrivileges,
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.dispatchRegister = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchRegister");
const context = this.generateContext(request, response);
await this.onFormatParametersForRegister(context);
context.state.operationResults = await this.onRegister(context);
await this.onFormatOutputForRegister(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchConfirm = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchConfirm");
const context = this.generateContext(request, response);
await this.onFormatParametersForConfirm(context);
context.state.operationResults = await this.onConfirm(context);
await this.onFormatOutputForConfirm(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchLogin = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchLogin");
const context = this.generateContext(request, response);
await this.onFormatParametersForLogin(context);
context.state.operationResults = await this.onLogin(context);
await this.onFormatOutputForLogin(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchLogout = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchLogout");
const context = this.generateContext(request, response);
await this.onFormatParametersForLogout(context);
context.state.operationResults = await this.onLogout(context);
await this.onFormatOutputForLogout(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchForgot = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchForgot");
const context = this.generateContext(request, response);
await this.onFormatParametersForForgot(context);
context.state.operationResults = await this.onForgot(context);
await this.onFormatOutputForForgot(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchRecover = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchRecover");
const context = this.generateContext(request, response);
await this.onFormatParametersForRecover(context);
context.state.operationResults = await this.onRecover(context);
await this.onFormatOutputForRecover(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchUnregister = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchUnregister");
const context = this.generateContext(request, response);
await this.onFormatParametersForUnregister(context);
context.state.operationResults = await this.onUnregister(context);
await this.onFormatOutputForUnregister(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.dispatchModify = async function (request, response) {
try {
trace("AuthByMySQL.prototype.dispatchModify");
const context = this.generateContext(request, response);
await this.onFormatParametersForModify(context);
context.state.operationResults = await this.onModify(context);
await this.onFormatOutputForModify(context);
await this.onRespond(context);
} catch (error) {
this.onDispatchError(error, request, response);
}
};
AuthByMySQL.prototype.onRegister = async function (context) {
try {
trace("AuthByMySQL.prototype.onRegister");
return await this.register(context.parameters.user, context.parameters.password, context.parameters.email);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onConfirm = async function (context) {
try {
trace("AuthByMySQL.prototype.onConfirm");
return await this.confirm(context.parameters.confirmationToken);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onLogin = async function (context) {
try {
trace("AuthByMySQL.prototype.onLogin");
return await this.login(context.parameters.user, context.parameters.password);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onLogout = async function (context) {
try {
trace("AuthByMySQL.prototype.onLogout");
return await this.logout(context.parameters.session_token);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onForgot = async function (context) {
try {
trace("AuthByMySQL.prototype.onForgot");
return await this.forgot(context.parameters.user);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onRecover = async function (context) {
try {
trace("AuthByMySQL.prototype.onRecover");
return await this.recover(context.parameters.recovery_token);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onUnregister = async function (context) {
try {
trace("AuthByMySQL.prototype.onUnregister");
return await this.unregister(context.parameters.session_token, context.parameters.user, context.parameters.password);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onModify = async function (context) {
try {
trace("AuthByMySQL.prototype.onModify");
return await this.modify(context.parameters.session_token, context.parameters.user, context.parameters.password);
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForRegister = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForRegister");
context.parameters.user = context.input.query.user;
context.parameters.password = context.input.query.password;
context.parameters.email = context.input.query.email;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForRegister = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForRegister");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/register",
action: "/register",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForConfirm = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForConfirm");
context.parameters.confirmationToken = context.input.query.confirmation_token;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForConfirm = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForConfirm");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/confirm",
action: "/confirm",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForLogin = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForLogin");
context.parameters.user = context.input.query.user;
context.parameters.password = context.input.query.password;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForLogin = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForLogin");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/login",
action: "/login",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForLogout = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForLogout");
context.parameters.session_token = context.input.query.session_token;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForLogout = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForLogout");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/logout",
action: "/logout",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForForgot = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForForgot");
context.parameters.user = context.input.query.user;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForForgot = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForForgot");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/forgot",
action: "/forgot",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForRecover = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForRecover");
context.parameters.recovery_token = context.input.query.recovery_token;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForRecover = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForRecover");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/recover",
action: "/recover",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForUnregister = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForUnregister");
context.parameters.user = context.input.query.user;
context.parameters.password = context.input.query.password;
context.parameters.session_token = context.input.query.session_token;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForUnregister = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForUnregister");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/unregister",
action: "/unregister",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatParametersForModify = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatParametersForModify");
context.parameters.session_token = context.input.query.session_token;
context.parameters.user = context.input.query.user;
context.parameters.password = context.input.query.password;
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.onFormatOutputForModify = function (context) {
try {
trace("AuthByMySQL.prototype.onFormatOutputForModify");
context.output = {
data: context.state.operationResults,
metadata: {
path: this.server.basePathForAuth + "/modify",
action: "/modify",
}
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.register = async function (user, password, email) {
try {
trace("AuthByMySQL.prototype.register");
if (typeof user !== "string") {
throw new Error("Required parameter «user» to be a «string» in order to «register»");
}
if (typeof password !== "string") {
throw new Error("Required parameter «password» to be a «string» in order to «register»");
}
if (typeof email !== "string") {
throw new Error("Required parameter «email» to be a «string» in order to «register»");
}
const sanitizedUser = RestUtils.sanitize(user);
const sanitizedEmail = RestUtils.sanitize(email);
const [coincidentNames] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE name = ${sanitizedUser};`
].join("\n"));
if (coincidentNames.length) {
throw new Error("Required parameter «name» to be unique in order to «register»");
}
const [coincidentEmails] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE email = ${sanitizedEmail};`
].join("\n"));
if (coincidentEmails.length) {
throw new Error("Required parameter «email» to be unique in order to «register»");
}
const sanitizedPassword = RestUtils.sanitize(password);
const confirmationToken = RestUtils.generateRandomToken(20);
const sanitizedConfirmationToken = RestUtils.sanitize(confirmationToken);
const [{ insertId }] = await this.server.rest.connection.proxifiedQuery([
`INSERT INTO auth_pending_users (name, password, email, confirmation_token) VALUES (${sanitizedUser},${sanitizedPassword},${sanitizedEmail},${sanitizedConfirmationToken});`
].join("\n"));
return {
message: "user successfully registered",
// pending_user_id: insertId,
confirmation_token: confirmationToken,
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.confirm = async function (confirmationToken) {
try {
trace("AuthByMySQL.prototype.confirm");
if (typeof confirmationToken !== "string") {
throw new Error("Required parameter «confirmation_token» to be a «string» in order to «confirm»");
}
const sanitizedConfirmationToken = RestUtils.sanitize(confirmationToken);
const [pendingUsers] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_pending_users WHERE 1=1 AND confirmation_token = ${sanitizedConfirmationToken};`
].join("\n"));
if (pendingUsers.length === 0) {
throw new Error("Required parameter «confirmation_token» to match an existing pending users confirmation token in order to «confirm»");
} else if (pendingUsers.length !== 1) {
throw new Error("Data corrupted by duplication of confirmation_token of user");
}
const [userData] = pendingUsers;
const sanitizedName = RestUtils.sanitize(userData.name);
const sanitizedPassword = RestUtils.sanitize(userData.password);
const sanitizedEmail = RestUtils.sanitize(userData.email);
await this.server.rest.connection.proxifiedQuery([
`INSERT INTO auth_users (name, password, email) VALUES (${sanitizedName},${sanitizedPassword},${sanitizedEmail});`
].join("\n"));
const sanitizedId = RestUtils.sanitize(userData.id);
await this.server.rest.connection.proxifiedQuery([
`DELETE FROM auth_pending_users WHERE id = ${sanitizedId};`
].join("\n"));
return {
message: "user successfully confirmed"
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.login = async function (user, password) {
try {
trace("AuthByMySQL.prototype.login");
// @TODO......................................
let sessionToken = undefined;
if (typeof user !== "string") {
throw new Error("Required parameter «user» to be a «string» in order to «login»");
}
if (typeof password !== "string") {
throw new Error("Required parameter «password» to be a «string» in order to «login»");
}
const sanitizedUser = RestUtils.sanitize(user);
const [users] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE 1=1 AND name = ${sanitizedUser};`
].join("\n"));
if (users.length === 0) {
throw new Error("Required parameter «user» to match an existing user in order to «login»");
} else if (users.length !== 1) {
throw new Error("Data corrupted by duplication of name of user");
}
const [matchedUser] = users;
if (matchedUser.password !== password) {
throw new Error("Required parameter «password» to be the user password in order to «login»");
}
const userId = matchedUser.id;
const sanitizedUserId = RestUtils.sanitize(userId);
const [sessionsResults] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_sessions WHERE 1=1 AND id_user = ${sanitizedUserId};`
].join("\n"));
if (sessionsResults.length === 0) {
sessionToken = RestUtils.generateRandomToken(20);
const sanitizedSessionToken = RestUtils.sanitize(sessionToken);
await this.server.rest.connection.proxifiedQuery([
`INSERT INTO auth_sessions (id_user, token) VALUES (${sanitizedUserId}, ${sanitizedSessionToken});`
].join("\n"));
} else {
sessionToken = sessionsResults[0].token;
}
const authentication = await this.authenticate(sessionToken);
return {
message: "user successfully logged in",
session_token: sessionToken,
authentication,
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.logout = async function (sessionToken) {
try {
trace("AuthByMySQL.prototype.logout");
const sanitizedSessionToken = RestUtils.sanitize(sessionToken);
const [sessionsResults] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_sessions WHERE 1=1 AND token = ${sanitizedSessionToken};`
].join("\n"));
if (sessionsResults.length === 0) {
throw new Error("Required parameter «session_token» to be a session token in order to «logout»");
} else if (sessionsResults.length !== 1) {
throw new Error("Data corrupted by session token duplication");
}
const [matchedSession] = sessionsResults;
const sanitizedSessionId = RestUtils.sanitize(matchedSession.id);
await this.server.rest.connection.proxifiedQuery([
`DELETE FROM auth_sessions WHERE 1=1 AND id = ${sanitizedSessionId};`
].join("\n"));
return {
message: "user successfully logged out",
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.forgot = async function (user) {
try {
trace("AuthByMySQL.prototype.forgot");
const token = RestUtils.generateRandomToken(20);
const sanitizedUser = RestUtils.sanitize(user);
const sanitizedToken = RestUtils.sanitize(token);
await this.server.rest.connection.proxifiedQuery([
`UPDATE auth_users SET recovery_token = ${sanitizedToken} WHERE 1=1 AND name = ${sanitizedUser};`
].join("\n"));
return {
message: "user successfully notified with recovery email",
recovery_token: configurations.environment !== "test" ? "unknown" : token
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.recover = async function (recovery_token) {
try {
trace("AuthByMySQL.prototype.recover");
const sanitizedToken = RestUtils.sanitize(recovery_token);
const [matchedUsers] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE recovery_token = ${sanitizedToken};`
].join("\n"));
if (matchedUsers.length === 0) {
throw new Error("Required parameter «recovery_token» to be a recovery token in order to «recover»");
} else if (matchedUsers.length !== 1) {
throw new Error("Required user «recovery_token» to be active in order to «recover»");
}
const [userData] = matchedUsers;
const token = RestUtils.generateRandomToken(20);
const sanitizedUserId = RestUtils.sanitize(userData.id);
await this.server.rest.connection.proxifiedQuery([
`UPDATE auth_users SET recovery_token = NULL WHERE 1=1 AND id = ${sanitizedUserId};`
].join("\n"));
return {
message: "user successfully recovered",
password: userData.password
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.unregister = async function (session_token, user, password) {
try {
trace("AuthByMySQL.prototype.unregister");
const sanitizedToken = RestUtils.sanitize(session_token);
const [matchedSessions] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_sessions WHERE token = ${sanitizedToken};`
].join("\n"));
if (matchedSessions.length === 0) {
throw new Error("Required parameters «session_token» to be a session token in order to «unregister»");
} else if (matchedSessions.length !== 1) {
matchedSessions
throw new Error("Data corrupted by session duplication on unregister");
}
const [matchedSession] = matchedSessions;
const sanitizedUserId = RestUtils.sanitize(matchedSession.id_user);
const [[matchedUser]] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_users WHERE id = ${sanitizedUserId};`
].join("\n"));
const isValidUser = (matchedUser.name === user) && (matchedUser.password === password);
if (!isValidUser) {
throw new Error("Required parameters «user» and «password» to match in order to «unregister»")
}
const sanitizedSessionId = RestUtils.sanitize(matchedSession.id);
await this.server.rest.connection.proxifiedQuery([
`DELETE FROM auth_sessions WHERE 1=1 AND id = ${sanitizedSessionId};`
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
`DELETE FROM auth_users WHERE 1=1 AND id = ${sanitizedUserId};`
].join("\n"));
return {
message: "user successfully unregistered",
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.modify = async function (sessionToken, user, password) {
try {
trace("AuthByMySQL.prototype.modify");
const sanitizedToken = RestUtils.sanitize(sessionToken);
const [matchedSessions] = await this.server.rest.connection.proxifiedQuery([
`SELECT * FROM auth_sessions WHERE token = ${sanitizedToken};`
].join("\n"));
if (matchedSessions.length === 0) {
throw new Error("Required parameters «session_token» to be a session token in order to «modify»");
} else if (matchedSessions.length !== 1) {
matchedSessions
throw new Error("Data corrupted by session duplication on modify");
}
const [matchedSession] = matchedSessions;
const sanitizedUserId = RestUtils.sanitize(matchedSession.id_user);
const sanitizedUser = RestUtils.sanitize(user || "");
const sanitizedPassword = RestUtils.sanitize(password || "");
let sanitizedValues = "";
sanitizedValues += user ? ("name = " + sanitizedUser) : "";
sanitizedValues += ((user && password) ? ", " : "") + (password ? ("password = " + sanitizedPassword) : "");
const [updateResults] = await this.server.rest.connection.proxifiedQuery([
`UPDATE auth_users SET ${sanitizedValues} WHERE id = ${sanitizedUserId};`
].join("\n"));
return {
message: "user successfully modified",
};
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.resetAuth = async function () {
try {
trace("AuthByMySQL.prototype.resetAuth");
// ENTITIES:
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_pending_users (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" name VARCHAR(100),",
" password VARCHAR(100),",
" email VARCHAR(100),",
" confirmation_token VARCHAR(100)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_users (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" name VARCHAR(100),",
" password VARCHAR(100),",
" email VARCHAR(100),",
" recovery_token VARCHAR(100),",
" description VARCHAR(200)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_groups (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" name VARCHAR(100),",
" description VARCHAR(200)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_privileges (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" name VARCHAR(100),",
" description VARCHAR(200)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_sessions (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" id_user INT,",
" token VARCHAR(100),",
" FOREIGN KEY (id_user) REFERENCES auth_users(id)",
");"
].join("\n"));
// RELATIONS:
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_groups_of_users (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" id_user INT,",
" id_group INT,",
" FOREIGN KEY (id_user) REFERENCES auth_users(id),",
" FOREIGN KEY (id_group) REFERENCES auth_groups(id)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"CREATE TABLE auth_privileges_of_groups (",
" id INT PRIMARY KEY AUTO_INCREMENT,",
" id_privilege INT,",
" id_group INT,",
" FOREIGN KEY (id_privilege) REFERENCES auth_privileges(id),",
" FOREIGN KEY (id_group) REFERENCES auth_groups(id)",
");"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"INSERT INTO auth_users (name, password, email) VALUES ('administrator', 'administrator', 'carlcarlsonc18@gmail.com');"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"INSERT INTO auth_groups (name, description) VALUES ('administrators', 'the administration');"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"INSERT INTO auth_privileges (name, description) VALUES ('to administrate', 'to administrate');"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"INSERT INTO auth_groups_of_users (id_user, id_group) VALUES ('1', '1');"
].join("\n"));
await this.server.rest.connection.proxifiedQuery([
"INSERT INTO auth_privileges_of_groups (id_group, id_privilege) VALUES ('1', '1');"
].join("\n"));
} catch (error) {
this.onError(error);
}
};
AuthByMySQL.prototype.hasAuthorizationFor = async function (privilegeName, authentication) {
try {
trace("AuthByMySQL.prototype.hasAuthorizationFor");
if (typeof privilegeName !== "string") {
throw new Error("Required parameter «privilegeName» to be a string in order to «hasAuthorizationFor»");
}
if (typeof authentication !== "object") {
throw new Error("Required parameter «authentication» to be a string in order to «hasAuthorizationFor»");
}
const matchedPrivileges = authentication.privileges.filter(privilege => privilege.name === privilegeName);
return matchedPrivileges.length;
} catch (error) {
this.onError(error);
}
};
let RestByDexie = function (options, extensions = {}) {
trace("RestByDexie.constructor");
if (typeof options !== "object") {
throw new Error("Required parameter «options» to be an object in order to «RestByDexie.constructor»");
}
if (typeof options.credentials !== "object") {
throw new Error("Required parameter «options.credentials» to be an object in order to «RestByDexie.constructor»");
}
if (typeof extensions !== "object") {
throw new Error("Required parameter «extensions» to be an object in order to «RestByDexie.constructor»");
}
this.credentials = options.credentials;
Object.assign(this, extensions);
return this;
};
RestByDexie = Object.assign(RestByDexie, { ...RestByMySQL });
RestByDexie.prototype = Object.assign(RestByDexie.prototype, { ...RestByMySQL.prototype });
RestByDexie.prototype.initialize = async function () {
try {
trace("RestByDexie.prototype.initialize");
const versionSchema = {};
const allServices = this.server.services;
for (let indexService = 0; indexService < allServices.length; indexService++) {
const serviceClass = allServices[indexService];
if (typeof serviceClass.creationScript === "string") {
versionSchema[serviceClass.table] = serviceClass.creationScript;
// await this.connection.proxifiedQuery(serviceClass.creationScript);
}
}
if (typeof this.seeder === "function") {
await this.seeder(authentication);
}
this.connection = await RanasDB.connect("main_app_id", [[versionSchema, () => { }]]);
this.connection = RestUtils.expandConnection(this.connection);
return this;
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.resetDatabase = async function (authentication) {
try {
trace("RestByDexie.prototype.resetDatabase");
await RanasDB.dropDatabaseIfExists("main_app_id");
await this.initialize();
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.selectOne = async function (dataType, { where }, authentication) {
try {
trace("RestByDexie.prototype.selectOne");
await this.server.hooks.useHook("api://rest.selectOne::before", { dataType, where, authentication });
await this.server.hooks.useHook("api://rest.selectOne:" + dataType + "::before", { dataType, where, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const allResults = await this.connection.dexieDB[dataType].filter(tfilter).toArray();
if (allResults.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.selectOne»");
} else if (allResults.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.selectOne»");
}
const result = allResults[0];
await this.server.hooks.useHook("api://rest.selectOne::after", { dataType, where, authentication, result });
await this.server.hooks.useHook("api://rest.selectOne:" + dataType + "::after", { dataType, where, authentication, result });
return result;
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.selectMany = async function (dataType, { where = [], order = [], group = [], pagination = [] }, authentication) {
try {
trace("RestByDexie.prototype.selectMany");
await this.server.hooks.useHook("api://rest.selectMany::before", { dataType, where, order, group, pagination, authentication });
await this.server.hooks.useHook("api://rest.selectMany:" + dataType + "::before", { dataType, where, order, group, pagination, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const transaction = await this.connection.dexieDB[dataType].filter(tfilter);
const [page = 1, items = 20] = pagination;
const offset = (page - 1) * items;
const finalOrder = ((!Array.isArray(order)) || (order.length === 0)) ? ":id" : order[0].startsWith("!") ? order[0].substr(1) : order[0];
if (order[0].startsWith("!")) {
transaction.reverse();
}
transaction.offset(offset).limit(items);
const result = await transaction.sortBy(...finalOrder);
await this.server.hooks.useHook("api://rest.selectMany::after", { dataType, where, order, group, pagination, result, authentication });
await this.server.hooks.useHook("api://rest.selectMany:" + dataType + "::after", { dataType, where, order, group, pagination, result, authentication });
return result;
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.insertOne = async function (dataType, { item }, authentication) {
try {
trace("RestByDexie.prototype.insertOne");
await this.server.hooks.useHook("api://rest.insertOne::before", { dataType, item, authentication });
await this.server.hooks.useHook("api://rest.insertOne:" + dataType + "::before", { dataType, item, authentication });
const result = await this.connection.dexieDB[dataType].add(item);
await this.server.hooks.useHook("api://rest.insertOne::after", { dataType, item, authentication });
await this.server.hooks.useHook("api://rest.insertOne:" + dataType + "::after", { dataType, item, authentication });
return {
rows: 1,
id: result
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.insertMany = async function (dataType, { items }, authentication) {
try {
trace("RestByDexie.prototype.insertMany");
await this.server.hooks.useHook("api://rest.insertMany::before", { dataType, items, authentication });
await this.server.hooks.useHook("api://rest.insertMany:" + dataType + "::before", { dataType, items, authentication });
const result = await this.connection.dexieDB[dataType].bulkAdd(items);
await this.server.hooks.useHook("api://rest.insertMany::after", { dataType, items, authentication });
await this.server.hooks.useHook("api://rest.insertMany:" + dataType + "::after", { dataType, items, authentication });
return {
rows: items.length,
id: result
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.updateOne = async function (dataType, { where, values }, authentication) {
try {
trace("RestByDexie.prototype.updateOne");
await this.server.hooks.useHook("api://rest.updateOne::before", { dataType, where, values, authentication });
await this.server.hooks.useHook("api://rest.updateOne:" + dataType + "::before", { dataType, where, values, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const transaction = await this.connection.dexieDB[dataType].filter(tfilter);
const allResults = await transaction.toArray();
if (allResults.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.updateOne»");
} else if (allResults.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.updateOne»");
}
await transaction.modify(item => {
Object.assign(item, values);
});
await this.server.hooks.useHook("api://rest.updateOne::after", { dataType, where, values, authentication });
await this.server.hooks.useHook("api://rest.updateOne:" + dataType + "::after", { dataType, where, values, authentication });
return {
rows: allResults.length,
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.updateMany = async function (dataType, { where, values }, authentication) {
try {
trace("RestByDexie.prototype.updateMany");
await this.server.hooks.useHook("api://rest.updateMany::before", { dataType, where, values, authentication });
await this.server.hooks.useHook("api://rest.updateMany:" + dataType + "::before", { dataType, where, values, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const transaction = await this.connection.dexieDB[dataType].filter(tfilter);
const allResults = await transaction.toArray();
await transaction.modify(item => {
Object.assign(item, values);
});
await this.server.hooks.useHook("api://rest.updateMany::after", { dataType, where, values, authentication });
await this.server.hooks.useHook("api://rest.updateMany:" + dataType + "::after", { dataType, where, values, authentication });
return {
rows: allResults.length,
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.deleteOne = async function (dataType, { where }, authentication) {
try {
trace("RestByDexie.prototype.deleteOne");
await this.server.hooks.useHook("api://rest.deleteOne::before", { dataType, where, authentication });
await this.server.hooks.useHook("api://rest.deleteOne:" + dataType + "::before", { dataType, where, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const transaction = await this.connection.dexieDB[dataType].filter(tfilter);
const allResults = await transaction.toArray();
if (allResults.length === 0) {
throw new Error("No items were found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.deleteOne»");
} else if (allResults.length !== 1) {
throw new Error("More than 1 item was found on «" + dataType + "» by using the specified filters on «RestByDexie.prototype.deleteOne»");
}
await transaction.delete();
await this.server.hooks.useHook("api://rest.deleteOne::after", { dataType, where, authentication });
await this.server.hooks.useHook("api://rest.deleteOne:" + dataType + "::after", { dataType, where, authentication });
return {
rows: allResults.length,
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.deleteMany = async function (dataType, { where }, authentication) {
try {
trace("RestByDexie.prototype.deleteMany");
await this.server.hooks.useHook("api://rest.deleteMany::before", { dataType, where, authentication });
await this.server.hooks.useHook("api://rest.deleteMany:" + dataType + "::before", { dataType, where, authentication });
const tfilter = RestUtils.fromWhereToFilterFunction(where);
const transaction = await this.connection.dexieDB[dataType].filter(tfilter);
const allResults = await transaction.toArray();
await transaction.delete();
await this.server.hooks.useHook("api://rest.deleteMany::after", { dataType, where, authentication });
await this.server.hooks.useHook("api://rest.deleteMany:" + dataType + "::after", { dataType, where, authentication });
return {
rows: allResults.length,
};
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.getFile = async function (table) {
try {
trace("RestByDexie.prototype.getFile");
console.log(table);
return 600;
} catch (error) {
this.onError(error);
}
};
RestByDexie.prototype.setFile = async function (table) {
try {
trace("RestByDexie.prototype.setFile");
console.log(table);
return 600;
} catch (error) {
this.onError(error);
}
};
let AuthByDexie = function (options, extensions = {}) {
trace("AuthByDexie.constructor");
if (typeof options !== "object") {
throw new Error("Required parameter «options» to be an object in order to «AuthByDexie.constructor»");
}
if (typeof options.credentials !== "object") {
throw new Error("Required parameter «options.credentials» to be an object in order to «AuthByDexie.constructor»");
}
if (typeof extensions !== "object") {
throw new Error("Required parameter «extensions» to be an object in order to «AuthByDexie.constructor»");
}
this.credentials = options.credentials;
Object.assign(this, extensions);
return this;
};
AuthByDexie = Object.assign(AuthByDexie, { ...AuthByMySQL });
AuthByDexie.prototype = Object.assign(AuthByDexie.prototype, { ...AuthByMySQL.prototype });
AuthByDexie.prototype.authenticate = function () { };
AuthByDexie.prototype.login = function () { };
AuthByDexie.prototype.logout = function () { };
AuthByDexie.prototype.refresh = function () { };
AuthByDexie.prototype.register = function () { };
AuthByDexie.prototype.confirm = function () { };
AuthByDexie.prototype.forgot = function () { };
AuthByDexie.prototype.recover = function () { };
AuthByDexie.prototype.unregister = function () { };
AuthByDexie.prototype.hasAuthorizationFor = function () { };
AuthByDexie.prototype.resetAuth = function () { };
const VirtualDataService = function (dynamicInterface = {}) {
trace("VirtualDataService.constructor");
Object.assign(this, dynamicInterface);
return this;
};
Object.assign(VirtualDataService, { ...DataService });
Object.assign(VirtualDataService.prototype, { ...DataService.prototype });
VirtualDataService.prototype.resetDatabase = async function () {
trace("VirtualDataService.prototype.resetDatabase");
try {
await RanasDB.dropDatabaseIfExists(this.credentials.database);
return await this.initialize();
} catch (error) {
this.onError(error);
}
};
VirtualDataService.prototype.initialize = async function () {
trace("VirtualDataService.prototype.initialize");
try {
this.connection = await RanasDB.connect(this.credentials.database, this.versionation);
return this;
} catch (error) {
this.onError(error);
}
};
const VirtualQueryService = function () {
trace("VirtualQueryService.constructor");
};
Object.assign(VirtualQueryService, { ...QueryService });
Object.assign(VirtualQueryService.prototype, { ...QueryService.prototype });
const VirtualProcessService = function () {
trace("VirtualProcessService.constructor");
};
Object.assign(VirtualProcessService, { ...ProcessService });
Object.assign(VirtualProcessService.prototype, { ...ProcessService.prototype });
// VirtualProcessService.prototype.dispatch = function (request, response) { };
const VirtualDataServer = function (dynamicInterface = {}) {
trace("VirtualDataServer.constructor");
Object.assign(this, dynamicInterface);
if (!this.adapter) this.adapter = "dexie";
this.rest = undefined;
this.auth = undefined;
this.services = [];
this.queries = [];
this.processes = [];
this.hooks = Hooks.create();
this.basePathForData = "/rest/api/v1";
this.basePathForAuth = "/auth/api/v1";
this.basePathForQuery = "/query/api/v1";
this.basePathForProcess = "/process/api/v1";
return this;
};
Object.assign(VirtualDataServer, { ...DataServer });
Object.assign(VirtualDataServer.prototype, { ...DataServer.prototype });
VirtualDataServer.prototype.initializeRest = async function () {
try {
trace("VirtualDataServer.prototype.initializeRest");
let restAdapter = undefined;
if (typeof this.adapter !== "string") {
this.adapter = "dexie";
}
// @TOCONTINUE: continue adding other REST adapters on the following conditional:
if (this.adapter === "dexie") {
restAdapter = new RestByDexie({
credentials: this.credentials || {},
}, {
...this.restExtension,
server: this,
});
} else {
throw new Error("Required configuration «this.adapter» to be a valid option in order to «initializeRest»");
}
// @OK!
this.rest = await restAdapter.initialize();
} catch (error) {
this.onError(error);
}
};
VirtualDataServer.prototype.initializeAuth = async function () {
try {
trace("VirtualDataServer.prototype.initializeAuth");
let authAdapter = undefined;
if (typeof this.adapter !== "string") {
this.adapter = "dexie";
}
// @TOCONTINUE: continue adding other AUTH adapters on the following conditional:
if (this.adapter === "dexie") {
authAdapter = new AuthByDexie({
credentials: this.credentials,
}, {
...this.authExtension,
server: this,
});
} else {
throw new Error("Required parameter «adapter» to be a valid option in order to «initializeRest»");
}
// @OK!
this.auth = await authAdapter.initialize();
} catch (error) {
this.onError(error);
}
};
VirtualDataServer.prototype.addService = function (...args) {
trace("VirtualDataServer.prototype.addService");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicServiceFactory()
const service = constructorFunction;
Object.assign(service, { ...VirtualDataService }, { ...staticInterface });
Object.assign(service.prototype, { ...VirtualDataService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticServiceInterface(service);
RestUtils.validateDynamicServiceInterface(service.prototype);
this.services.push(service);
return this;
};
VirtualDataServer.prototype.addQuery = function (...args) {
trace("VirtualDataServer.prototype.addQuery");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicQueryFactory()
const queryClass = constructorFunction;
Object.assign(queryClass, { ...VirtualQueryService }, { ...staticInterface });
Object.assign(queryClass.prototype, { ...VirtualQueryService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticQueryInterface(queryClass);
RestUtils.validateDynamicQueryInterface(queryClass.prototype);
this.queries.push(queryClass);
return this;
};
VirtualDataServer.prototype.addProcess = function (...args) {
trace("VirtualDataServer.prototype.addProcess");
const [staticInterface = {}, dynamicInterface = {}, constructorFunctionParameter = undefined] = args;
const constructorFunction = constructorFunctionParameter ? constructorFunctionParameter : RestUtils.basicProcessFactory()
const processClass = constructorFunction;
Object.assign(processClass, { ...VirtualProcessService }, { ...staticInterface });
Object.assign(processClass.prototype, { ...VirtualProcessService.prototype }, { ...dynamicInterface }, {
server: this
});
RestUtils.validateStaticProcessInterface(processClass);
RestUtils.validateDynamicProcessInterface(processClass.prototype);
this.processes.push(processClass);
return this;
};
VirtualDataServer.prototype.dispatchSelf = function (method = "get", url = "/", requestArgs = {}, responseArgs = {}) {
trace("VirtualDataServer.prototype.dispatchSelf");
trace("METHOD: " + method);
trace(" URL: " + url);
const parsedUrl = RestUtils.require("url").parse(url);
const request = new RequestPolyfill(method, url, requestArgs);
const response = new ResponsePolyfill(responseArgs);
if (parsedUrl.pathname.startsWith(this.basePathForData)) {
const [model, operation, quantifier] = parsedUrl.pathname.replace(this.basePathForData, "").split("/").filter(it => it !== "");
this.dispatch(request, response);
return response.response_promise.then(VirtualDataServer.throwOnErrorStatus);
} else if (parsedUrl.pathname.startsWith(this.basePathForAuth)) {
const [operation] = parsedUrl.pathname.replace(this.basePathForAuth, "").split("/").filter(it => it !== "");
this.dispatch(request, response);
return response.response_promise.then(VirtualDataServer.throwOnErrorStatus);
} else if (parsedUrl.pathname.startsWith(this.basePathForProcess)) {
const [processId] = parsedUrl.pathname.replace(this.basePathForProcess, "").split("/").filter(it => it !== "");
this.dispatch(request, response);
return response.response_promise.then(VirtualDataServer.throwOnErrorStatus);
} else if (parsedUrl.pathname.startsWith(this.basePathForQuery)) {
const [queryId] = parsedUrl.pathname.replace(this.basePathForQuery, "").split("/").filter(it => it !== "");
this.dispatch(request, response);
return response.response_promise.then(VirtualDataServer.throwOnErrorStatus);
}
throw new Error("Request not valid: domain out of bounds");
};
VirtualDataServer.throwOnErrorStatus = function (data) {
if (data.status >= 200 && data.status <= 400) {
data.response = Object.assign({}, data, {
statusText: "OK"
});
return data;
}
throw data;
};
/*
VirtualDataServer.prototype.dispatch = function () {};
VirtualDataServer.prototype.createDispatcher = function() {};
VirtualDataServer.prototype.createHttpServerController = function() {};
VirtualDataServer.prototype.createHttpServer = function() {};
VirtualDataServer.prototype.listen = function() {};
VirtualDataServer.prototype.stopDatabaseConnection = function() {};
VirtualDataServer.prototype.stopHttpServer = function() {};
VirtualDataServer.prototype.resetDatabase = function() {};
VirtualDataServer.prototype.resetAuth = function() {};
//*/
////////////////////////////////////////////////////////////////////////
// 12. Common traits:
RestByMySQL.prototype.onError = RestUtils.generateOnErrorFunction("RestByMySQL.prototype.onError");
RestByMySQL.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("RestByMySQL.prototype.onDispatchError");
AuthByMySQL.prototype.onError = RestUtils.generateOnErrorFunction("AuthByMySQL.prototype.onError");
AuthByMySQL.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("AuthByMySQL.prototype.onDispatchError");
DataService.prototype.onError = RestUtils.generateOnErrorFunction("DataService.prototype.onError");
DataService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("DataService.prototype.onDispatchError");
DataServer.prototype.onError = RestUtils.generateOnErrorFunction("DataServer.prototype.onError");
DataServer.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("DataServer.prototype.onDispatchError");
Hooks.prototype.onError = RestUtils.generateOnErrorFunction("Hooks.prototype.onError");
Hooks.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("Hooks.prototype.onDispatchError");
QueryService.prototype.onError = RestUtils.generateOnErrorFunction("QueryService.prototype.onError");
QueryService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("QueryService.prototype.onDispatchError");
ProcessService.prototype.onError = RestUtils.generateOnErrorFunction("ProcessService.prototype.onError");
ProcessService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("ProcessService.prototype.onDispatchError");
RestByDexie.prototype.onError = RestUtils.generateOnErrorFunction("RestByDexie.prototype.onError");
RestByDexie.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("RestByDexie.prototype.onDispatchError");
AuthByDexie.prototype.onError = RestUtils.generateOnErrorFunction("AuthByDexie.prototype.onError");
AuthByDexie.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("AuthByDexie.prototype.onDispatchError");
VirtualDataService.prototype.onError = RestUtils.generateOnErrorFunction("VirtualDataService.prototype.onError");
VirtualDataService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("VirtualDataService.prototype.onDispatchError");
VirtualDataServer.prototype.onError = RestUtils.generateOnErrorFunction("VirtualDataServer.prototype.onError");
VirtualDataServer.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("VirtualDataServer.prototype.onDispatchError");
VirtualQueryService.prototype.onError = RestUtils.generateOnDispatchErrorFunction("VirtualQueryService.prototype.onError");
VirtualQueryService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("VirtualQueryService.prototype.onDispatchError");
VirtualProcessService.prototype.onError = RestUtils.generateOnDispatchErrorFunction("VirtualProcessService.prototype.onError");
VirtualProcessService.prototype.onDispatchError = RestUtils.generateOnDispatchErrorFunction("VirtualProcessService.prototype.onDispatchError");
////////////////////////////////////////////////////////////////////////
// 99. Export internal interfaces from DataServer:
DataServer.RestInterface = RestInterface;
DataServer.RestByMySQL = RestByMySQL;
DataServer.AuthInterface = AuthInterface;
DataServer.AuthByMySQL = AuthByMySQL;
DataServer.DataService = DataService;
DataServer.RestUtils = RestUtils;
DataServer.Hooks = Hooks;
DataServer.RestByDexie = RestByDexie;
DataServer.AuthByDexie = AuthByDexie;
DataServer.VirtualDataServer = VirtualDataServer;
DataServer.VirtualDataService = VirtualDataService;
////////////////////////////////////////////////////////////////////////
const finalAPI = {
// Public API:
DataServer,
VirtualDataServer,
DataService,
Hooks,
// Internal (but exposed) API:
RestInterface,
RestByMySQL,
AuthInterface,
AuthByMySQL,
RestUtils,
RestByDexie,
AuthByDexie,
VirtualDataService,
};
finalAPI.default = finalAPI;
return finalAPI;
});
//Included:lib/014.jquery-v3.3.1.part.js
// ~$ npm install jquery@3.3.1
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
if(typeof window !== "undefined") {
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},G=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,K=/[+~]/,Z=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ee=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ne=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},re=function(){p()},ie=me(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{L.apply(A=H.call(w.childNodes),w.childNodes),A[w.childNodes.length].nodeType}catch(e){L={apply:A.length?function(e,t){q.apply(e,H.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function oe(e,t,r,i){var o,s,l,c,f,h,v,m=t&&t.ownerDocument,T=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==T&&9!==T&&11!==T)return r;if(!i&&((t?t.ownerDocument||t:w)!==d&&p(t),t=t||d,g)){if(11!==T&&(f=J.exec(e)))if(o=f[1]){if(9===T){if(!(l=t.getElementById(o)))return r;if(l.id===o)return r.push(l),r}else if(m&&(l=m.getElementById(o))&&x(t,l)&&l.id===o)return r.push(l),r}else{if(f[2])return L.apply(r,t.getElementsByTagName(e)),r;if((o=f[3])&&n.getElementsByClassName&&t.getElementsByClassName)return L.apply(r,t.getElementsByClassName(o)),r}if(n.qsa&&!S[e+" "]&&(!y||!y.test(e))){if(1!==T)m=t,v=e;else if("object"!==t.nodeName.toLowerCase()){(c=t.getAttribute("id"))?c=c.replace(te,ne):t.setAttribute("id",c=b),s=(h=a(e)).length;while(s--)h[s]="#"+c+" "+ve(h[s]);v=h.join(","),m=K.test(e)&&ge(t.parentNode)||t}if(v)try{return L.apply(r,m.querySelectorAll(v)),r}catch(e){}finally{c===b&&t.removeAttribute("id")}}}return u(e.replace(B,"$1"),t,r,i)}function ae(){var e=[];function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}return t}function se(e){return e[b]=!0,e}function ue(e){var t=d.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function le(e,t){var n=e.split("|"),i=n.length;while(i--)r.attrHandle[n[i]]=t}function ce(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function fe(e){return function(t){return"input"===t.nodeName.toLowerCase()&&t.type===e}}function pe(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function de(e){return function(t){return"form"in t?t.parentNode&&!1===t.disabled?"label"in t?"label"in t.parentNode?t.parentNode.disabled===e:t.disabled===e:t.isDisabled===e||t.isDisabled!==!e&&ie(t)===e:t.disabled===e:"label"in t&&t.disabled===e}}function he(e){return se(function(t){return t=+t,se(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function ge(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}n=oe.support={},o=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},p=oe.setDocument=function(e){var t,i,a=e?e.ownerDocument||e:w;return a!==d&&9===a.nodeType&&a.documentElement?(d=a,h=d.documentElement,g=!o(d),w!==d&&(i=d.defaultView)&&i.top!==i&&(i.addEventListener?i.addEventListener("unload",re,!1):i.attachEvent&&i.attachEvent("onunload",re)),n.attributes=ue(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ue(function(e){return e.appendChild(d.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(d.getElementsByClassName),n.getById=ue(function(e){return h.appendChild(e).id=b,!d.getElementsByName||!d.getElementsByName(b).length}),n.getById?(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){return e.getAttribute("id")===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n=t.getElementById(e);return n?[n]:[]}}):(r.filter.ID=function(e){var t=e.replace(Z,ee);return function(e){var n="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return n&&n.value===t}},r.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&g){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),r.find.TAG=n.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):n.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},r.find.CLASS=n.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&g)return t.getElementsByClassName(e)},v=[],y=[],(n.qsa=Q.test(d.querySelectorAll))&&(ue(function(e){h.appendChild(e).innerHTML="<a id='"+b+"'></a><select id='"+b+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+P+")"),e.querySelectorAll("[id~="+b+"-]").length||y.push("~="),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+b+"+*").length||y.push(".#.+[+~]")}),ue(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=d.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),h.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(n.matchesSelector=Q.test(m=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ue(function(e){n.disconnectedMatch=m.call(e,"*"),m.call(e,"[s!='']:x"),v.push("!=",W)}),y=y.length&&new RegExp(y.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),x=t||Q.test(h.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===d||e.ownerDocument===w&&x(w,e)?-1:t===d||t.ownerDocument===w&&x(w,t)?1:c?O(c,e)-O(c,t):0:4&r?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===d?-1:t===d?1:i?-1:o?1:c?O(c,e)-O(c,t):0;if(i===o)return ce(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?ce(a[r],s[r]):a[r]===w?-1:s[r]===w?1:0},d):d},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==d&&p(e),t=t.replace(z,"='$1']"),n.matchesSelector&&g&&!S[t+" "]&&(!v||!v.test(t))&&(!y||!y.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return oe(t,d,null,[e]).length>0},oe.contains=function(e,t){return(e.ownerDocument||e)!==d&&p(e),x(e,t)},oe.attr=function(e,t){(e.ownerDocument||e)!==d&&p(e);var i=r.attrHandle[t.toLowerCase()],o=i&&N.call(r.attrHandle,t.toLowerCase())?i(e,t,!g):void 0;return void 0!==o?o:n.attributes||!g?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null},oe.escape=function(e){return(e+"").replace(te,ne)},oe.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},oe.uniqueSort=function(e){var t,r=[],i=0,o=0;if(f=!n.detectDuplicates,c=!n.sortStable&&e.slice(0),e.sort(D),f){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return c=null,e},i=oe.getText=function(e){var t,n="",r=0,o=e.nodeType;if(o){if(1===o||9===o||11===o){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(3===o||4===o)return e.nodeValue}else while(t=e[r++])n+=i(t);return n},(r=oe.selectors={cacheLength:50,createPseudo:se,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(Z,ee),e[3]=(e[3]||e[4]||e[5]||"").replace(Z,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=a(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(Z,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=E[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&E(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=oe.attr(r,e);return null==i?"!="===t:!t||(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i.replace($," ")+" ").indexOf(n)>-1:"|="===t&&(i===n||i.slice(0,n.length+1)===n+"-"))}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,f,p,d,h,g=o!==a?"nextSibling":"previousSibling",y=t.parentNode,v=s&&t.nodeName.toLowerCase(),m=!u&&!s,x=!1;if(y){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===v:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?y.firstChild:y.lastChild],a&&m){x=(d=(l=(c=(f=(p=y)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1])&&l[2],p=d&&y.childNodes[d];while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if(1===p.nodeType&&++x&&p===t){c[e]=[T,d,x];break}}else if(m&&(x=d=(l=(c=(f=(p=t)[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]||[])[0]===T&&l[1]),!1===x)while(p=++d&&p&&p[g]||(x=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===v:1===p.nodeType)&&++x&&(m&&((c=(f=p[b]||(p[b]={}))[p.uniqueID]||(f[p.uniqueID]={}))[e]=[T,x]),p===t))break;return(x-=i)===r||x%r==0&&x/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||oe.error("unsupported pseudo: "+e);return i[b]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?se(function(e,n){var r,o=i(e,t),a=o.length;while(a--)e[r=O(e,o[a])]=!(n[r]=o[a])}):function(e){return i(e,0,n)}):i}},pseudos:{not:se(function(e){var t=[],n=[],r=s(e.replace(B,"$1"));return r[b]?se(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),t[0]=null,!n.pop()}}),has:se(function(e){return function(t){return oe(e,t).length>0}}),contains:se(function(e){return e=e.replace(Z,ee),function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:se(function(e){return U.test(e||"")||oe.error("unsupported lang: "+e),e=e.replace(Z,ee).toLowerCase(),function(t){var n;do{if(n=g?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return(n=n.toLowerCase())===e||0===n.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:de(!1),disabled:de(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return Y.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:he(function(){return[0]}),last:he(function(e,t){return[t-1]}),eq:he(function(e,t,n){return[n<0?n+t:n]}),even:he(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:he(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:he(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:he(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=fe(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=pe(t);function ye(){}ye.prototype=r.filters=r.pseudos,r.setFilters=new ye,a=oe.tokenize=function(e,t){var n,i,o,a,s,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=r.preFilter;while(s){n&&!(i=F.exec(s))||(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),n=!1,(i=_.exec(s))&&(n=i.shift(),o.push({value:n,type:i[0].replace(B," ")}),s=s.slice(n.length));for(a in r.filter)!(i=V[a].exec(s))||l[a]&&!(i=l[a](i))||(n=i.shift(),o.push({value:n,type:a,matches:i}),s=s.slice(n.length));if(!n)break}return t?s.length:s?oe.error(e):k(e,u).slice(0)};function ve(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function me(e,t,n){var r=t.dir,i=t.next,o=i||r,a=n&&"parentNode"===o,s=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||a)return e(t,n,i);return!1}:function(t,n,u){var l,c,f,p=[T,s];if(u){while(t=t[r])if((1===t.nodeType||a)&&e(t,n,u))return!0}else while(t=t[r])if(1===t.nodeType||a)if(f=t[b]||(t[b]={}),c=f[t.uniqueID]||(f[t.uniqueID]={}),i&&i===t.nodeName.toLowerCase())t=t[r]||t;else{if((l=c[o])&&l[0]===T&&l[1]===s)return p[2]=l[2];if(c[o]=p,p[2]=e(t,n,u))return!0}return!1}}function xe(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function be(e,t,n){for(var r=0,i=t.length;r<i;r++)oe(e,t[r],n);return n}function we(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Te(e,t,n,r,i,o){return r&&!r[b]&&(r=Te(r)),i&&!i[b]&&(i=Te(i,o)),se(function(o,a,s,u){var l,c,f,p=[],d=[],h=a.length,g=o||be(t||"*",s.nodeType?[s]:s,[]),y=!e||!o&&t?g:we(g,p,e,s,u),v=n?i||(o?e:h||r)?[]:a:y;if(n&&n(y,v,s,u),r){l=we(v,d),r(l,[],s,u),c=l.length;while(c--)(f=l[c])&&(v[d[c]]=!(y[d[c]]=f))}if(o){if(i||e){if(i){l=[],c=v.length;while(c--)(f=v[c])&&l.push(y[c]=f);i(null,v=[],l,u)}c=v.length;while(c--)(f=v[c])&&(l=i?O(o,f):p[c])>-1&&(o[l]=!(a[l]=f))}}else v=we(v===a?v.splice(h,v.length):v),i?i(null,a,v,u):L.apply(a,v)})}function Ce(e){for(var t,n,i,o=e.length,a=r.relative[e[0].type],s=a||r.relative[" "],u=a?1:0,c=me(function(e){return e===t},s,!0),f=me(function(e){return O(t,e)>-1},s,!0),p=[function(e,n,r){var i=!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):f(e,n,r));return t=null,i}];u<o;u++)if(n=r.relative[e[u].type])p=[me(xe(p),n)];else{if((n=r.filter[e[u].type].apply(null,e[u].matches))[b]){for(i=++u;i<o;i++)if(r.relative[e[i].type])break;return Te(u>1&&xe(p),u>1&&ve(e.slice(0,u-1).concat({value:" "===e[u-2].type?"*":""})).replace(B,"$1"),n,u<i&&Ce(e.slice(u,i)),i<o&&Ce(e=e.slice(i)),i<o&&ve(e))}p.push(n)}return xe(p)}function Ee(e,t){var n=t.length>0,i=e.length>0,o=function(o,a,s,u,c){var f,h,y,v=0,m="0",x=o&&[],b=[],w=l,C=o||i&&r.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,k=C.length;for(c&&(l=a===d||a||c);m!==k&&null!=(f=C[m]);m++){if(i&&f){h=0,a||f.ownerDocument===d||(p(f),s=!g);while(y=e[h++])if(y(f,a||d,s)){u.push(f);break}c&&(T=E)}n&&((f=!y&&f)&&v--,o&&x.push(f))}if(v+=m,n&&m!==v){h=0;while(y=t[h++])y(x,b,a,s);if(o){if(v>0)while(m--)x[m]||b[m]||(b[m]=j.call(u));b=we(b)}L.apply(u,b),c&&!o&&b.length>0&&v+t.length>1&&oe.uniqueSort(u)}return c&&(T=E,l=w),x};return n?se(o):o}return s=oe.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=a(e)),n=t.length;while(n--)(o=Ce(t[n]))[b]?r.push(o):i.push(o);(o=S(e,Ee(i,r))).selector=e}return o},u=oe.select=function(e,t,n,i){var o,u,l,c,f,p="function"==typeof e&&e,d=!i&&a(e=p.selector||e);if(n=n||[],1===d.length){if((u=d[0]=d[0].slice(0)).length>2&&"ID"===(l=u[0]).type&&9===t.nodeType&&g&&r.relative[u[1].type]){if(!(t=(r.find.ID(l.matches[0].replace(Z,ee),t)||[])[0]))return n;p&&(t=t.parentNode),e=e.slice(u.shift().value.length)}o=V.needsContext.test(e)?0:u.length;while(o--){if(l=u[o],r.relative[c=l.type])break;if((f=r.find[c])&&(i=f(l.matches[0].replace(Z,ee),K.test(u[0].type)&&ge(t.parentNode)||t))){if(u.splice(o,1),!(e=i.length&&ve(u)))return L.apply(n,i),n;break}}}return(p||s(e,d))(i,t,!g,n,!t||K.test(e)&&ge(t.parentNode)||t),n},n.sortStable=b.split("").sort(D).join("")===b,n.detectDuplicates=!!f,p(),n.sortDetached=ue(function(e){return 1&e.compareDocumentPosition(d.createElement("fieldset"))}),ue(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||le("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ue(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||le("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ue(function(e){return null==e.getAttribute("disabled")})||le(P,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),oe}(e);w.find=E,w.expr=E.selectors,w.expr[":"]=w.expr.pseudos,w.uniqueSort=w.unique=E.uniqueSort,w.text=E.getText,w.isXMLDoc=E.isXML,w.contains=E.contains,w.escapeSelector=E.escape;var k=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&w(e).is(n))break;r.push(e)}return r},S=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},D=w.expr.match.needsContext;function N(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var A=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,t,n){return g(t)?w.grep(e,function(e,r){return!!t.call(e,r,e)!==n}):t.nodeType?w.grep(e,function(e){return e===t!==n}):"string"!=typeof t?w.grep(e,function(e){return u.call(t,e)>-1!==n}):w.filter(t,e,n)}w.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?w.find.matchesSelector(r,e)?[r]:[]:w.find.matches(e,w.grep(t,function(e){return 1===e.nodeType}))},w.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(w(e).filter(function(){for(t=0;t<r;t++)if(w.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)w.find(e,i[t],n);return r>1?w.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&D.test(e)?w(e):e||[],!1).length}});var q,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(w.fn.init=function(e,t,n){var i,o;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(i="<"===e[0]&&">"===e[e.length-1]&&e.length>=3?[null,e,null]:L.exec(e))||!i[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:r,!0)),A.test(i[1])&&w.isPlainObject(t))for(i in t)g(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(o=r.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):g(e)?void 0!==n.ready?n.ready(e):e(w):w.makeArray(e,this)}).prototype=w.fn,q=w(r);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};w.fn.extend({has:function(e){var t=w(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(w.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&w(e);if(!D.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&w.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?w.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?u.call(w(e),this[0]):u.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(w.uniqueSort(w.merge(this.get(),w(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}w.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return k(e,"parentNode")},parentsUntil:function(e,t,n){return k(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return k(e,"nextSibling")},prevAll:function(e){return k(e,"previousSibling")},nextUntil:function(e,t,n){return k(e,"nextSibling",n)},prevUntil:function(e,t,n){return k(e,"previousSibling",n)},siblings:function(e){return S((e.parentNode||{}).firstChild,e)},children:function(e){return S(e.firstChild)},contents:function(e){return N(e,"iframe")?e.contentDocument:(N(e,"template")&&(e=e.content||e),w.merge([],e.childNodes))}},function(e,t){w.fn[e]=function(n,r){var i=w.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=w.filter(r,i)),this.length>1&&(O[e]||w.uniqueSort(i),H.test(e)&&i.reverse()),this.pushStack(i)}});var M=/[^\x20\t\r\n\f]+/g;function R(e){var t={};return w.each(e.match(M)||[],function(e,n){t[n]=!0}),t}w.Callbacks=function(e){e="string"==typeof e?R(e):w.extend({},e);var t,n,r,i,o=[],a=[],s=-1,u=function(){for(i=i||e.once,r=t=!0;a.length;s=-1){n=a.shift();while(++s<o.length)!1===o[s].apply(n[0],n[1])&&e.stopOnFalse&&(s=o.length,n=!1)}e.memory||(n=!1),t=!1,i&&(o=n?[]:"")},l={add:function(){return o&&(n&&!t&&(s=o.length-1,a.push(n)),function t(n){w.each(n,function(n,r){g(r)?e.unique&&l.has(r)||o.push(r):r&&r.length&&"string"!==x(r)&&t(r)})}(arguments),n&&!t&&u()),this},remove:function(){return w.each(arguments,function(e,t){var n;while((n=w.inArray(t,o,n))>-1)o.splice(n,1),n<=s&&s--}),this},has:function(e){return e?w.inArray(e,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||t||(o=n=""),this},locked:function(){return!!i},fireWith:function(e,n){return i||(n=[e,(n=n||[]).slice?n.slice():n],a.push(n),t||u()),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!r}};return l};function I(e){return e}function W(e){throw e}function $(e,t,n,r){var i;try{e&&g(i=e.promise)?i.call(e).done(t).fail(n):e&&g(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}w.extend({Deferred:function(t){var n=[["notify","progress",w.Callbacks("memory"),w.Callbacks("memory"),2],["resolve","done",w.Callbacks("once memory"),w.Callbacks("once memory"),0,"resolved"],["reject","fail",w.Callbacks("once memory"),w.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},"catch":function(e){return i.then(null,e)},pipe:function(){var e=arguments;return w.Deferred(function(t){w.each(n,function(n,r){var i=g(e[r[4]])&&e[r[4]];o[r[1]](function(){var e=i&&i.apply(this,arguments);e&&g(e.promise)?e.promise().progress(t.notify).done(t.resolve).fail(t.reject):t[r[0]+"With"](this,i?[e]:arguments)})}),e=null}).promise()},then:function(t,r,i){var o=0;function a(t,n,r,i){return function(){var s=this,u=arguments,l=function(){var e,l;if(!(t<o)){if((e=r.apply(s,u))===n.promise())throw new TypeError("Thenable self-resolution");l=e&&("object"==typeof e||"function"==typeof e)&&e.then,g(l)?i?l.call(e,a(o,n,I,i),a(o,n,W,i)):(o++,l.call(e,a(o,n,I,i),a(o,n,W,i),a(o,n,I,n.notifyWith))):(r!==I&&(s=void 0,u=[e]),(i||n.resolveWith)(s,u))}},c=i?l:function(){try{l()}catch(e){w.Deferred.exceptionHook&&w.Deferred.exceptionHook(e,c.stackTrace),t+1>=o&&(r!==W&&(s=void 0,u=[e]),n.rejectWith(s,u))}};t?c():(w.Deferred.getStackHook&&(c.stackTrace=w.Deferred.getStackHook()),e.setTimeout(c))}}return w.Deferred(function(e){n[0][3].add(a(0,e,g(i)?i:I,e.notifyWith)),n[1][3].add(a(0,e,g(t)?t:I)),n[2][3].add(a(0,e,g(r)?r:W))}).promise()},promise:function(e){return null!=e?w.extend(e,i):i}},o={};return w.each(n,function(e,t){var a=t[2],s=t[5];i[t[1]]=a.add,s&&a.add(function(){r=s},n[3-e][2].disable,n[3-e][3].disable,n[0][2].lock,n[0][3].lock),a.add(t[3].fire),o[t[0]]=function(){return o[t[0]+"With"](this===o?void 0:this,arguments),this},o[t[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(e){var t=arguments.length,n=t,r=Array(n),i=o.call(arguments),a=w.Deferred(),s=function(e){return function(n){r[e]=this,i[e]=arguments.length>1?o.call(arguments):n,--t||a.resolveWith(r,i)}};if(t<=1&&($(e,a.done(s(n)).resolve,a.reject,!t),"pending"===a.state()||g(i[n]&&i[n].then)))return a.then();while(n--)$(i[n],s(n),a.reject);return a.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;w.Deferred.exceptionHook=function(t,n){e.console&&e.console.warn&&t&&B.test(t.name)&&e.console.warn("jQuery.Deferred exception: "+t.message,t.stack,n)},w.readyException=function(t){e.setTimeout(function(){throw t})};var F=w.Deferred();w.fn.ready=function(e){return F.then(e)["catch"](function(e){w.readyException(e)}),this},w.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--w.readyWait:w.isReady)||(w.isReady=!0,!0!==e&&--w.readyWait>0||F.resolveWith(r,[w]))}}),w.ready.then=F.then;function _(){r.removeEventListener("DOMContentLoaded",_),e.removeEventListener("load",_),w.ready()}"complete"===r.readyState||"loading"!==r.readyState&&!r.documentElement.doScroll?e.setTimeout(w.ready):(r.addEventListener("DOMContentLoaded",_),e.addEventListener("load",_));var z=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===x(n)){i=!0;for(s in n)z(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,g(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(w(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},X=/^-ms-/,U=/-([a-z])/g;function V(e,t){return t.toUpperCase()}function G(e){return e.replace(X,"ms-").replace(U,V)}var Y=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function Q(){this.expando=w.expando+Q.uid++}Q.uid=1,Q.prototype={cache:function(e){var t=e[this.expando];return t||(t={},Y(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[G(t)]=n;else for(r in t)i[G(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][G(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(G):(t=G(t))in r?[t]:t.match(M)||[]).length;while(n--)delete r[t[n]]}(void 0===t||w.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!w.isEmptyObject(t)}};var J=new Q,K=new Q,Z=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,ee=/[A-Z]/g;function te(e){return"true"===e||"false"!==e&&("null"===e?null:e===+e+""?+e:Z.test(e)?JSON.parse(e):e)}function ne(e,t,n){var r;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(ee,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n=te(n)}catch(e){}K.set(e,t,n)}else n=void 0;return n}w.extend({hasData:function(e){return K.hasData(e)||J.hasData(e)},data:function(e,t,n){return K.access(e,t,n)},removeData:function(e,t){K.remove(e,t)},_data:function(e,t,n){return J.access(e,t,n)},_removeData:function(e,t){J.remove(e,t)}}),w.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=K.get(o),1===o.nodeType&&!J.get(o,"hasDataAttrs"))){n=a.length;while(n--)a[n]&&0===(r=a[n].name).indexOf("data-")&&(r=G(r.slice(5)),ne(o,r,i[r]));J.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof e?this.each(function(){K.set(this,e)}):z(this,function(t){var n;if(o&&void 0===t){if(void 0!==(n=K.get(o,e)))return n;if(void 0!==(n=ne(o,e)))return n}else this.each(function(){K.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){K.remove(this,e)})}}),w.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=J.get(e,t),n&&(!r||Array.isArray(n)?r=J.access(e,t,w.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=w.queue(e,t),r=n.length,i=n.shift(),o=w._queueHooks(e,t),a=function(){w.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return J.get(e,n)||J.access(e,n,{empty:w.Callbacks("once memory").add(function(){J.remove(e,[t+"queue",n])})})}}),w.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?w.queue(this[0],e):void 0===t?this:this.each(function(){var n=w.queue(this,e,t);w._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&w.dequeue(this,e)})},dequeue:function(e){return this.each(function(){w.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=w.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=J.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var re=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ie=new RegExp("^(?:([+-])=|)("+re+")([a-z%]*)$","i"),oe=["Top","Right","Bottom","Left"],ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&w.contains(e.ownerDocument,e)&&"none"===w.css(e,"display")},se=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};function ue(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return w.css(e,t,"")},u=s(),l=n&&n[3]||(w.cssNumber[t]?"":"px"),c=(w.cssNumber[t]||"px"!==l&&+u)&&ie.exec(w.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)w.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,w.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var le={};function ce(e){var t,n=e.ownerDocument,r=e.nodeName,i=le[r];return i||(t=n.body.appendChild(n.createElement(r)),i=w.css(t,"display"),t.parentNode.removeChild(t),"none"===i&&(i="block"),le[r]=i,i)}function fe(e,t){for(var n,r,i=[],o=0,a=e.length;o<a;o++)(r=e[o]).style&&(n=r.style.display,t?("none"===n&&(i[o]=J.get(r,"display")||null,i[o]||(r.style.display="")),""===r.style.display&&ae(r)&&(i[o]=ce(r))):"none"!==n&&(i[o]="none",J.set(r,"display",n)));for(o=0;o<a;o++)null!=i[o]&&(e[o].style.display=i[o]);return e}w.fn.extend({show:function(){return fe(this,!0)},hide:function(){return fe(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?w(this).show():w(this).hide()})}});var pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ge.optgroup=ge.option,ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td;function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?w.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n<r;n++)J.set(e[n],"globalEval",!t||J.get(t[n],"globalEval"))}var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===x(o))w.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+w.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;w.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&w.inArray(o,r)>-1)i&&i.push(o);else if(l=w.contains(o.ownerDocument,o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}!function(){var e=r.createDocumentFragment().appendChild(r.createElement("div")),t=r.createElement("input");t.setAttribute("type","radio"),t.setAttribute("checked","checked"),t.setAttribute("name","t"),e.appendChild(t),h.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="<textarea>x</textarea>",h.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var be=r.documentElement,we=/^key/,Te=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function ke(){return!1}function Se(){try{return r.activeElement}catch(e){}}function De(e,t,n,r,i,o){var a,s;if("object"==typeof t){"string"!=typeof n&&(r=r||n,n=void 0);for(s in t)De(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=ke;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,i,r,n)})}w.event={global:{},add:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.get(e);if(y){n.handler&&(n=(o=n).handler,i=o.selector),i&&w.find.matchesSelector(be,i),n.guid||(n.guid=w.guid++),(u=y.events)||(u=y.events={}),(a=y.handle)||(a=y.handle=function(t){return"undefined"!=typeof w&&w.event.triggered!==t.type?w.event.dispatch.apply(e,arguments):void 0}),l=(t=(t||"").match(M)||[""]).length;while(l--)d=g=(s=Ce.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=w.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=w.event.special[d]||{},c=w.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&w.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(e,r,h,a)||e.addEventListener&&e.addEventListener(d,a)),f.add&&(f.add.call(e,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),w.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=J.hasData(e)&&J.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(M)||[""]).length;while(l--)if(s=Ce.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){f=w.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||w.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)w.event.remove(e,d+t[l],n,r,!0);w.isEmptyObject(u)&&J.remove(e,"handle events")}},dispatch:function(e){var t=w.event.fix(e),n,r,i,o,a,s,u=new Array(arguments.length),l=(J.get(this,"events")||{})[t.type]||[],c=w.event.special[t.type]||{};for(u[0]=t,n=1;n<arguments.length;n++)u[n]=arguments[n];if(t.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,t)){s=w.event.handlers.call(this,t,l),n=0;while((o=s[n++])&&!t.isPropagationStopped()){t.currentTarget=o.elem,r=0;while((a=o.handlers[r++])&&!t.isImmediatePropagationStopped())t.rnamespace&&!t.rnamespace.test(a.namespace)||(t.handleObj=a,t.data=a.data,void 0!==(i=((w.event.special[a.origType]||{}).handle||a.handler).apply(o.elem,u))&&!1===(t.result=i)&&(t.preventDefault(),t.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,t),t.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&e.button>=1))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?w(i,this).index(l)>-1:w.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(e,t){Object.defineProperty(w.Event.prototype,e,{enumerable:!0,configurable:!0,get:g(t)?function(){if(this.originalEvent)return t(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[e]},set:function(t){Object.defineProperty(this,e,{enumerable:!0,configurable:!0,writable:!0,value:t})}})},fix:function(e){return e[w.expando]?e:new w.Event(e)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==Se()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===Se()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&N(this,"input"))return this.click(),!1},_default:function(e){return N(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},w.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},w.Event=function(e,t){if(!(this instanceof w.Event))return new w.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Ee:ke,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&w.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[w.expando]=!0},w.Event.prototype={constructor:w.Event,isDefaultPrevented:ke,isPropagationStopped:ke,isImmediatePropagationStopped:ke,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Ee,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Ee,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Ee,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},w.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&we.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&Te.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},w.event.addProp),w.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){w.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return i&&(i===r||w.contains(r,i))||(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),w.fn.extend({on:function(e,t,n,r){return De(this,e,t,n,r)},one:function(e,t,n,r){return De(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,w(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=ke),this.each(function(){w.event.remove(this,e,n,t)})}});var Ne=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Ae=/<script|<style|<link/i,je=/checked\s*(?:[^=]|=\s*.checked.)/i,qe=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Le(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")?w(e).children("tbody")[0]||e:e}function He(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(J.hasData(e)&&(o=J.access(e),a=J.set(t,o),l=o.events)){delete a.handle,a.events={};for(i in l)for(n=0,r=l[i].length;n<r;n++)w.event.add(t,i,l[i][n])}K.hasData(e)&&(s=K.access(e),u=w.extend({},s),K.set(t,u))}}function Me(e,t){var n=t.nodeName.toLowerCase();"input"===n&&pe.test(e.type)?t.checked=e.checked:"input"!==n&&"textarea"!==n||(t.defaultValue=e.defaultValue)}function Re(e,t,n,r){t=a.apply([],t);var i,o,s,u,l,c,f=0,p=e.length,d=p-1,y=t[0],v=g(y);if(v||p>1&&"string"==typeof y&&!h.checkClone&&je.test(y))return e.each(function(i){var o=e.eq(i);v&&(t[0]=y.call(this,i,o.html())),Re(o,t,n,r)});if(p&&(i=xe(t,e[0].ownerDocument,!1,e,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(u=(s=w.map(ye(i,"script"),He)).length;f<p;f++)l=i,f!==d&&(l=w.clone(l,!0,!0),u&&w.merge(s,ye(l,"script"))),n.call(e[f],l,f);if(u)for(c=s[s.length-1].ownerDocument,w.map(s,Oe),f=0;f<u;f++)l=s[f],he.test(l.type||"")&&!J.access(l,"globalEval")&&w.contains(c,l)&&(l.src&&"module"!==(l.type||"").toLowerCase()?w._evalUrl&&w._evalUrl(l.src):m(l.textContent.replace(qe,""),c,l))}return e}function Ie(e,t,n){for(var r,i=t?w.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||w.cleanData(ye(r)),r.parentNode&&(n&&w.contains(r.ownerDocument,r)&&ve(ye(r,"script")),r.parentNode.removeChild(r));return e}w.extend({htmlPrefilter:function(e){return e.replace(Ne,"<$1></$2>")},clone:function(e,t,n){var r,i,o,a,s=e.cloneNode(!0),u=w.contains(e.ownerDocument,e);if(!(h.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=ye(s),r=0,i=(o=ye(e)).length;r<i;r++)Me(o[r],a[r]);if(t)if(n)for(o=o||ye(e),a=a||ye(s),r=0,i=o.length;r<i;r++)Pe(o[r],a[r]);else Pe(e,s);return(a=ye(s,"script")).length>0&&ve(a,!u&&ye(e,"script")),s},cleanData:function(e){for(var t,n,r,i=w.event.special,o=0;void 0!==(n=e[o]);o++)if(Y(n)){if(t=n[J.expando]){if(t.events)for(r in t.events)i[r]?w.event.remove(n,r):w.removeEvent(n,r,t.handle);n[J.expando]=void 0}n[K.expando]&&(n[K.expando]=void 0)}}}),w.fn.extend({detach:function(e){return Ie(this,e,!0)},remove:function(e){return Ie(this,e)},text:function(e){return z(this,function(e){return void 0===e?w.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return Re(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return Re(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return Re(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(w.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return w.clone(this,e,t)})},html:function(e){return z(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ae.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=w.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(w.cleanData(ye(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=[];return Re(this,arguments,function(t){var n=this.parentNode;w.inArray(this,e)<0&&(w.cleanData(ye(this)),n&&n.replaceChild(t,this))},e)}}),w.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){w.fn[e]=function(e){for(var n,r=[],i=w(e),o=i.length-1,a=0;a<=o;a++)n=a===o?this:this.clone(!0),w(i[a])[t](n),s.apply(r,n.get());return this.pushStack(r)}});var We=new RegExp("^("+re+")(?!px)[a-z%]+$","i"),$e=function(t){var n=t.ownerDocument.defaultView;return n&&n.opener||(n=e),n.getComputedStyle(t)},Be=new RegExp(oe.join("|"),"i");!function(){function t(){if(c){l.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",c.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",be.appendChild(l).appendChild(c);var t=e.getComputedStyle(c);i="1%"!==t.top,u=12===n(t.marginLeft),c.style.right="60%",s=36===n(t.right),o=36===n(t.width),c.style.position="absolute",a=36===c.offsetWidth||"absolute",be.removeChild(l),c=null}}function n(e){return Math.round(parseFloat(e))}var i,o,a,s,u,l=r.createElement("div"),c=r.createElement("div");c.style&&(c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",h.clearCloneStyle="content-box"===c.style.backgroundClip,w.extend(h,{boxSizingReliable:function(){return t(),o},pixelBoxStyles:function(){return t(),s},pixelPosition:function(){return t(),i},reliableMarginLeft:function(){return t(),u},scrollboxSize:function(){return t(),a}}))}();function Fe(e,t,n){var r,i,o,a,s=e.style;return(n=n||$e(e))&&(""!==(a=n.getPropertyValue(t)||n[t])||w.contains(e.ownerDocument,e)||(a=w.style(e,t)),!h.pixelBoxStyles()&&We.test(a)&&Be.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function _e(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}var ze=/^(none|table(?!-c[ea]).+)/,Xe=/^--/,Ue={position:"absolute",visibility:"hidden",display:"block"},Ve={letterSpacing:"0",fontWeight:"400"},Ge=["Webkit","Moz","ms"],Ye=r.createElement("div").style;function Qe(e){if(e in Ye)return e;var t=e[0].toUpperCase()+e.slice(1),n=Ge.length;while(n--)if((e=Ge[n]+t)in Ye)return e}function Je(e){var t=w.cssProps[e];return t||(t=w.cssProps[e]=Qe(e)||e),t}function Ke(e,t,n){var r=ie.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Ze(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=w.css(e,n+oe[a],!0,i)),r?("content"===n&&(u-=w.css(e,"padding"+oe[a],!0,i)),"margin"!==n&&(u-=w.css(e,"border"+oe[a]+"Width",!0,i))):(u+=w.css(e,"padding"+oe[a],!0,i),"padding"!==n?u+=w.css(e,"border"+oe[a]+"Width",!0,i):s+=w.css(e,"border"+oe[a]+"Width",!0,i));return!r&&o>=0&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))),u}function et(e,t,n){var r=$e(e),i=Fe(e,t,r),o="border-box"===w.css(e,"boxSizing",!1,r),a=o;if(We.test(i)){if(!n)return i;i="auto"}return a=a&&(h.boxSizingReliable()||i===e.style[t]),("auto"===i||!parseFloat(i)&&"inline"===w.css(e,"display",!1,r))&&(i=e["offset"+t[0].toUpperCase()+t.slice(1)],a=!0),(i=parseFloat(i)||0)+Ze(e,t,n||(o?"border":"content"),a,r,i)+"px"}w.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Fe(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=G(t),u=Xe.test(t),l=e.style;if(u||(t=Je(s)),a=w.cssHooks[t]||w.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"==(o=typeof n)&&(i=ie.exec(n))&&i[1]&&(n=ue(e,t,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(w.cssNumber[s]?"":"px")),h.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=G(t);return Xe.test(t)||(t=Je(s)),(a=w.cssHooks[t]||w.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Fe(e,t,r)),"normal"===i&&t in Ve&&(i=Ve[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),w.each(["height","width"],function(e,t){w.cssHooks[t]={get:function(e,n,r){if(n)return!ze.test(w.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?et(e,t,r):se(e,Ue,function(){return et(e,t,r)})},set:function(e,n,r){var i,o=$e(e),a="border-box"===w.css(e,"boxSizing",!1,o),s=r&&Ze(e,t,r,a,o);return a&&h.scrollboxSize()===o.position&&(s-=Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-parseFloat(o[t])-Ze(e,t,"border",!1,o)-.5)),s&&(i=ie.exec(n))&&"px"!==(i[3]||"px")&&(e.style[t]=n,n=w.css(e,t)),Ke(e,n,s)}}}),w.cssHooks.marginLeft=_e(h.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Fe(e,"marginLeft"))||e.getBoundingClientRect().left-se(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),w.each({margin:"",padding:"",border:"Width"},function(e,t){w.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[e+oe[r]+t]=o[r]||o[r-2]||o[0];return i}},"margin"!==e&&(w.cssHooks[e+t].set=Ke)}),w.fn.extend({css:function(e,t){return z(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=$e(e),i=t.length;a<i;a++)o[t[a]]=w.css(e,t[a],!1,r);return o}return void 0!==n?w.style(e,t,n):w.css(e,t)},e,t,arguments.length>1)}});function tt(e,t,n,r,i){return new tt.prototype.init(e,t,n,r,i)}w.Tween=tt,tt.prototype={constructor:tt,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||w.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(w.cssNumber[n]?"":"px")},cur:function(){var e=tt.propHooks[this.prop];return e&&e.get?e.get(this):tt.propHooks._default.get(this)},run:function(e){var t,n=tt.propHooks[this.prop];return this.options.duration?this.pos=t=w.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):tt.propHooks._default.set(this),this}},tt.prototype.init.prototype=tt.prototype,tt.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=w.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){w.fx.step[e.prop]?w.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[w.cssProps[e.prop]]&&!w.cssHooks[e.prop]?e.elem[e.prop]=e.now:w.style(e.elem,e.prop,e.now+e.unit)}}},tt.propHooks.scrollTop=tt.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},w.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},w.fx=tt.prototype.init,w.fx.step={};var nt,rt,it=/^(?:toggle|show|hide)$/,ot=/queueHooks$/;function at(){rt&&(!1===r.hidden&&e.requestAnimationFrame?e.requestAnimationFrame(at):e.setTimeout(at,w.fx.interval),w.fx.tick())}function st(){return e.setTimeout(function(){nt=void 0}),nt=Date.now()}function ut(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=oe[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function lt(e,t,n){for(var r,i=(pt.tweeners[t]||[]).concat(pt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function ct(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),y=J.get(e,"fxshow");n.queue||(null==(a=w._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,w.queue(e,"fx").length||a.empty.fire()})}));for(r in t)if(i=t[r],it.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!y||void 0===y[r])continue;g=!0}d[r]=y&&y[r]||w.style(e,r)}if((u=!w.isEmptyObject(t))||!w.isEmptyObject(d)){f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=y&&y.display)&&(l=J.get(e,"display")),"none"===(c=w.css(e,"display"))&&(l?c=l:(fe([e],!0),l=e.style.display||l,c=w.css(e,"display"),fe([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===w.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1;for(r in d)u||(y?"hidden"in y&&(g=y.hidden):y=J.access(e,"fxshow",{display:l}),o&&(y.hidden=!g),g&&fe([e],!0),p.done(function(){g||fe([e]),J.remove(e,"fxshow");for(r in d)w.style(e,r,d[r])})),u=lt(g?y[r]:0,r,p),r in y||(y[r]=u.start,g&&(u.end=u.start,u.start=0))}}function ft(e,t){var n,r,i,o,a;for(n in e)if(r=G(n),i=t[r],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=w.cssHooks[r])&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function pt(e,t,n){var r,i,o=0,a=pt.prefilters.length,s=w.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var t=nt||st(),n=Math.max(0,l.startTime+l.duration-t),r=1-(n/l.duration||0),o=0,a=l.tweens.length;o<a;o++)l.tweens[o].run(r);return s.notifyWith(e,[l,r,n]),r<1&&a?n:(a||s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:w.extend({},t),opts:w.extend(!0,{specialEasing:{},easing:w.easing._default},n),originalProperties:t,originalOptions:n,startTime:nt||st(),duration:n.duration,tweens:[],createTween:function(t,n){var r=w.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;n<r;n++)l.tweens[n].run(1);return t?(s.notifyWith(e,[l,1,0]),s.resolveWith(e,[l,t])):s.rejectWith(e,[l,t]),this}}),c=l.props;for(ft(c,l.opts.specialEasing);o<a;o++)if(r=pt.prefilters[o].call(l,e,c,l.opts))return g(r.stop)&&(w._queueHooks(l.elem,l.opts.queue).stop=r.stop.bind(r)),r;return w.map(c,lt,l),g(l.opts.start)&&l.opts.start.call(e,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),w.fx.timer(w.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l}w.Animation=w.extend(pt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return ue(n.elem,e,ie.exec(t),n),n}]},tweener:function(e,t){g(e)?(t=e,e=["*"]):e=e.match(M);for(var n,r=0,i=e.length;r<i;r++)n=e[r],pt.tweeners[n]=pt.tweeners[n]||[],pt.tweeners[n].unshift(t)},prefilters:[ct],prefilter:function(e,t){t?pt.prefilters.unshift(e):pt.prefilters.push(e)}}),w.speed=function(e,t,n){var r=e&&"object"==typeof e?w.extend({},e):{complete:n||!n&&t||g(e)&&e,duration:e,easing:n&&t||t&&!g(t)&&t};return w.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in w.fx.speeds?r.duration=w.fx.speeds[r.duration]:r.duration=w.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){g(r.old)&&r.old.call(this),r.queue&&w.dequeue(this,r.queue)},r},w.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=w.isEmptyObject(e),o=w.speed(t,n,r),a=function(){var t=pt(this,w.extend({},e),o);(i||J.get(this,"finish"))&&t.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&!1!==e&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=w.timers,a=J.get(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&ot.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));!t&&n||w.dequeue(this,e)})},finish:function(e){return!1!==e&&(e=e||"fx"),this.each(function(){var t,n=J.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=w.timers,a=r?r.length:0;for(n.finish=!0,w.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;t<a;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),w.each(["toggle","show","hide"],function(e,t){var n=w.fn[t];w.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ut(t,!0),e,r,i)}}),w.each({slideDown:ut("show"),slideUp:ut("hide"),slideToggle:ut("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){w.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),w.timers=[],w.fx.tick=function(){var e,t=0,n=w.timers;for(nt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||w.fx.stop(),nt=void 0},w.fx.timer=function(e){w.timers.push(e),w.fx.start()},w.fx.interval=13,w.fx.start=function(){rt||(rt=!0,at())},w.fx.stop=function(){rt=null},w.fx.speeds={slow:600,fast:200,_default:400},w.fn.delay=function(t,n){return t=w.fx?w.fx.speeds[t]||t:t,n=n||"fx",this.queue(n,function(n,r){var i=e.setTimeout(n,t);r.stop=function(){e.clearTimeout(i)}})},function(){var e=r.createElement("input"),t=r.createElement("select").appendChild(r.createElement("option"));e.type="checkbox",h.checkOn=""!==e.value,h.optSelected=t.selected,(e=r.createElement("input")).value="t",e.type="radio",h.radioValue="t"===e.value}();var dt,ht=w.expr.attrHandle;w.fn.extend({attr:function(e,t){return z(this,w.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){w.removeAttr(this,e)})}}),w.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?w.prop(e,t,n):(1===o&&w.isXMLDoc(e)||(i=w.attrHooks[t.toLowerCase()]||(w.expr.match.bool.test(t)?dt:void 0)),void 0!==n?null===n?void w.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=w.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!h.radioValue&&"radio"===t&&N(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(M);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),dt={set:function(e,t,n){return!1===t?w.removeAttr(e,n):e.setAttribute(n,n),n}},w.each(w.expr.match.bool.source.match(/\w+/g),function(e,t){var n=ht[t]||w.find.attr;ht[t]=function(e,t,r){var i,o,a=t.toLowerCase();return r||(o=ht[a],ht[a]=i,i=null!=n(e,t,r)?a:null,ht[a]=o),i}});var gt=/^(?:input|select|textarea|button)$/i,yt=/^(?:a|area)$/i;w.fn.extend({prop:function(e,t){return z(this,w.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[w.propFix[e]||e]})}}),w.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&w.isXMLDoc(e)||(t=w.propFix[t]||t,i=w.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=w.find.attr(e,"tabindex");return t?parseInt(t,10):gt.test(e.nodeName)||yt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),h.optSelected||(w.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),w.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){w.propFix[this.toLowerCase()]=this});function vt(e){return(e.match(M)||[]).join(" ")}function mt(e){return e.getAttribute&&e.getAttribute("class")||""}function xt(e){return Array.isArray(e)?e:"string"==typeof e?e.match(M)||[]:[]}w.fn.extend({addClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).addClass(e.call(this,t,mt(this)))});if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},removeClass:function(e){var t,n,r,i,o,a,s,u=0;if(g(e))return this.each(function(t){w(this).removeClass(e.call(this,t,mt(this)))});if(!arguments.length)return this.attr("class","");if((t=xt(e)).length)while(n=this[u++])if(i=mt(n),r=1===n.nodeType&&" "+vt(i)+" "){a=0;while(o=t[a++])while(r.indexOf(" "+o+" ")>-1)r=r.replace(" "+o+" "," ");i!==(s=vt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(e,t){var n=typeof e,r="string"===n||Array.isArray(e);return"boolean"==typeof t&&r?t?this.addClass(e):this.removeClass(e):g(e)?this.each(function(n){w(this).toggleClass(e.call(this,n,mt(this),t),t)}):this.each(function(){var t,i,o,a;if(r){i=0,o=w(this),a=xt(e);while(t=a[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else void 0!==e&&"boolean"!==n||((t=mt(this))&&J.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||!1===e?"":J.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&(" "+vt(mt(n))+" ").indexOf(t)>-1)return!0;return!1}});var bt=/\r/g;w.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=g(e),this.each(function(n){var i;1===this.nodeType&&(null==(i=r?e.call(this,n,w(this).val()):e)?i="":"number"==typeof i?i+="":Array.isArray(i)&&(i=w.map(i,function(e){return null==e?"":e+""})),(t=w.valHooks[this.type]||w.valHooks[this.nodeName.toLowerCase()])&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return(t=w.valHooks[i.type]||w.valHooks[i.nodeName.toLowerCase()])&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:"string"==typeof(n=i.value)?n.replace(bt,""):null==n?"":n}}}),w.extend({valHooks:{option:{get:function(e){var t=w.find.attr(e,"value");return null!=t?t:vt(w.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!N(n.parentNode,"optgroup"))){if(t=w(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=w.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=w.inArray(w.valHooks.option.get(r),o)>-1)&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),w.each(["radio","checkbox"],function(){w.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=w.inArray(w(e).val(),t)>-1}},h.checkOn||(w.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),h.focusin="onfocusin"in e;var wt=/^(?:focusinfocus|focusoutblur)$/,Tt=function(e){e.stopPropagation()};w.extend(w.event,{trigger:function(t,n,i,o){var a,s,u,l,c,p,d,h,v=[i||r],m=f.call(t,"type")?t.type:t,x=f.call(t,"namespace")?t.namespace.split("."):[];if(s=h=u=i=i||r,3!==i.nodeType&&8!==i.nodeType&&!wt.test(m+w.event.triggered)&&(m.indexOf(".")>-1&&(m=(x=m.split(".")).shift(),x.sort()),c=m.indexOf(":")<0&&"on"+m,t=t[w.expando]?t:new w.Event(m,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=x.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+x.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),n=null==n?[t]:w.makeArray(n,[t]),d=w.event.special[m]||{},o||!d.trigger||!1!==d.trigger.apply(i,n))){if(!o&&!d.noBubble&&!y(i)){for(l=d.delegateType||m,wt.test(l+m)||(s=s.parentNode);s;s=s.parentNode)v.push(s),u=s;u===(i.ownerDocument||r)&&v.push(u.defaultView||u.parentWindow||e)}a=0;while((s=v[a++])&&!t.isPropagationStopped())h=s,t.type=a>1?l:d.bindType||m,(p=(J.get(s,"events")||{})[t.type]&&J.get(s,"handle"))&&p.apply(s,n),(p=c&&s[c])&&p.apply&&Y(s)&&(t.result=p.apply(s,n),!1===t.result&&t.preventDefault());return t.type=m,o||t.isDefaultPrevented()||d._default&&!1!==d._default.apply(v.pop(),n)||!Y(i)||c&&g(i[m])&&!y(i)&&((u=i[c])&&(i[c]=null),w.event.triggered=m,t.isPropagationStopped()&&h.addEventListener(m,Tt),i[m](),t.isPropagationStopped()&&h.removeEventListener(m,Tt),w.event.triggered=void 0,u&&(i[c]=u)),t.result}},simulate:function(e,t,n){var r=w.extend(new w.Event,n,{type:e,isSimulated:!0});w.event.trigger(r,null,t)}}),w.fn.extend({trigger:function(e,t){return this.each(function(){w.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return w.event.trigger(e,t,n,!0)}}),h.focusin||w.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){w.event.simulate(t,e.target,w.event.fix(e))};w.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=J.access(r,t);i||r.addEventListener(e,n,!0),J.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=J.access(r,t)-1;i?J.access(r,t,i):(r.removeEventListener(e,n,!0),J.remove(r,t))}}});var Ct=e.location,Et=Date.now(),kt=/\?/;w.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||w.error("Invalid XML: "+t),n};var St=/\[\]$/,Dt=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;function jt(e,t,n,r){var i;if(Array.isArray(t))w.each(t,function(t,i){n||St.test(e)?r(e,i):jt(e+"["+("object"==typeof i&&null!=i?t:"")+"]",i,n,r)});else if(n||"object"!==x(t))r(e,t);else for(i in t)jt(e+"["+i+"]",t[i],n,r)}w.param=function(e,t){var n,r=[],i=function(e,t){var n=g(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(Array.isArray(e)||e.jquery&&!w.isPlainObject(e))w.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},w.fn.extend({serialize:function(){return w.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=w.prop(this,"elements");return e?w.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!w(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=w(this).val();return null==n?null:Array.isArray(n)?w.map(n,function(e){return{name:t.name,value:e.replace(Dt,"\r\n")}}):{name:t.name,value:n.replace(Dt,"\r\n")}}).get()}});var qt=/%20/g,Lt=/#.*$/,Ht=/([?&])_=[^&]*/,Ot=/^(.*?):[ \t]*([^\r\n]*)$/gm,Pt=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Mt=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Wt={},$t="*/".concat("*"),Bt=r.createElement("a");Bt.href=Ct.href;function Ft(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(M)||[];if(g(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function _t(e,t,n,r){var i={},o=e===Wt;function a(s){var u;return i[s]=!0,w.each(e[s]||[],function(e,s){var l=s(t,n,r);return"string"!=typeof l||o||i[l]?o?!(u=l):void 0:(t.dataTypes.unshift(l),a(l),!1)}),u}return a(t.dataTypes[0])||!i["*"]&&a("*")}function zt(e,t){var n,r,i=w.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&w.extend(!0,e,r),e}function Xt(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function Ut(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}w.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Pt.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":$t,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":w.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?zt(zt(e,w.ajaxSettings),t):zt(w.ajaxSettings,e)},ajaxPrefilter:Ft(It),ajaxTransport:Ft(Wt),ajax:function(t,n){"object"==typeof t&&(n=t,t=void 0),n=n||{};var i,o,a,s,u,l,c,f,p,d,h=w.ajaxSetup({},n),g=h.context||h,y=h.context&&(g.nodeType||g.jquery)?w(g):w.event,v=w.Deferred(),m=w.Callbacks("once memory"),x=h.statusCode||{},b={},T={},C="canceled",E={readyState:0,getResponseHeader:function(e){var t;if(c){if(!s){s={};while(t=Ot.exec(a))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return c?a:null},setRequestHeader:function(e,t){return null==c&&(e=T[e.toLowerCase()]=T[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==c&&(h.mimeType=e),this},statusCode:function(e){var t;if(e)if(c)E.always(e[E.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||C;return i&&i.abort(t),k(0,t),this}};if(v.promise(E),h.url=((t||h.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),h.type=n.method||n.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(M)||[""],null==h.crossDomain){l=r.createElement("a");try{l.href=h.url,l.href=l.href,h.crossDomain=Bt.protocol+"//"+Bt.host!=l.protocol+"//"+l.host}catch(e){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=w.param(h.data,h.traditional)),_t(It,h,n,E),c)return E;(f=w.event&&h.global)&&0==w.active++&&w.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!Mt.test(h.type),o=h.url.replace(Lt,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(qt,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(kt.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Ht,"$1"),d=(kt.test(o)?"&":"?")+"_="+Et+++d),h.url=o+d),h.ifModified&&(w.lastModified[o]&&E.setRequestHeader("If-Modified-Since",w.lastModified[o]),w.etag[o]&&E.setRequestHeader("If-None-Match",w.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||n.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+$t+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(C="abort",m.add(h.complete),E.done(h.success),E.fail(h.error),i=_t(Wt,h,n,E)){if(E.readyState=1,f&&y.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(u=e.setTimeout(function(){E.abort("timeout")},h.timeout));try{c=!1,i.send(b,k)}catch(e){if(c)throw e;k(-1,e)}}else k(-1,"No Transport");function k(t,n,r,s){var l,p,d,b,T,C=n;c||(c=!0,u&&e.clearTimeout(u),i=void 0,a=s||"",E.readyState=t>0?4:0,l=t>=200&&t<300||304===t,r&&(b=Xt(h,E,r)),b=Ut(h,b,E,l),l?(h.ifModified&&((T=E.getResponseHeader("Last-Modified"))&&(w.lastModified[o]=T),(T=E.getResponseHeader("etag"))&&(w.etag[o]=T)),204===t||"HEAD"===h.type?C="nocontent":304===t?C="notmodified":(C=b.state,p=b.data,l=!(d=b.error))):(d=C,!t&&C||(C="error",t<0&&(t=0))),E.status=t,E.statusText=(n||C)+"",l?v.resolveWith(g,[p,C,E]):v.rejectWith(g,[E,C,d]),E.statusCode(x),x=void 0,f&&y.trigger(l?"ajaxSuccess":"ajaxError",[E,h,l?p:d]),m.fireWith(g,[E,C]),f&&(y.trigger("ajaxComplete",[E,h]),--w.active||w.event.trigger("ajaxStop")))}return E},getJSON:function(e,t,n){return w.get(e,t,n,"json")},getScript:function(e,t){return w.get(e,void 0,t,"script")}}),w.each(["get","post"],function(e,t){w[t]=function(e,n,r,i){return g(n)&&(i=i||r,r=n,n=void 0),w.ajax(w.extend({url:e,type:t,dataType:i,data:n,success:r},w.isPlainObject(e)&&e))}}),w._evalUrl=function(e){return w.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},w.fn.extend({wrapAll:function(e){var t;return this[0]&&(g(e)&&(e=e.call(this[0])),t=w(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return g(e)?this.each(function(t){w(this).wrapInner(e.call(this,t))}):this.each(function(){var t=w(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=g(e);return this.each(function(n){w(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){w(this).replaceWith(this.childNodes)}),this}}),w.expr.pseudos.hidden=function(e){return!w.expr.pseudos.visible(e)},w.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},w.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Vt={0:200,1223:204},Gt=w.ajaxSettings.xhr();h.cors=!!Gt&&"withCredentials"in Gt,h.ajax=Gt=!!Gt,w.ajaxTransport(function(t){var n,r;if(h.cors||Gt&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);n=function(e){return function(){n&&(n=r=s.onload=s.onerror=s.onabort=s.ontimeout=s.onreadystatechange=null,"abort"===e?s.abort():"error"===e?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(Vt[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=n(),r=s.onerror=s.ontimeout=n("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{s.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),w.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),w.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return w.globalEval(e),e}}}),w.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),w.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(i,o){t=w("<script>").prop({charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&o("error"===e.type?404:200,e.type)}),r.head.appendChild(t[0])},abort:function(){n&&n()}}}});var Yt=[],Qt=/(=)\?(?=&|$)|\?\?/;w.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Yt.pop()||w.expando+"_"+Et++;return this[e]=!0,e}}),w.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=!1!==t.jsonp&&(Qt.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&Qt.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0])return i=t.jsonpCallback=g(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(Qt,"$1"+i):!1!==t.jsonp&&(t.url+=(kt.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||w.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){void 0===o?w(e).removeProp(i):e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,Yt.push(i)),a&&g(o)&&o(a[0]),a=o=void 0}),"script"}),h.createHTMLDocument=function(){var e=r.implementation.createHTMLDocument("").body;return e.innerHTML="<form></form><form></form>",2===e.childNodes.length}(),w.parseHTML=function(e,t,n){if("string"!=typeof e)return[];"boolean"==typeof t&&(n=t,t=!1);var i,o,a;return t||(h.createHTMLDocument?((i=(t=r.implementation.createHTMLDocument("")).createElement("base")).href=r.location.href,t.head.appendChild(i)):t=r),o=A.exec(e),a=!n&&[],o?[t.createElement(o[1])]:(o=xe([e],t,a),a&&a.length&&w(a).remove(),w.merge([],o.childNodes))},w.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return s>-1&&(r=vt(e.slice(s)),e=e.slice(0,s)),g(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),a.length>0&&w.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?w("<div>").append(w.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},w.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){w.fn[t]=function(e){return this.on(t,e)}}),w.expr.pseudos.animated=function(e){return w.grep(w.timers,function(t){return e===t.elem}).length},w.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l,c=w.css(e,"position"),f=w(e),p={};"static"===c&&(e.style.position="relative"),s=f.offset(),o=w.css(e,"top"),u=w.css(e,"left"),(l=("absolute"===c||"fixed"===c)&&(o+u).indexOf("auto")>-1)?(a=(r=f.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),g(t)&&(t=t.call(e,n,w.extend({},s))),null!=t.top&&(p.top=t.top-s.top+a),null!=t.left&&(p.left=t.left-s.left+i),"using"in t?t.using.call(e,p):f.css(p)}},w.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){w.offset.setOffset(this,e,t)});var t,n,r=this[0];if(r)return r.getClientRects().length?(t=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:t.top+n.pageYOffset,left:t.left+n.pageXOffset}):{top:0,left:0}},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===w.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===w.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),i.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-w.css(r,"marginTop",!0),left:t.left-i.left-w.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===w.css(e,"position"))e=e.offsetParent;return e||be})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;w.fn[e]=function(r){return z(this,function(e,r,i){var o;if(y(e)?o=e:9===e.nodeType&&(o=e.defaultView),void 0===i)return o?o[t]:e[r];o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):e[r]=i},e,r,arguments.length)}}),w.each(["top","left"],function(e,t){w.cssHooks[t]=_e(h.pixelPosition,function(e,n){if(n)return n=Fe(e,t),We.test(n)?w(e).position()[t]+"px":n})}),w.each({Height:"height",Width:"width"},function(e,t){w.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){w.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),s=n||(!0===i||!0===o?"margin":"border");return z(this,function(t,n,i){var o;return y(t)?0===r.indexOf("outer")?t["inner"+e]:t.document.documentElement["client"+e]:9===t.nodeType?(o=t.documentElement,Math.max(t.body["scroll"+e],o["scroll"+e],t.body["offset"+e],o["offset"+e],o["client"+e])):void 0===i?w.css(t,n,s):w.style(t,n,i,s)},t,a?i:void 0,a)}})}),w.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,t){w.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),w.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),w.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}}),w.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),g(e))return r=o.call(arguments,2),i=function(){return e.apply(t||this,r.concat(o.call(arguments)))},i.guid=e.guid=e.guid||w.guid++,i},w.holdReady=function(e){e?w.readyWait++:w.ready(!0)},w.isArray=Array.isArray,w.parseJSON=JSON.parse,w.nodeName=N,w.isFunction=g,w.isWindow=y,w.camelCase=G,w.type=x,w.now=Date.now,w.isNumeric=function(e){var t=w.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},"function"==typeof define&&define.amd&&define("jquery",[],function(){return w});var Jt=e.jQuery,Kt=e.$;return w.noConflict=function(t){return e.$===w&&(e.$=Kt),t&&e.jQuery===w&&(e.jQuery=Jt),w},t||(e.jQuery=e.$=w),w});
}
//Included:lib/300.castelog.v1.inicializacion.part.js
/*lib:castelog@0.0.1*/
Castelog = (function(factory, scope) {
const output = factory.call(scope);
if(typeof window === "object") {
window["Castelog"] = output;
}
if(typeof global === "object") {
global["Castelog"] = output;
}
if(typeof module === "object") {
module.exports = output;
}
return output;
})(function() {
if((typeof(window) !== "undefined") && (typeof(window.Castelog) !== "undefined")) {
return window.Castelog;
}
if((typeof(global) !== "undefined") && (typeof(global.Castelog) !== "undefined")) {
return global.Castelog;
}
const globalmente = (typeof(window) !== "undefined") ? window : (typeof(global) !== "undefined") ? global : this;
const Castelog = {
globalmente,
metodos: {},
modulos: {},
variables: {
noop: function() {},
mysql2: undefined,
Automatic_http_rest_api_interface: Automatic_http_rest_api_interface,
RanasDB: typeof globalmente.RanasDB !== "undefined" ? globalmente.RanasDB : undefined,
SimplestDB: globalmente.SimplestDB,
axios: typeof window !== "object" ? require("axios") : globalmente.axios,
ejs: globalmente.ejs,
globales: {
entorno: "development"
},
alfabeto_ingles: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),
Entorno_de_testeo: function(parametros = {}) {
Object.assign(this, parametros);
return this;
}
},
compilacion: {
"ruta_del_sistema": "/home/carlos/Escritorio/Nuevo/Castelog/castelog-core",
"sistema_operativo": "",
"fecha": "2022/12/50 19:50.30.110"
}
};
return Castelog;
}, this);
//Included:lib/320.castelog.v1.metodos.un_filtrado_por.js
Castelog.metodos.un_filtrado_por = function(lista, filtro) {
if(typeof lista === "object") {
if(Array.isArray(lista)) {
return lista.reduce((output, value, index) => {
const otherValue = filtro(value, index, index, output, lista);
if (otherValue === true) {
output.push(value);
}
return output;
}, []);
} else {
const keys = Object.keys(lista);
return lista.reduce((output, key, index) => {
const value = lista[key];
if(filtro(value, key, index, output, lista)) {
output[key] = value;
}
return output;
}, {});
}
} else throw new Error("Required argument «lista» to be an array in order to «Castelog.metodos.un_filtrado_por»")
};
//Included:lib/321.castelog.v1.metodos.un_mapeado_por.js
Castelog.metodos.un_mapeado_por = function (lista, mapeo) {
if (typeof lista === "object") {
if (Array.isArray(lista)) {
return lista.reduce((output, value, index) => {
const otherValue = mapeo(value, index, index, output, lista);
if (typeof otherValue !== "undefined") {
output.push(value);
}
return output;
}, []);
} else {
const keys = Object.keys(lista);
return keys.reduce((output, key, index) => {
const value = lista[key];
const otherValue = mapeo(value, key, index, output, lista);
if (typeof otherValue !== "undefined") {
output[key] = value;
}
return output;
}, {});
}
} else throw new Error("Required argument «lista» to be an array in order to «Castelog.metodos.un_mapeado_por»")
};
//Included:lib/322.castelog.v1.metodos.un_reducido_por.js
Castelog.metodos.un_reducido_por = function (lista, reduccion, base = false) {
if (typeof lista === "object") {
if (Array.isArray(lista)) {
return lista.reduce((output, value, index) => {
const otherValue = reduccion(value, output, index, index, lista);
if (typeof otherValue !== "undefined") {
output = otherValue;
}
return output;
}, base || []);
} else {
const keys = Object.keys(lista);
return keys.reduce((output, key, index) => {
const value = lista[key];
const otherValue = reduccion(value, output, key, index, lista);
if (typeof otherValue !== "undefined") {
output = otherValue;
}
return output;
}, base || {});
}
} else throw new Error("Required argument «lista» to be an array in order to «Castelog.metodos.un_reducido_por»")
};
//Included:lib/402.castelog.v1.variables.un_servidor_activo_de_control_remoto.part.js
Castelog.variables.ServidorActivoDeControlRemoto = class {
constructor(configurations, directory) {
this.activos = [];
this.pasivos = [];
Object.assign(this, { configurations, directory });
}
async start() {
try {
this.on_initialize_configurations();
this.on_initialize_http_server();
this.on_initialize_socket_io_server();
await this.on_run_http_server();
} catch(error) {
console.log("Error en «Castelog.variables.ServidorActivoDeControlRemoto.prototype.start»:", error)
throw error;
}
}
on_initialize_configurations() {
// @TOREVIEW...
Object.assign(this.configurations, {
"nativo.socket.host": "127.0.0.1",
"nativo.socket.port": "9989",
"nativo.socket.path": "/centralita/de/control/remoto"
}, this.configurations);
}
on_initialize_http_server() {
// @TOREVIEW...
this.http_server = undefined;
if(typeof this.configurations["nativo.http.server"] !== "undefined") {
this.http_server = this.configurations["nativo.http.server"];
} else {
this.http_server = require("http").createServer((...args) => this.on_respond_request(...args));
}
}
on_initialize_socket_io_server() {
// @TOREVIEW...
this.socket_server = require("socket.io").io(this.http_server);
this.socket_server.on("connect", socket_client => {
if(this.configurations["nativo.socket.events"]) {
const allEvents = this.configurations["nativo.socket.events"];
const eventsKeys = Object.keys(allEvents);
for(let indexEvent = 0; indexEvent < eventsKeys.length; indexEvent++) {
const eventKey = eventsKeys[indexEvent];
const eventValue = allEvents[eventKey];
const [ event_id, event_function ] = eventValue;
socket_client.on(event_id, event_function);
}
}
socket_client.on("unregister passive device", (data) => {
const { user, password } = data;
// filter socket_server.?getAllConnections
// so you can get the user+password key checked
// then return assigned passive devices
socket_client.emit("unregister passive device response", { error: "not yet available" });
});
socket_client.on("register passive device", (data) => {
const { user, password } = data;
// filter socket_server.?getAllConnections
// so you can get the user+password key checked
// then return assigned passive devices
socket_client.emit("register passive device response", { error: "not yet available" });
});
socket_client.on("list passive devices", (data) => {
const { } = data;
// filter socket_server.?getAllConnections
// so you can get the user+password key checked
// then return assigned passive devices
socket_client.emit("list passive devices response", { error: "not yet available" });
});
socket_client.on("execute on passive devices", (data) => {
const { targets, code } = data;
// filter socket_server.?getAllConnections
// so you can get the user+password key checked
// then return assigned passive devices
socket_client.emit("execute on passive devices response", { error: "not yet available" });
});
});
}
on_run_http_server() {
// @TOREVIEW...
const port = this.configurations["nativo.socket.port"] || 9989;
const host = this.configurations["nativo.socket.host"] || "127.0.0.1";
const path = this.configurations["nativo.socket.path"] || "/";
return new Promise((ok, fail) => {
try {
this.http_server.listen(port, host, () => {
const socket_url = "ws://" + host + ":" + port + path;
console.log("Un servidor activo de control remoto en:\n - " + socket_url);
return ok({ http_server: this.http_server, socket_io: this.socket_server, socket_url });
});
} catch (error) {
return fail(error);
}
});
}
on_respond_request(request, response) {
// @TOREVIEW...
response.write("This an active remote control server of Castelog.");
return response.end();
}
};
//Included:lib/403.castelog.v1.variables.un_cliente_activo_de_control_remoto.part.js
Castelog.variables.ClienteActivoDeControlRemoto = class {
constructor(configuraciones, directorio) {
Object.assign(this, { configuraciones, directorio });
}
async start() {
try {
this.on_initialize_configurations();
this.on_initialize_connection();
} catch (error) {
console.log("Error en «Castelog.variables.ClienteActivoDeControlRemoto.prototype.start»:", error)
throw error;
}
}
on_initialize_configurations() {
Object.assign(this.configurations, {
"nativo.socket.host": "127.0.0.1",
"nativo.socket.port": "9985",
"nativo.socket.path": "/centralita/de/control/remoto"
}, this.configurations);
}
on_initialize_connection() {
try {
// @TOREVIEW...
if(this.connection) {
return this.connection;
}
const socket_port = this.configurations["nativo.socket.port"] || 9989;
const socket_host = this.configurations["nativo.socket.host"] || "127.0.0.1";
const socket_path = this.configurations["nativo.socket.path"] || "/";
const socket_url = "ws://" + socket_host + ":" + socket_port + socket_path
this.connection = require("socket.io-client").io(socket_url);
this.connection.on("list passive devices response", (parameters) => {
console.log("list passive devices response", parameters);
});
this.connection.on("execute on passive device response", (parameters) => {
console.log("execute on passive device response", parameters);
});
} catch (error) {
console.log("Error en «Castelog.variables.ClienteActivoDeControlRemoto.prototype.on_initialize_connection»:", error)
throw error;
}
}
async command_to_list_passive_devices(self_id, self_password) {
try {
// @TODO...
} catch(error) {
}
}
async command_to_execute_on_passive_device(target_id, target_password, target_code, target_metadata) {
try {
// @TODO...
} catch (error) {
// @TODO...
}
}
};
//Included:lib/404.castelog.v1.variables.un_cliente_pasivo_de_control_remoto.part.js
Castelog.variables.ClientePasivoDeControlRemoto = class {
constructor(configuraciones, directorio) {
Object.assign(this, { configuraciones, directorio });
}
async start() {
try {
this.on_initialize_configurations();
this.on_initialize_connection();
} catch (error) {
console.log("Error en «Castelog.variables.ClientePasivoDeControlRemoto.prototype.start»:", error)
throw error;
}
}
on_initialize_configurations() {
Object.assign(this.configurations, {
"nativo.socket.host": "127.0.0.1",
"nativo.socket.port": "9985",
"nativo.socket.path": "/centralita/de/control/remoto"
}, this.configurations);
}
on_initialize_connection() {
try {
// @TOREVIEW...
if(this.connection) {
return this.connection;
}
const socket_port = this.configurations["nativo.socket.port"] || 9989;
const socket_host = this.configurations["nativo.socket.host"] || "127.0.0.1";
const socket_path = this.configurations["nativo.socket.path"] || "/";
const socket_url = "ws://" + socket_host + ":" + socket_port + socket_path;
const socket_id = "abcdef";
this.connection = require("socket.io-client").io(socket_url);
this.connection.on("connect", (parameters) => {
console.log("connect", parameters);
this.connection.emit("register passive device", { name: socket_id, password: socket_id });
});
this.connection.on("disconnect", (parameters) => {
console.log("disconnect", parameters);
this.connection.emit("unregister passive device", { name: socket_id, password: socket_id });
});
this.connection.on("register passive device response", () => {
console.log("ok: current device was registered as passive device");
});
this.connection.on("unregister passive device response", () => {
console.log("ok: current device was unregistered as passive device");
});
this.connection.on("execute on passive device remotely", (parameters) => {
console.log("execute on passive device remotely", parameters);
});
} catch (error) {
console.log("Error en «Castelog.variables.ClientePasivoDeControlRemoto.prototype.on_initialize_connection»:", error)
throw error;
}
}
};
//Included:lib/405.castelog.v1.variables.un_servidor_pasivo_de_control_remoto.part.js
Castelog.variables.ServidorPasivoDeControlRemoto = class {
constructor(configurations, directory) {
this.activos = [];
this.pasivos = [];
Object.assign(this, { configurations, directory });
}
async start() {
try {
this.on_initialize_configurations();
this.on_initialize_http_server();
this.on_initialize_socket_io_server();
await this.on_run_http_server();
} catch(error) {
this.log("Error en «Castelog.variables.ServidorPasivoDeControlRemoto.prototype.start»:", error)
throw error;
}
}
on_initialize_configurations() {
Object.assign(this.configurations, {
"nativo.socket.host": "127.0.0.1",
"nativo.socket.port": "9985",
"nativo.socket.path": "/centralita/de/control/remoto",
"nativo.socket.log": true,
"nativo.server.host": "127.0.0.1",
"nativo.server.port": "9987",
"nativo.server.path": "/centralita/de/control/remoto",
"nativo.server.log": true,
}, this.configurations);
}
on_initialize_http_server() {
this.http_server = undefined;
if(typeof this.configurations["nativo.http.server"] !== "undefined") {
this.http_server = this.configurations["nativo.http.server"];
} else {
this.http_server = require("http").createServer((...args) => this.on_respond_request(...args));
}
}
on_initialize_socket_io_server() {
this.socket_server = require("socket.io").io(this.http_server);
this.socket_server.on("connect", socket_client => {
if(this.configurations["nativo.socket.events"]) {
const allEvents = this.configurations["nativo.socket.events"];
const eventsKeys = Object.keys(allEvents);
for(let indexEvent = 0; indexEvent < eventsKeys.length; indexEvent++) {
const eventKey = eventsKeys[indexEvent];
const eventValue = allEvents[eventKey];
const [ event_id, event_function ] = eventValue;
socket_client.on(event_id, event_function);
}
}
socket_client.on("execute on passive device remotely", (data) => {
const { code } = data;
eval(code);
});
});
}
on_run_http_server() {
const port = this.configurations["nativo.socket.port"] || 9989;
const host = this.configurations["nativo.socket.host"] || "127.0.0.1";
const path = this.configurations["nativo.socket.path"] || "/";
return new Promise((ok, fail) => {
try {
this.http_server.listen(port, host, () => {
const socket_url = "ws://" + host + ":" + port + path;
this.log("New sockets (passive) app listening on: " + socket_url);
return ok({ http_server: this.http_server, socket_io: this.socket_server, socket_url });
});
} catch (error) {
return fail(error);
}
});
}
on_respond_request(request, response) {
response.write("This a passive remote control server of Castelog.");
return response.end();
}
log(...args) {
if(this.configurations["nativo.socket.log"]) {
console.log(...args);
}
}
};
//Included:lib/406.castelog.v1.variables.una_aplicacion_sintactica_universal.part.js
Castelog.variables.Aplicacion_sintactica_universal = class {
static get DEFAULT_CONFIGURATION() {
return {
separador: "."
};
}
constructor(comandos, configuracion) {
this.comandos = comandos;
this.configuracion = Object.assign({}, this.constructor.DEFAULT_CONFIGURATION, configuracion);
}
execute(command, parameters) {
try {
const command_path = command.split(this.configuracion.separador);
let value = this.comandos;
for(let index = 0; index < command_path.length; index++) {
const command_step = command_path[index];
if(!(command_step in value)) {
throw new Error("Required command step «" + command_step + "» on command path «" + command_path.splice(0, index).join(this.configuracion.separador) + "» in order to «Castelog.variables.Aplicacion_sintactica_universal.execute» with command «" + command + "»");
}
value = value[command_step];
}
if(!(value instanceof Castelog.variables.Punto_sintactico_universal)) {
throw new Error("Required command path «" + command + "» to be a «Castelog.variables.Punto_sintactico_universal» in order to «Castelog.variables.Aplicacion_sintactica_universal.execute» with command «" + command + "»");
}
return value.run(parameters);
} catch(error) {
return this.onError(error, command, parameters);
}
}
onError(error, command, parameters) {
console.log("Error ejecutando comando «" + command + "» de aplicación sintáctica universal:", error);
throw error;
}
};
//Included:lib/407.castelog.v1.variables.un_punto_sintactico_universal.part.js
Castelog.variables.Punto_sintactico_universal = class {
constructor(comando, onError) {
this.comando = comando;
this.onError = onError ? onError : (error, command, parameters) => {
console.log("Error ejecutando comando de punto sintáctico universal «" + command + "»:", error);
throw error;
};
}
run(parametros) {
try {
return this.comando(parametros);
} catch(error) {
return this.onError(error, command, parameters);
}
}
};
//Included:lib/408.01.castelog.v1.variables.un_utilities_helper_para_mysql2.part.js
Castelog.variables.un_utilities_helper_para_mysql2 = class {
constructor() {}
escapeValue(text) {
if (typeof text !== "string") throw new Error("Required text to be a string in order to «escapeValue«");
return require("mysql2").escape(text);
}
escapeId(id) {
if (typeof id !== "string") throw new Error("Required id to be a string in order to «escapeId«");
return require("mysql2").escapeId(id);
}
escapeToOperator(operator) {
const validOperators = {
"<": " < ",
"es menos que": " < ",
">": " > ",
"es más que": " > ",
"<=": " <= ",
"es menos o igual que": " <= ",
">=": " >= ",
"es más o igual que": " >= ",
"=": " = ",
"es igual que": " = ",
"!=": " != ",
"no es igual que": " != "
};
if(operator in validOperators) {
return validOperators[operator];
}
throw new Error("Required «operator» to be a valid known operator in order to «escapeToOperator»");
}
escapeToWhereExpression(list) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToWhereExpression»");
const mysql2 = require("mysql2");
let out = "";
out += "WHERE 1 = 1";
for(let index = 0; index < list.length; index++) {
const item = list[index];
const [ subject, operator, predicate, predicateOptions = { as: "value" } ] = item;
out += "\n AND ";
out += mysql2.escapeId(subject);
out += this.escapeToOperator(operator);
if(!("as" in predicateOptions)) {
predicateOptions.as = "value";
}
if(predicateOptions.as === "value") {
out += this.escapeValue(predicate);
} else if (predicateOptions.as === "id") {
out += this.escapeId(predicate);
} else if (predicateOptions.as === "list") {
out += this.escapeToValuesExpression(predicate);
} else if (predicateOptions.as === "null") {
out += "null";
} else throw new Error("Required predicateOption to be a valid known predicate option for as property in order to «escapeToWhereExpression»");
}
return out;
}
escapeToFieldsExpression(list) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToFieldsExpression«");
let out = "(";
for (let index = 0; index < list.length; index++) {
const item = list[index];
out += (index !== 0) ? ", " : "";
out += this.escapeId(item);
}
out += ")";
return out;
}
escapeToValuesExpression(list) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToValuesExpression«");
let out = "(";
for(let index = 0; index < list.length; index++) {
const item = list[index];
out += (index !== 0) ? ", " : "";
out += this.escapeValue(item);
}
out += ")";
return out;
}
escapeToSetValuesExpression(values) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToSetValuesExpression«");
const list = Object.keys(values);
for (let index = 0; index < list.length; index++) {
const key = list[index];
const value = values[key];
out += (index !== 0) ? ", " : "";
out += this.escapeId(key);
out += " = ";
out += this.escapeValue(value);
}
return out;
}
escapeToIdsArray(list) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToIdsArray«");
return list.map(item => require("mysql2").escapeId(item));
}
escapeToValuesArray(list) {
if (!Array.isArray(list)) throw new Error("Required list to be an array in order to «escapeToValuesArray«");
return list.map(item => require("mysql2").escape(item));
}
};
//Included:lib/408.02.castelog.v1.variables.un_proxy_de_pool_de_conexiones_para_mysql2.part.js
Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2 = class extends Castelog.variables.un_utilities_helper_para_mysql2 {
constructor(pool, options = {}) {
super();
this.pool = pool;
Object.assign(this, options);
}
getConnection() {
return this.pool.getConnection();
}
create(options) {
return new Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2(this.pool, options);
}
// Schema:
async getSchema() {
try {
return this.schema;
} catch (error) {
throw error;
}
}
buildSelectQuery(modelo, filtrando, ordenando, agrupando, paginando, db, objetivo) {
let query = "";
query += "SELECT * FROM ";
query += this.escapeId(modelo);
query += "\n";
query += this.escapeToWhereExpression(filtrando);
if(Array.isArray(ordenando) && ordenando.length) {
query += "\n ORDER BY ";
for(let index = 0; index < ordenando.length; index++) {
const orden = ordenando[index];
const isDesc = orden.startsWith("!");
const columna = isDesc ? orden.substr(1) : orden;
if(index !== 0) {
query += ", ";
}
query += "" + this.escapeId(columna) + (isDesc ? " DESC" : " ASC");
}
}
if(Array.isArray(paginando)) {
const [ page = 1, items = 20 ] = paginando;
const offset = page * (items - 1);
query += "\n LIMIT " + items;
query += "\n OFFSET " + offset;
}
return query;
}
// Select
async select(modelo, filtrando, ordenando, agrupando, paginando, db = "system", adaptador = Castelog.variables.SimplestDB, objetivo = "a varios ítems") {
try {
if(objetivo === "a varios ítems") {
return await this.select_many(modelo, filtrando, ordenando, agrupando, paginando, db, adaptador);
} else if(objetivo === "a un ítem") {
return await this.select_one(modelo, filtrando, ordenando, agrupando, paginando, db, adaptador);
} else if(objetivo === "al primer ítem") {
return await this.select_first(modelo, filtrando, ordenando, agrupando, paginando, db, adaptador);
} else if(objetivo === "al último ítem") {
return await this.select_last(modelo, filtrando, ordenando, agrupando, paginando, db, adaptador);
}
} catch (error) {
throw error;
}
}
async select_many(modelo, filtrando, ordenando, agrupando, paginando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = this.buildSelectQuery(modelo, filtrando, ordenando, agrupando, paginando, db);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
async select_one(modelo, filtrando, ordenando, agrupando, paginando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = this.buildSelectQuery(modelo, filtrando, ordenando, agrupando, paginando, db);
const result = await connection.query(query);
const [ output, fields ] = result;
if(output.length > 1) throw new Error("Required output to be 1 and no more than 1 row in order to «Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2.select_one»");
if(output.length === 0) return undefined;
const [row] = output;
return row;
} catch (error) {
throw error;
}
}
async select_first(modelo, filtrando, ordenando, agrupando, paginando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = this.buildSelectQuery(modelo, filtrando, ordenando, agrupando, paginando, db);
const result = await connection.query(query);
const [output, fields] = result;
if (output.length === 0) return undefined;
const [row] = output;
return row;
} catch (error) {
throw error;
}
}
async select_last(modelo, filtrando, ordenando, agrupando, paginando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = this.buildSelectQuery(modelo, filtrando, ordenando, agrupando, paginando, db);
const result = await connection.query(query);
const [output, fields] = result;
if (output.length === 0) return undefined;
const row = output.pop();
return row;
} catch (error) {
throw error;
}
}
// Insert
buildInsertManyQuery(modelo, items) {
if(items.length < 1) throw new Error("Required parameter «items» to be an array of 1 or more items in order to «buildInsertManyQuery»");
const [item] = items;
const columnas = Object.keys(item);
let query = "";
query += "INSERT INTO ";
query += this.escapeId(modelo);
query += "\n";
query += this.escapeToFieldsExpression(columnas);
query += " VALUES \n";
for(let index = 0; index < items.length; index++) {
const iteratedItem = items[index];
const values = Object.values(iteratedItem);
if(index !== 0) {
query += ",\n";
}
query += this.escapeToValuesExpression(values);
}
return query;
}
buildInsertOneQuery(modelo, item) {
const columnas = Object.keys(item);
const valores = Object.values(item);
let query = "";
query += "INSERT INTO ";
query += this.escapeId(modelo);
query += "\n";
query += this.escapeToFieldsExpression(columnas);
query += " VALUES \n";
query += this.escapeToValuesExpression(valores);
return query;
}
insert(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
return Array.isArray(valor) ? this.insert_many(modelo, valor, db, adaptador) : this.insert_one(modelo, valor, db, adaptador);
}
async insert_one(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildInsertOneQuery(modelo, valor);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
async insert_many(modelo, valores, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildInsertManyQuery(modelo, valores);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
// Update
async update(modelo, filtrando, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
return Array.isArray(filtrando) ? this.update_many(modelo, filtrando, valor, db, adaptador) : this.update_one(modelo, filtrando, valor, db, adaptador);
}
buildUpdateManyQuery(modelo, filtrando, valor) {
if (valor.length < 1) throw new Error("Required parameter «valor» to be an object in order to «buildUpdateManyQuery»");
let query = "";
query += "UPDATE ";
query += this.escapeId(modelo);
query += "\n" + this.escapeToWhereExpression(filtrando);
query += "\nSET\n";
query += this.escapeToSetValuesExpression(valor);
return query;
}
buildUpdateOneQuery(modelo, filtrando, valor) {
if (valor.length < 1) throw new Error("Required parameter «valor» to be an object in order to «buildUpdateOneQuery»");
let query = "";
query += "UPDATE ";
query += this.escapeId(modelo);
query += "\n" + this.escapeToWhereExpression(filtrando);
query += "\nSET\n";
query += this.escapeToSetValuesExpression(valor);
return query;
}
async update_one(modelo, filtrando, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildUpdateOneQuery(modelo, filtrando, valor);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
async update_many(modelo, filtrando, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildUpdateManyQuery(modelo, filtrando, valor);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
// Delete
async delete(modelo, filtrando, db = "system", adaptador = Castelog.variables.SimplestDB) {
return Array.isArray(filtrando) ? this.delete_many(modelo, filtrando, db, adaptador) : this.delete_one(modelo, filtrando, db, adaptador);
}
buildDeleteManyQuery(modelo, filtrando) {
let query = "";
query += "DELETE FROM ";
query += this.escapeId(modelo);
query += "\n" + this.escapeToWhereExpression(filtrando);
return query;
}
buildDeleteOneQuery(modelo, filtrando) {
if (filtrando.length < 1) throw new Error("Required parameter «filtrando» to be an array of 1 or more items in order to «buildDeleteOneQuery»");
let query = "";
query += "DELETE FROM ";
query += this.escapeId(modelo);
query += "\n" + this.escapeToWhereExpression(filtrando);
return query;
}
async delete_one(modelo, filtrando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildDeleteOneQuery(modelo, filtrando);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
async delete_many(modelo, filtrando, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
const query = await this.buildDeleteManyQuery(modelo, filtrando);
const result = await connection.query(query);
const [output, fields] = result;
return output;
} catch (error) {
throw error;
}
}
// Metacrud:
async add_table(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async add_column(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async add_database(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async execute_script(modelo, valor, db = "system", adaptador = Castelog.variables.SimplestDB) {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async alter_table() {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async alter_column() {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async drop_table() {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async drop_column() {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
async drop_database() {
try {
const connection = await this.getConnection();
// @TODO...
return { message: "This work is still to be done!" };
} catch (error) {
throw error;
}
}
};
//Included:lib/408.03.castelog.v1.variables.un_proxy_de_conexion_para_mysql2.part.js
Castelog.variables.un_proxy_de_conexion_para_mysql2 = class extends Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2 {
constructor(connection, options = {}) {
super();
this.connection = connection;
Object.assign(this, options);
}
getConnection() {
return this.connection;
}
create(options) {
return new Castelog.variables.un_proxy_de_conexion_para_mysql2(this.connection, options);
}
};
//Included:lib/501.castelog.v1.metodos.una_peticion_http.part.js
Castelog.variables.cliente_http = Castelog.variables.axios.create();
Castelog.metodos.una_peticion_http = function (url, method_p, data, headers, client = Castelog.variables.cliente_http, en_errores = console.log) {
const errorHandler = (typeof en_errores === "function") ? en_errores : error => console.log("Error en petición HTTP:", error);
const requests_client = (typeof client === "function") ? client : Castelog.variables.cliente_http;
try {
const method = method_p ? method_p.toLowerCase() : "get";
return requests_client[method](url, data, { headers }).catch(errorHandler);
} catch (error) {
return errorHandler(error) || error;
}
};
//Included:lib/502.castelog.v1.metodos.un_cacheo.part.js
Castelog.metodos.un_cacheo = function(clave, valor, condicion) {
let condicionFinal = condicion;
if(typeof condicion === "function") {
condicionFinal = condicion();
}
NoSeRefresca:
if(!condicionFinal) {
const cacheDB = Castelog.variables.SimplestDB.getCache();
const coincidencias = cacheDB.select("cache", item => item.key === clave);
const coincidenciasIds = Object.keys(coincidencias);
if (coincidenciasIds.length === 0) {
break NoSeRefresca;
} else if (coincidenciasIds.length > 1) {
throw new Error("Clave de cacheo «" + clave + "» corrupta por concurrencia de " + coincidenciasIds.length + " registros (0001).");
}
return coincidencias[coincidenciasIds[0]].value;
}
let valorFinal = valor;
if (typeof valor === "function") {
valorFinal = valor();
}
const cacheDB = Castelog.variables.SimplestDB.getCache();
const coincidencias = cacheDB.select("cache", item => item.key === clave);
const coincidenciasIds = Object.keys(coincidencias);
if(coincidenciasIds.length === 0) {
const item = cacheDB.insert("cache", { key: clave, value: valorFinal });
return item.value;
} else if(coincidenciasIds.length > 1) {
throw new Error("Clave de cacheo «" + clave + "» corrupta por concurrencia de " + coincidenciasIds.length + " registros (0002).");
}
const coincidencia = coincidencias[coincidenciasIds[0]];
cacheDB.update("cache", coincidencia.id, { valor: valorFinal });
return valorFinal;
};
//Included:lib/503.castelog.v1.metodos.un_modulo_importado.part.js
Castelog.metodos.un_modulo_importado = function(id, file_dir = undefined, process_dir = undefined) {
try {
// console.log("0. iniciando importacion de: " + id);
// Intento 1. De la cache propia:
// console.log("intento 1: de la cache propia");
if(id in Castelog.modulos) {
// console.log("Funcionó el método 1.");
return Castelog.modulos[id].value;
}
// Intento 2. Del require normal:
// console.log("intento 2: del require normal");
if(typeof(Castelog.globalmente.require) === "function") {
try {
const modulix = Castelog.globalmente.require(id);
// console.log("Funcionó el método 2.");
return modulix;
} catch (error) {
// noop.
}
}
// Intento 3. Cambiando las rutas + de la cache propia:
// console.log("intento 3: cambiando rutas + de la cache propia");
let id2 = id;
if(id.startsWith("./") && file_dir) {
id2 = id.replace(/^\.\//g, file_dir.replace(/\/$/g, "") + "/");
} else if(id.startsWith("@/") && process_dir) {
id2 = id.replace(/^\.\//g, process_dir.replace(/\/$/g, "") + "/");
}
if(id2 in Castelog.modulos) {
const mod = Castelog.modulos[id2].value;
// console.log("Funcionó el método 3 con: " + id2);
return mod;
}
// Intento 4. Cambiando las rutas + del require normal:
// console.log("intento 4: cambiando rutas + del require normal");
if(typeof(Castelog.globalmente.require) === "function") {
try {
const mod = require(id2);
// console.log("Funcionó el método 4 con: " + id2);
return mod;
} catch (error) {
// Ya no hay más intentos, se lanza error:
throw error;
}
}
throw new Error(`No se pudo importar módulo porque no existe «${id2}» importable con «require(...)» ni tampoco en «Castelog.modulos»`);
} catch (error) {
console.log("Error al importar módulo: " + id);
throw error;
}
};
//Included:lib/503.castelog.v1.metodos.una_exportacion_de_modulo_universal_estandar.part.js
Castelog.metodos.una_exportacion_de_modulo_universal_estandar = function(id, modulo, file_dir = undefined, process_dir = undefined) {
try {
Castelog.modulos[id] = {
filedir: file_dir,
processdir: process_dir,
value: modulo
};
} catch (error) {
console.log("Error al exportar módulo universal estándar: " + id);
throw error;
}
};
//Included:lib/503.castelog.v1.metodos.una_importacion_de_modulo_universal_estandar.part.js
Castelog.metodos.una_importacion_de_modulo_universal_estandar = function(id, errores = false) {
try {
if(!(id in Castelog.modulos)) {
throw new Error("Módulo universal estándar llamado «" + id + "» no fue encontrado.");
}
return Castelog.modulos[id].value;
} catch (error) {
if(typeof errores === "function") {
const errorOutput = errores(error);
if(errorOutput !== "undefined") {
return errorOutput;
}
}
console.log("Error al importar módulo universal estándar: " + id);
throw error;
}
};
//Included:lib/504.castelog.v1.metodos.un_modulo_exportado.part.js
Castelog.metodos.un_modulo_exportado = function(id, modulo, factory = undefined, file_dir = undefined, process_dir = undefined) {
// console.log("0. iniciando exportacion de: " + id);
// Persistencia 1. En la cache propia:
// console.log("1. persistencia en cache propia: ");
Castelog.modulos[id] = { value: modulo, factory };
// Persistencia 2. En el module.exports normal:
if(typeof(module) !== "undefined") {
// console.log("2. persistencia en module.exports normal: ");
try {
module.exports = modulo;
} catch (error) {
// noop.
}
}
// Persistencia 3. Cambiando las rutas + cache propia:
if(process_dir) {
if(id.startsWith(process_dir)) {
const path_relative_to_process = id.replace(process_dir, "@/").replace(/\/+/g, "/");
Castelog.modulos[path_relative_to_process] = { value: modulo, factory };
}
}
// Ya no hay más persistencias, se retorna el módulo con ruta original:
return Castelog.modulos[id].value;
};
//Included:lib/504.castelog.v1.metodos.una_plantilla.js
Castelog.variables.plantillas_config_por_defecto = {};
Castelog.variables.plantillas_settings_por_defecto = { delimiter: ":", async: false };
Castelog.metodos.una_plantilla = function(fn, defaultConfig = {}, defaultSettings = {}) {
if(typeof fn === "string") {
return (config_p, settings_p) => {
const config = Object.assign({}, Castelog.variables.plantillas_config_por_defecto, defaultConfig, config_p);
const settings = Object.assign({}, Castelog.variables.plantillas_settings_por_defecto, defaultSettings, settings_p);
const parameters = { config };
return Castelog.variables.ejs.render(fn, parameters, settings);
};
} else if(typeof fn === "function") {
return (config, settings) => {
return fn(
Object.assign({}, defaultConfig, config),
Object.assign({}, defaultSettings, settings),
);
};
} else throw new Error("Tipo de plantilla no identificado (válidos:'string' y 'function'");
};
//Included:lib/505.castelog.v1.metodos.una_lectura_de_fichero.js
Castelog.metodos.una_lectura_de_fichero = function(file, codificacion = "utf8", modelId_ = "fs", fsSystem = "simplestdb.fs") {
if(fsSystem === "simplestdb.fs") {
let modelId = modelId_;
if(modelId_ === null) {
modelId = "fs";
} else if(typeof modelId_ === "undefined") {
modelId = "fs";
}
const sdb_fs = Castelog.variables.SimplestDB.getFS();
const previous_files = sdb_fs.select(modelId, item => item.path === file);
const keys = Object.keys(previous_files);
if(!keys.length) {
return undefined;
} else if(keys.length > 1) {
throw new Error("Fichero corrupto por duplicidad de ruta al leer: " + file + " [00909]");
}
return previous_files[keys[0]].contents;
} else if(fsSystem === "node.fs") {
return require("fs").readFileSync(file, codificacion);
} else {
throw new Error("Modalidad de sistema de ficheros «" + fsSystem + "» no identificada. Solo disponibles: 'simplestdb.fs' y 'node.fs'. [0001]");
}
};
//Included:lib/506.castelog.v1.metodos.una_escritura_de_fichero.js
Castelog.metodos.una_escritura_de_fichero = function (file, contents, codificacion, modelId_ = "fs", fsSystem = "simplestdb.fs") {
if (fsSystem === "simplestdb.fs") {
let modelId = modelId_;
if(modelId_ === null) {
modelId = "fs";
} else if(typeof modelId_ === "undefined") {
modelId = "fs";
}
const sdb_fs = Castelog.variables.SimplestDB.getFS();
const previous_files = sdb_fs.select(modelId, item => item.path === file);
const keys = Object.keys(previous_files);
if(!keys.length) {
return sdb_fs.insert(modelId, { path: file, contents: contents || "" });
} else if(keys.length > 1) {
throw new Error("Fichero corrupto por duplicidad de ruta al escribir: " + file + " [00808]");
}
sdb_fs.update(modelId, previous_files[keys[0]].id, { contents });
return previous_files[keys[0]];
} else if (fsSystem === "node.fs") {
return require("fs").writeFileSync(file, contents, codificacion);
} else {
throw new Error("Modalidad de sistema de ficheros «" + fsSystem + "» no identificada. Solo disponibles: 'simplestdb.fs' y 'node.fs'. [0002]");
}
};
//Included:lib/507.castelog.v1.metodos.una_copia_de_ficheros.js
Castelog.metodos.una_copia_de_ficheros = function (file, contents, codificacion, modelId_ = "fs", fsSystem = "simplestdb.fs") {
if (fsSystem === "simplestdb.fs") {
let modelId = modelId_;
if(modelId_ === null) {
modelId = "fs";
} else if(typeof modelId_ === "undefined") {
modelId = "fs";
}
const sdb_fs = Castelog.variables.SimplestDB.getFS();
// @TODO...
} else if (fsSystem === "node.fs") {
// @TODO...
} else {
throw new Error("Modalidad de sistema de ficheros «" + fsSystem + "» no identificada. Solo disponibles: 'simplestdb.fs' y 'node.fs'. [0003]");
}
};
//Included:lib/508.01.castelog.v1.metodos.una_conexion_de_base_de_datos.js
Castelog.metodos.una_conexion_de_base_de_datos = async function (configuraciones, tipo = "simplestdb", en_errores = undefined, ontologia = "") {
try {
const metodo_final = "una_conexion_de_base_de_datos_tipo_" + tipo + (ontologia ? ("_" + ontologia) : "");
if (!(metodo_final in Castelog.metodos)) {
throw new Error("Tipo de conexión no identificado");
}
return await Castelog.metodos[metodo_final](configuraciones);
} catch(error) {
if(en_errores) {
return en_errores(error);
}
throw error;
}
};
Castelog.metodos.una_conexion_de_base_de_datos_tipo_rest = function(configuraciones) {
return Castelog.variables.Automatic_http_rest_api_interface(configuraciones);
}
Castelog.metodos.una_conexion_de_base_de_datos_tipo_simplestdb = function(configuraciones) {
return new SimplestDB(configuraciones.schema || {}, configuraciones.validateSchema || false);
};
Castelog.metodos.una_conexion_de_base_de_datos_tipo_ranasdb = function (configuraciones) {
return RanasDB.connect(configuraciones.id, configuraciones.versionado);
};
Castelog.metodos.una_conexion_de_base_de_datos_tipo_mysql2 = function (configuraciones) {
if(!configuraciones.database) {
configuraciones.database = undefined;
}
if(!configuraciones.host) {
configuraciones.host = "127.0.0.1";
}
if(!configuraciones.port) {
configuraciones.port = 3306;
}
if(!configuraciones.user) {
configuraciones.user = "root";
}
if(!configuraciones.password) {
configuraciones.password = "";
}
return new Promise(async (ok, fail) => {
try {
const mysql = require("mysql2/promise");
const connection = await mysql.createConnection(configuraciones);
const connectionProxy = new Castelog.variables.un_proxy_de_conexion_para_mysql2(connection);
return ok(connectionProxy);
} catch(error) {
return fail(error);
}
});
};
Castelog.metodos.una_conexion_de_base_de_datos_tipo_mysql2_pool = function (configuraciones) {
if(!configuraciones.database) {
configuraciones.database = undefined;
}
if(!configuraciones.host) {
configuraciones.host = "127.0.0.1";
}
if(!configuraciones.port) {
configuraciones.port = 3306;
}
if(!configuraciones.user) {
configuraciones.user = "root";
}
if(!configuraciones.password) {
configuraciones.password = "";
}
return new Promise(async (ok, fail) => {
try {
const mysql = require("mysql2/promise");
const pool = await mysql.createPool(configuraciones);
const poolProxy = new Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2(pool);
return ok(poolProxy);
} catch (error) {
return fail(error);
}
});
};
//Included:lib/508.02.castelog.v1.metodos.una_seleccion_de_base_de_datos.js
Castelog.metodos.una_seleccion_de_base_de_datos = function (modelo, filtrando, ordenando, agrupando, paginando, bd = "system", adaptador = Castelog.variables.SimplestDB, objetivo = "a varios ítems") {
if(typeof adaptador === "undefined") {
throw new Error("Required argument «adaptador» to not be undefined in order to «Castelog.metodos.una_seleccion_de_base_de_datos»");
}
const db = adaptador.create({ schema: bd }, true);
const [mysqlClass1, mysqlClass2] = [
Castelog.variables.un_proxy_de_conexion_para_mysql2,
Castelog.variables.un_proxy_de_pool_de_conexiones_para_mysql2
];
if ((db instanceof mysqlClass1) || (db instanceof mysqlClass2)) {
if (objetivo === "a un ítem") {
return db.select_one(modelo, filtrando, ordenando, agrupando, paginando, bd);
} else if (objetivo === "a varios ítems") {
return db.select_many(modelo, filtrando, ordenando, agrupando, paginando, bd);
} else if (objetivo === "al primer ítem") {
return db.select_first(modelo, filtrando, ordenando, agrupando, paginando, bd);
} else if (objetivo === "al último ítem") {
return db.select_last(modelo, filtrando, ordenando, agrupando, paginando, bd);
}
} else if (db.instanceType === "standard") {
return db.select(modelo, filtrando, ordenando, agrupando, paginando, bd, adaptador, objetivo);
} else {
if(objetivo === "a varios ítems") {
const resultOriginal = db.select(modelo, filtrando ? filtrando : i => i);
let result = Object.keys(resultOriginal).reduce((output, key) => {
output.push([key, resultOriginal[key]]);
return output;
}, []);
if(agrupando) {
// result = result.sort(ordenando);
}
if(ordenando) {
if(typeof ordenando === "function") {
result = result.sort(ordenando);
} else if(Array.isArray(ordenando)) {
result = result.sort(function(a, b) {
for(let index = 0; index < ordenando.length; index++) {
const ordenacion = ordenando[index];
const aHas = ordenacion in a;
const bHas = ordenacion in b;
if(aHas && bHas) {
if(a[ordenacion] < b[ordenacion]) {
return -1;
} else if(a[ordenacion] > b[ordenacion]) {
return 1;
}
} else if (aHas) {
return -1;
} else if(bHas) {
return 1;
}
}
return -1;
});
} else {
throw new Error("Parámetro «ordenando» debe ser una función o un array. [0001]");
}
}
if(paginando) {
if(typeof paginando !== "object") {
throw new Error("Parámetro «paginando» debe ser un objeto. [0001]");
}
const { pagina, items } = paginando;
const itemsNumber = parseInt(items) || 20;
const paginaNumber = parseInt(pagina) || 0;
let indexPagina = 0;
let indexItem = 0;
let result2 = [];
for(let indexRow = 0; indexRow < result.length; indexRow++) {
const row = result[indexRow];
indexItem++;
if(indexItem >= itemsNumber) {
indexPagina++;
indexItem = 0;
}
if(indexPagina === paginaNumber) {
result2.push(row);
}
}
result = result2;
}
if(Array.isArray(result)) {
result = result.reduce((output, item) => {
const [ key, value ] = item;
output[key] = value;
return output;
}, {});
}
return result;
}
}
};
//Included:lib/508.03.castelog.v1.metodos.una_insercion_de_base_de_datos.js
Castelog.metodos.una_insercion_de_base_de_datos = function (modelo, datos, bd = "system", adaptador = Castelog.variables.SimplestDB) {
if (typeof adaptador === "undefined") {
throw new Error("Required argument «adaptador» to not be undefined in order to «Castelog.metodos.una_insercion_de_base_de_datos»");
}
const db = adaptador.create({ schema: bd }, true);
return db.insert(modelo, datos);
};
//Included:lib/508.04.castelog.v1.metodos.una_actualizacion_de_base_de_datos.js
Castelog.metodos.una_actualizacion_de_base_de_datos = function (modelo, id, datos, bd = "system", adaptador = Castelog.variables.SimplestDB) {
if (typeof adaptador === "undefined") {
throw new Error("Required argument «adaptador» to not be undefined in order to «Castelog.metodos.una_actualizacion_de_base_de_datos»");
}
const db = adaptador.create({ schema: bd }, true);
return db.update(modelo, id, datos);
};
//Included:lib/508.05.castelog.v1.metodos.una_eliminacion_de_base_de_datos.js
Castelog.metodos.una_eliminacion_de_base_de_datos = function (modelo, id, bd = "system", adaptador = Castelog.variables.SimplestDB) {
if (typeof adaptador === "undefined") {
throw new Error("Required argument «adaptador» to not be undefined in order to «Castelog.metodos.una_eliminacion_de_base_de_datos»");
}
const db = adaptador.create({ schema: bd }, true);
return db.delete(modelo, id);
};
//Included:lib/510.castelog.v1.metodos.una_notificacion.js
Castelog.metodos.una_notificacion = function(mensaje) {
if (typeof window !== "undefined") {
return new Promise((ok, fail) => {
try {
const dialogDiv = document.createElement("div");
dialogDiv.innerHTML = `<div style="display: block; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: white; z-index: 9999;">
<table style="width: 100%; height: 100%;">
<tr style="height: 5%;">
<td style="vertical-align: bottom;">
<div style="display: inline-block; width: auto; font-family: monospace; font-size: 10px;" class="dialog_label"></div>
</td>
</tr>
<tr style="height: 50%;">
<td style="vertical-align: top; border-top: 1px solid #333;">
<button style="float: left; font-family: monospace; font-size: 10px;" class="dialog_submiter">Aceptar</button>
</td>
</tr>
</table>
</div>`;
const dialogLabel = dialogDiv.querySelector(".dialog_label");
const dialogSubmiter = dialogDiv.querySelector(".dialog_submiter");
dialogLabel.textContent = mensaje;
dialogSubmiter.addEventListener("click", function (event) {
dialogDiv.remove();
return ok(true);
});
document.body.appendChild(dialogDiv);
dialogSubmiter.focus();
} catch (error) {
window.alert(mensaje);
return fail(error);
}
});
} else if (typeof global === "object") {
return new Promise((ok, fail) => {
try {
const reader = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
reader.question(mensaje + "\n«Presiona enter:» ", answer => {
reader.close();
return ok(true);
});
} catch(error) {
console.log(mensaje);
return fail(error);
}
});
}
};
//Included:lib/511.castelog.v1.metodos.una_pregunta.js
Castelog.metodos.una_pregunta = function(mensaje, defecto = "", es_silenciosa = false) {
if(typeof window === "object") {
return new Promise((ok, fail) => {
try {
const dialogDiv = document.createElement("div");
dialogDiv.innerHTML = `<div style="display: block; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: white; z-index: 9999; font-family: monospace; font-size: 10px;">
<table style="width: 100%; height: 100%;">
<tr style="height: 5%;">
<td style="vertical-align: bottom;">
<div style="display: inline-block; width: auto; font-family: monospace; font-size: 10px;" class="dialog_label"></div>
<button style="float: right; font-family: monospace; font-size: 10px;" class="dialog_closer">Salir</div>
</td>
</tr>
<tr style="height: 50%;">
<td style="vertical-align: top; border-top: 1px solid #333;">
<textarea style="width: 100%; min-height: 100px; resize: vertical; box-sizing: border-box; font-family: monospace; font-size: 10px;" class="dialog_textarea"></textarea>
<button style="float: left; font-family: monospace; font-size: 10px;" class="dialog_submiter">Aceptar</button><span>ó CTRL + ENTER pero desde el texto</span>
</td>
</tr>
</table>
</div>`;
const dialogLabel = dialogDiv.querySelector(".dialog_label");
const dialogCloser = dialogDiv.querySelector(".dialog_closer");
const dialogTextarea = dialogDiv.querySelector(".dialog_textarea");
const dialogSubmiter = dialogDiv.querySelector(".dialog_submiter");
dialogLabel.textContent = mensaje;
dialogCloser.addEventListener("click", function(event) {
dialogDiv.remove();
return ok(false);
});
dialogSubmiter.addEventListener("click", function(event) {
const val = dialogTextarea.value;
dialogDiv.remove();
return ok(val);
});
dialogTextarea.value = defecto;
dialogTextarea.addEventListener("keypress", function(event) {
if((event.code === "Enter") && (event.ctrlKey)) {
const val = dialogTextarea.value;
dialogDiv.remove();
return ok(val);
}
});
document.body.appendChild(dialogDiv);
dialogTextarea.focus();
} catch(error) {
return fail(error);
}
});
} else if(typeof global === "object") {
return new Promise(ok => {
const reader = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
if(es_silenciosa) {
reader.question(mensaje, answer => {
reader.close();
if(!answer) {
return ok(defecto);
}
return ok(answer);
})
} else {
reader.question(mensaje + "\n«Respuesta:» ", answer => {
reader.close();
if(!answer) {
return ok(defecto);
}
return ok(answer);
});
}
});
}
};
//Included:lib/512.castelog.v1.metodos.una_confirmacion.js
Castelog.metodos.una_confirmacion = function(mensaje, defecto = false) {
if(typeof window === "object") {
return window.confirm(mensaje, defecto);
} else if(typeof global === "object") {
const readline = require("readline");
const reader = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(ok => {
const ask = () => {
reader.question(mensaje + ( defecto ? " (S/n = por defecto «sí»)" : " (s/N = por defecto «no»)" ), answer => {
reader.close();
if(!answer) {
return ok(defecto);
}
return ok(answer);
});
};
ask();
});
}
};
//Included:lib/514.castelog.v1.metodos.estoy_en.js
Castelog.metodos.estoy_en = function(expresion, arg1) {
// Esta función está por completarse/parchearse.
// Actualmente solo determina correctamente si:
// - estoy en navegador: tiene en cuenta window.
// - estoy en sistema: tiene en cuenta global y require.
// - estoy en windows: funciona bien en node.js solamente (en sistema).
// - estoy en linux: funciona bien solo si consideras linux a todo lo que no sea windows.
if(expresion === "estoy en navegador") {
return (typeof window !== "undefined") && (typeof document !== "undefined");
} else if(expresion === "estoy en sistema") {
return (typeof global !== "undefined") && (typeof require !== "undefined");
} else if(expresion === "estoy en windows") {
return (typeof global !== "undefined") && (typeof require !== "undefined") && (require("os").platform().indexOf("win") === 0);
} else if(expresion === "estoy en linux") {
return (typeof global !== "undefined") && (typeof require !== "undefined") && (require("os").platform().indexOf("win") !== 0);
} else if(expresion === "estoy en entorno") {
return Castelog.variables.globales.entorno === arg1;
} else {
throw new Error("Expresión de detección de entorno no identificada o no disponible: "+ expresion);
}
if(expresion === "estoy en mac") {
return undefined;
} else if(expresion === "estoy en chrome") {
return undefined;
} else if(expresion === "estoy en firefox") {
return undefined;
} else if(expresion === "estoy en opera") {
return undefined;
} else if(expresion === "estoy en safari") {
return undefined;
} else if(expresion === "estoy en ios") {
return undefined;
} else if(expresion === "estoy en android") {
return undefined;
} else if(expresion === "estoy en móvil") {
return undefined;
} else if(expresion === "estoy en tablet") {
return undefined;
} else if(expresion === "estoy en ordenador") {
return undefined;
}
return true;
};
//Included:lib/515.castelog.v1.metodos.un_elemento_html.js
Castelog.metodos.un_elemento_html = function(codigo) {
if(typeof window === "object") {
const parent = document.createElement("div");
parent.innerHTML = codigo;
return parent.children[0];
} else if(typeof global === "object") {
throw new Error("El entorno no soporta la carga de elementos HTML nativa. Suele funcionar en navegadores.");
}
};
//Included:lib/516.castelog.v1.metodos.una_compilacion_estandar_de_parametros_de_consola.js
Castelog.metodos.una_compilacion_estandar_de_parametros_de_consola = function(parametros) {
if(!Array.isArray(parametros)) {
throw new Error("Se requiere que «parametros» sea un array");
}
const compilados = {};
let propiedadSeleccionada = "_";
for(let index = 0; index < parametros.length; index++) {
const parametro = parametros[index];
if (parametro.match(/^\-\-/g)) {
propiedadSeleccionada = parametro.replace(/^\-\-/g, "");
} else if(parametro.match(/^\-/g)) {
propiedadSeleccionada = parametro.replace(/^\-/g, "");
} else {
if (!Array.isArray(compilados[propiedadSeleccionada])) {
compilados[propiedadSeleccionada] = [];
}
compilados[propiedadSeleccionada].push(parametro);
}
}
return compilados;
};
//Included:lib/517.castelog.v1.metodos.un_servidor_http.js
Castelog.metodos.un_servidor_http = function(controlador, opciones) {
if(typeof window === "object") {
return;
} else if(typeof global === "object") {
return require("http").createServer(controlador, opciones);
}
};
//Included:lib/518.castelog.v1.metodos.un_servidor_https.js
Castelog.metodos.un_servidor_https = function(controlador, opciones_seguras, opciones) {
if(typeof window === "object") {
return;
} else if(typeof global === "object") {
return require("https").createServer(controlador, opciones_seguras, opciones);
}
};
//Included:lib/519.castelog.v1.metodos.un_servidor_socket_io.js
Castelog.metodos.un_servidor_socket_io = function (servidor, eventos, eventos_socket, opciones_de_socket_servidor, opciones_seguras) {
try {
if (typeof window === "object") {
return;
} else if (typeof global === "object") {
let socket_io = undefined;
try {
socket_io = require("socket.io");
} catch (error) {
console.log(error);
throw new Error("Error intentando arrancar un servidor con «socket.io» probablemente porque no se encontró la dependencia en node/npm desde " + process.cwd());
}
if (typeof servidor === 'undefined') {
if (opciones_seguras) {
throw new Error("Opciones seguras de socket.io no están implementadas todavía");
} else if (servidor) {
// @OK!
} else {
servidor = require("http").createServer(function (request, response) {
response.writeHead(200, { "Content-type": "text/plain" });
response.write("This is a chat server only");
return response.end();
});
}
}
const socket_connection = new socket_io.Server(servidor, opciones_de_socket_servidor);
for (let indexEvento = 0; indexEvento < eventos.length; indexEvento++) {
const evento = eventos[indexEvento];
if (Array.isArray(evento) && (evento.length === 2) && (typeof evento[0] === "string") && (typeof evento[1] === "function")) {
const [evento_id, evento_funcion] = evento;
socket_connection.on(evento_id, (...args) => evento_funcion(args, {
socket_io,
io: socket_io,
socket: socket_connection,
evento: evento
}));
} else if ((typeof evento === "object") && (evento.tipo === "espacio de nombres")) {
const nombre_de_espacios = evento.nombre;
if (typeof evento.nombre !== "string") {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» on property «nombre» to be a string in order to «Castelog.metodos.un_servidor_socket_io»");
}
if (!Array.isArray(evento.eventos)) {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» on property «eventos» to be an array in order to «Castelog.metodos.un_servidor_socket_io»");
}
const socket_namespaced = socket_connection.of(nombre_de_espacios);
for (let indexSubevento = 0; indexSubevento < evento.eventos.length; indexSubevento++) {
const subevento = evento.eventos[indexSubevento];
const [subevento_id, subevento_funcion] = subevento;
if (Array.isArray(subevento) && (subevento.length === 2) && (typeof subevento[0] === "string") && (typeof subevento[1] === "function")) {
socket_namespaced.on(subevento_id, (...args) => subevento_funcion(args, {
socket_io,
io: socket_connection,
socket: socket_connection,
evento: evento
}));
} else {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» on property «eventos» on index «" + indexSubevento + "» to be an array like [string, function] in order to «Castelog.metodos.un_servidor_socket_io»")
}
}
} else {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» to be an array like [string, function] or to be an object with «tipo» set to «espacio de nombres» in order to «Castelog.metodos.un_servidor_socket_io» (message 2)")
}
}
socket_connection.on("connect", (socket_subconnection) => {
for (let indexEvento = 0; indexEvento < eventos_socket.length; indexEvento++) {
const evento = eventos_socket[indexEvento];
if (Array.isArray(evento) && (evento.length === 2) && (typeof evento[0] === "string") && (typeof evento[1] === "function")) {
const [evento_id, evento_funcion] = evento;
socket_subconnection.on(evento_id, (...args) => evento_funcion(args, {
socket_io,
io: socket_connection,
socket: socket_subconnection,
evento: evento
}));
} else if ((typeof evento === "object") && (evento.tipo === "espacio de nombres")) {
const nombre_de_espacios = evento.nombre;
if (typeof evento.nombre !== "string") {
throw new Error("Required argument «eventos_socket» on index «" + indexEvento + "» on property «nombre» to be a string in order to «Castelog.metodos.un_servidor_socket_io»");
}
if (!Array.isArray(evento.eventos)) {
throw new Error("Required argument «eventos_socket» on index «" + indexEvento + "» on property «eventos» to be an array in order to «Castelog.metodos.un_servidor_socket_io»");
}
const socket_namespaced = socket_subconnection.of(nombre_de_espacios);
for (let indexSubevento = 0; indexSubevento < evento.eventos.length; indexSubevento++) {
const subevento = evento.eventos[indexSubevento];
const [subevento_id, subevento_funcion] = subevento;
if (Array.isArray(subevento) && (subevento.length === 2) && (typeof subevento[0] === "string") && (typeof subevento[1] === "function")) {
socket_namespaced.on(subevento_id, (...args) => subevento_funcion(args, {
socket_io,
io: socket_connection,
socket: socket_subconnection,
evento: evento
}));
} else {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» on property «eventos» on index «" + indexSubevento + "» to be an array like [string, function] in order to «Castelog.metodos.un_servidor_socket_io»")
}
}
} else {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» to be an array like [string, function] or to be an object with «tipo» set to «espacio de nombres» in order to «Castelog.metodos.un_servidor_socket_io» (message 2)")
}
}
});
return socket_connection;
}
} catch (error) {
console.log("Error al intenter «un_servidor_socket_io»", error);
throw error;
}
};
//Included:lib/520.castelog.v1.metodos.un_cliente_socket_io.js
Castelog.metodos.un_cliente_socket_io = function (eventos, opciones) {
try {
let socket_io_client = undefined;
let cliente = undefined;
let common_io = undefined;
if (typeof io === "function") {
socket_io_client = io;
common_io = io.io;
} else if (typeof require === "function") {
socket_io_client = require("socket.io-client");
common_io = socket_io_client.io;
} else {
throw new Error("Required dependency «socket.io-client» reachable by global or by module in order to «Castelog.metodos.un_cliente_socket»");
}
if (typeof common_io !== "function") {
throw new Error("Required dependency «common_io» to be a function in order to «Castelog.metodos.un_cliente_socket»");
}
const client_socket = common_io(opciones);
if (!Array.isArray(eventos)) {
throw new Error("Required parameter «eventos» to be an array in order to «Castelog.metodos.un_cliente_socket_io»");
}
for (let indexEvento = 0; indexEvento < eventos.length; indexEvento++) {
const evento = eventos[indexEvento];
if (Array.isArray(evento) && (evento.length === 2) && (typeof evento[0] === "string") && (typeof evento[1] === "function")) {
const [evento_id, evento_funcion] = evento;
const evento_funcion_final = (() => {
return (...args) => {
return evento_funcion(args, {
socket_io_client,
io: socket_io_client.io,
client: client_socket,
socket: client_socket,
evento: evento
});
}
})();
client_socket.on(evento_id, evento_funcion_final);
} else {
throw new Error("Required argument «eventos» on index «" + indexEvento + "» to be an array like [string, function] in order to «Castelog.metodos.un_cliente_socket_io»")
}
}
return client_socket;
} catch (error) {
console.log("Error al intenter «un_cliente_socket_io»", error);
throw error;
}
};
//Included:lib/523.castelog.v1.metodos.una_red_de_servidores_http_rest_automaticos.js
Castelog.metodos.una_red_de_servidores_http_rest_automaticos = function (rutaDeProyectoPrototipo, deployerCallback) {
if (typeof global === "object") {
return new Promise((ok, fail) => {
try {
const path = require("path");
const rutaInicial = path.resolve(rutaDeProyectoPrototipo);
Castelog.variables.generador_de_proyector_rest(rutaInicial);
const rutaGeneratorBuilder = path.resolve(rutaInicial, "./bin/build-generator.js");
require(rutaGeneratorBuilder);
const rutaApi = path.resolve(rutaInicial, "./api.js");
const restApi = require(rutaApi);
const { una_red_de_servidores_http_rest_automaticos } = restApi;
return una_red_de_servidores_http_rest_automaticos(deployerCallback).then(() => {
console.log("La red de servidores http rest automáticos fue desplegada exitosamente,");
ok();
}).catch(error => {
console.log("Hubo errores al intentar generar una red de servidores http rest automáticos:", error);
fail(error);
});
} catch (error) {
return fail(error);
}
});
} else {
console.log("Sintaxis de red de servidores HTTP REST automáticos no soportada en navegadores");
}
};
//Included:lib/524.castelog.v1.metodos.una_superquery.js
Castelog.metodos.una_superquery = function(esquema, cliente, base) {
if(typeof esquema !== "object") {
throw new Error("Se requiere de parámetro «esquema» ser un objeto para «Castelog.metodos.una_superquery»");
}
if(typeof cliente !== "function") {
throw new Error("Se requiere de parámetro «cliente» ser una función para «Castelog.metodos.una_superquery»");
}
if(typeof base !== "function") {
throw new Error("Se requiere de parámetro «base» ser una función para «Castelog.metodos.una_superquery»");
}
return base({ esquema, cliente });
};
//Included:lib/525.castelog.v1.metodos.una_query.js
Castelog.metodos.una_query = function(superquery, tabla, cuyos, ordenada_por, paginada_por) {
if(typeof superquery !== "object") {
throw new Error("Se requiere de parámetro «superquery» ser un objeto para «Castelog.metodos.una_query»");
}
if(typeof superquery.esquema !== "object") {
throw new Error("Se requiere de parámetro «superquery.esquema» ser un objeto para «Castelog.metodos.una_query»");
}
if(typeof superquery.cliente !== "function") {
throw new Error("Se requiere de parámetro «superquery.cliente» ser una función para «Castelog.metodos.una_query»");
}
if(typeof tabla !== "string") {
throw new Error("Se requiere de parámetro «tabla» ser un string para «Castelog.metodos.una_query»");
}
if(typeof cuyos !== "object") {
throw new Error("Se requiere de parámetro «cuyos» ser una objeto para «Castelog.metodos.una_query»");
}
if(typeof ordenada_por !== "object") {
throw new Error("Se requiere de parámetro «ordenada_por» ser una objeto para «Castelog.metodos.una_query»");
}
if(typeof paginada_por !== "object") {
throw new Error("Se requiere de parámetro «paginada_por» ser una objeto para «Castelog.metodos.una_query»");
}
const { esquema, cliente } = superquery;
return cliente.get("?" + new URLSearchParams({
operation: "select",
table: tabla,
where: JSON.stringify(cuyos),
order: JSON.stringify(ordenada_por),
paginate: JSON.stringify(paginada_por)
}).toString()).then(response => {
return response.data.data.items;
});
};
//Included:lib/526.castelog.v1.metodos.un_proyecto_npm.js
Castelog.metodos.un_proyecto_npm = async function(extensionDePackage, directorio, esAsincrono = false) {
try {
if(typeof extensionDePackage !== "object") {
throw new Error("Se requiere de parámetro «extensionDePackage» ser un object para «Castelog.metodos.un_proyecto_npm»");
}
if(typeof directorio !== "string") {
throw new Error("Se requiere de parámetro «directorio» ser un string para «Castelog.metodos.un_proyecto_npm»");
}
if(typeof global === "undefined" || typeof require !== "function") {
throw new Error("Se requiere de variable «global» no ser undefined y a variable «require» ser una función para «Castelog.metodos.un_proyecto_npm»");
}
const fs = require("fs");
const path = require("path");
// Sí o sí, síncrono:
Castelog.metodos.un_comando_de_consola("npm init -y", { cwd: directorio ? directorio : process.cwd() }, false);
const packagePath = path.resolve(directorio, "package.json");
let packageContents = undefined;
if(esAsincrono) {
packageContents = await fs.promises.readFile(packagePath, "utf8")
} else {
packageContents = fs.readFileSync(packagePath, "utf8");
}
const packageData = JSON.parse(packageContents);
Object.assign(packageData, extensionDePackage);
if(esAsincrono) {
await fs.promises.writeFile(packagePath, JSON.stringify(packageData, null, 4), "utf8");
} else {
fs.writeFileSync(packagePath, JSON.stringify(packageData, null, 4), "utf8");
}
return extensionDePackage;
} catch (error) {
console.log("Error al desplegar proyecto npm:", error);
throw error;
}
};
//Included:lib/527.castelog.v1.metodos.un_comando_de_consola.js
Castelog.metodos.un_comando_de_consola = function(comando, configuraciones, esParalelo = false) {
try {
if(esParalelo) {
if(!Array.isArray(comando)) {
throw new Error("Required parameter «comando» to be an array in order to «Castelog.metodos.un_comando_de_consola» in «en paralelo» mode");
}
if (comando.length !== 2) {
throw new Error("Required parameter «comando» to be an array of 2 items in order to «Castelog.metodos.un_comando_de_consola» in «en paralelo» mode");
}
if(typeof comando[0] !== "string") {
throw new Error("Required parameter «comando» on item 1 to be a string in order to «Castelog.metodos.un_comando_de_consola» in «en paralelo» mode");
}
if(!Array.isArray(comando[1])) {
throw new Error("Required parameter «comando» on item 2 to be an array in order to «Castelog.metodos.un_comando_de_consola» in «en paralelo» mode");
}
} else {
if (typeof comando !== "string") {
throw new Error("Required parameter «comando» to be a string in order to «Castelog.metodos.un_comando_de_consola» in «en serie» mode");
}
}
if(typeof configuraciones !== "object") {
throw new Error("Required parameter «configuraciones» to be an object in order to «Castelog.metodos.un_comando_de_consola»");
}
if(typeof require !== "function") {
throw new Error("Required global «require» to be a function in order to «Castelog.metodos.un_comando_de_consola»");
}
if(typeof configuraciones.cwd !== "string") {
configuraciones.cwd = process.cwd();
}
if(typeof configuraciones.stdio === "undefined") {
if(!esParalelo) {
configuraciones.stdio = ["inherit", "inherit", "inherit"];
} else {
configuraciones.stdio = ["ignore", "ignore", "ignore"];
}
}
if(esParalelo) {
return new Promise((ok, fail) => {
return require("child_process").spawn(comando[0], comando[1], configuraciones, (error, stdout, stderr) => {
if(error) {
return fail(error);
}
if(stderr) {
return ok({ error: stderr });
}
if(stdout) {
return ok(stdout);
}
return ok();
});
});
} else {
return require("child_process").execSync(comando, configuraciones);
}
} catch (error) {
console.log("Error al ejecutar comando de consola:", error);
throw error;
}
};
//Included:lib/529.castelog.v1.metodos.un_testeo.js
Castelog.metodos.un_testeo = function (tiempo, nombre_de_testeo, nombres_de_tests, en_exito, en_error) {
try {
if(typeof tiempo !== "number") {
throw new Error("Required parameter «tiempo» to be a number in order to «Castelog.metodos.un_testeo»");
}
if(!Array.isArray(nombres_de_tests)) {
throw new Error("Required parameter «nombres_de_tests» to be an array in order to «Castelog.metodos.un_testeo»");
}
if(nombres_de_tests.length === 0) {
throw new Error("Required parameter «nombres_de_tests» to be an array with 1 or more items in order to «Castelog.metodos.un_testeo»");
}
if (typeof en_exito === "undefined") {
// OK
} else if (typeof en_exito !== "function") {
throw new Error("Required parameter «en_exito» to be a function or undefined in order to «Castelog.metodos.un_testeo»");
}
if(typeof en_error === "undefined") {
// OK
} else if(typeof en_error !== "function") {
throw new Error("Required parameter «en_error» to be a function or undefined in order to «Castelog.metodos.un_testeo»");
}
const entorno_de_testeo = new Castelog.variables.Entorno_de_testeo({
tests_planificados: nombres_de_tests,
tests_completados: [],
tests_fallidos: [],
tiempo_maximo_de_testeo: tiempo,
estado_del_testeo: "pendiente", // "completado", "fallido"
en_error: en_error ? en_error : (error) => {
console.log("El testeo «" + nombre_de_testeo + "» falló con el siguiente error:", error);
},
en_exito: en_exito ? en_exito : () => {
console.log("El testeo «" + nombre_de_testeo + "» se completó satisfactoriamente.");
},
});
entorno_de_testeo.id_de_temporizador = setTimeout(() => {
// console.log(200);
const tests_no_completados = [];
for(let index = 0; index < entorno_de_testeo.tests_planificados.length; index++) {
// console.log(201);
const nombre_de_test = entorno_de_testeo.tests_planificados[index];
if(entorno_de_testeo.tests_completados.indexOf(nombre_de_test) === -1) {
// console.log(202);
tests_no_completados.push(nombre_de_test);
}
}
if(entorno_de_testeo.estado_del_testeo === "pendiente") {
// console.log(203);
entorno_de_testeo.estado_del_testeo = "fallido";
const mensaje_del_error = "El testeo «" + nombre_de_testeo + "» no completó en el tiempo estipulado («" + (tiempo/1000) + " segundos») los siguientes (" + tests_no_completados.length + ") tests: " + tests_no_completados.map(t => `«${t}»`).join(", ");
const error = new Error(mensaje_del_error);
if(typeof entorno_de_testeo.en_error === "function") {
// console.log(204);
entorno_de_testeo.en_error(error);
} else {
// console.log(205);
console.log(error);
throw error;
}
}
}, tiempo);
return entorno_de_testeo;
} catch (error) {
throw error;
}
};
//Included:lib/530.castelog.v1.metodos.un_test.js
Castelog.metodos.un_test = function(nombre_de_test, funcion_de_test, objeto_de_testeo, en_exito, en_error) {
try {
if(typeof nombre_de_test !== "string") {
throw new Error("Required parameter «nombre_de_test» to be a string in order to «Castelog.metodos.un_test»");
}
if(typeof funcion_de_test !== "function") {
throw new Error("Required parameter «funcion_de_test» to be a function in order to «Castelog.metodos.un_test»");
}
if(typeof en_exito === "undefined") {
// OK
} else if(typeof en_exito !== "function") {
throw new Error("Required parameter «en_exito» to be a function or undefined in order to «Castelog.metodos.un_test»");
}
if(typeof en_error === "undefined") {
// OK
} else if(typeof en_error !== "function") {
throw new Error("Required parameter «en_error» to be a function or undefined in order to «Castelog.metodos.un_test»");
}
if(typeof objeto_de_testeo === "undefined") {
// OK
} else if(!(objeto_de_testeo instanceof Castelog.variables.Entorno_de_testeo)) {
throw new Error("Required parameter «objeto_de_testeo» to be an object or undefined in order to «Castelog.metodos.un_test»")
}
try {
// console.log(100);
const resultado_de_test = funcion_de_test(objeto_de_testeo, nombre_de_test);
if(!(resultado_de_test instanceof Promise)) {
throw new Error("Required parameter «funcion_de_test» to be a function that returns a Promise in order to «Castelog.metodos.un_test»");
}
// console.log(101);
return resultado_de_test.then(resultado_final_de_test => {
// console.log(102);
let es_ultimo_test = true;
if(typeof objeto_de_testeo === "object") {
// console.log(103);
objeto_de_testeo.tests_completados.push(nombre_de_test);
EsUltimoTest:
for (let index = 0; index < objeto_de_testeo.tests_planificados.length; index++) {
// console.log(104);
const nombre_de_test_planificado = objeto_de_testeo.tests_planificados[index];
if (objeto_de_testeo.tests_completados.indexOf(nombre_de_test_planificado) === -1) {
// console.log(105);
es_ultimo_test = false;
break EsUltimoTest;
}
}
if(es_ultimo_test) {
// console.log(106);
objeto_de_testeo.estado_del_testeo = "completado";
clearTimeout(objeto_de_testeo.id_de_temporizador);
}
}
if(typeof en_exito === "function") {
// console.log(107);
en_exito(resultado_final_de_test, objeto_de_testeo);
}
if((typeof objeto_de_testeo === "object") && (typeof objeto_de_testeo.en_exito === "function")) {
// console.log(108);
if (es_ultimo_test) {
// console.log(109);
if (typeof objeto_de_testeo.en_exito === "function") {
// console.log(110);
objeto_de_testeo.en_exito(objeto_de_testeo, nombre_de_test, resultado_final_de_test);
}
}
}
return resultado_final_de_test;
}).catch(error => {
// console.log(120);
if (typeof objeto_de_testeo === "object") {
// console.log(121);
clearTimeout(objeto_de_testeo.id_de_temporizador);
objeto_de_testeo.estado_del_testeo = "fallido";
objeto_de_testeo.tests_fallidos.push(nombre_de_test);
}
if(typeof en_error === "function") {
// console.log(122);
en_error(error, objeto_de_testeo);
} else {
// console.log(123);
console.log("Error en test «" + nombre_de_test + "»:", error);
}
if(typeof objeto_de_testeo === "object") {
// console.log(124);
if (typeof objeto_de_testeo.en_error === "function") {
// console.log(125);
objeto_de_testeo.en_error(error, objeto_de_testeo, nombre_de_test);
}
}
});
} catch(error) {
// console.log(150);
if (typeof objeto_de_testeo === "object") {
// console.log(151);
clearTimeout(objeto_de_testeo.id_de_temporizador);
objeto_de_testeo.estado_del_testeo = "fallido";
objeto_de_testeo.tests_fallidos.push(nombre_de_test);
}
if (typeof en_error === "function") {
// console.log(152);
en_error(error, objeto_de_testeo);
} else {
// console.log(153);
console.log("Error en test «" + nombre_de_test + "»:", error);
}
if (typeof objeto_de_testeo === "object") {
// console.log(154);
if (typeof objeto_de_testeo.en_error === "function") {
// console.log(155);
objeto_de_testeo.en_error(error, nombre_de_test, objeto_de_testeo);
}
}
}
} catch (error) {
throw error;
}
};
//Included:lib/531.castelog.v1.metodos.una_descripcion_del_entorno.js
Castelog.metodos.una_descripcion_del_entorno = function() {
try {
if(typeof require === "function") {
const os = require("os");
return {
hostname: os.hostname(),
platform: os.platform(),
architecture: os.arch(),
type: os.type(),
release: os.release(),
endianness: os.endianness(),
totalmem: os.totalmem(),
tmpdir: os.tmpdir(),
homedir: os.homedir(),
userInfo: os.userInfo(),
cpus: os.cpus(),
networkInterfaces: os.networkInterfaces()
};
};
} catch (error) {
console.log("Error al hacer una descripción del entorno:", error);
throw error;
}
};
//Included:lib/532.castelog.v1.metodos.un_reseteo_de_directorio.js
Castelog.metodos.un_reseteo_de_directorio = async function(directorio, esAsincrono = false) {
try {
if(typeof require === "function") {
const fs = require("fs");
if(esAsincrono) {
await fs.promises.rmdir(directorio, { recursive: true });
await fs.promises.mkdir(directorio);
} else {
fs.rmdirSync(directorio, { recursive: true });
fs.mkdirSync(directorio);
}
};
} catch (error) {
console.log("Error al hacer un reseteo de directorio:", error);
throw error;
}
};
//Included:lib/533.castelog.v1.metodos.un_servicio_de_ficheros_estaticos.js
Castelog.metodos.un_servicio_de_ficheros_estaticos = async function(parametros, errores = false, enFicherosNoEncontrados = false, enOtrosCasos = false) {
try {
if(typeof require !== "function") {
throw new Error("Required global «require» to be a function in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
const fs = require("fs");
const parse_url = (arg) => require("url").parse(arg);
const path = require("path");
const { directorio, request, response, url: directorio_url_original = "/" } = parametros;
const directorio_url = directorio_url_original.replace(/\/$/g, "") + "/";
if(typeof directorio !== "string") {
throw new Error("Required parameter «directorio» to be a string in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
if (typeof directorio_url !== "string") {
throw new Error("Required parameter «directorio» to be a string in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
if(typeof request === "undefined") {
throw new Error("Required parameter «request» to not be undefined in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
if(typeof response === "undefined") {
throw new Error("Required parameter «response» to not be undefined in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
const requested_url = parse_url(request.url).pathname;
if(requested_url.startsWith(directorio_url)) {
const remaining_url = requested_url.replace(directorio_url, "").replace(/^\//g, "");
const fichero_path = path.resolve(directorio, remaining_url);
if(!fichero_path.startsWith(directorio)) {
throw new Error("Required parameter «request.url» to result in a subfile of «directorio» in order to «Castelog.metodos.un_servicio_de_ficheros_estaticos»");
}
const reader = fs.createReadStream(fichero_path);
reader.pipe(response);
reader.on("error", function(error) {
if (typeof enFicherosNoEncontrados === "function") {
return enFicherosNoEncontrados(error, parametros);
}
});
} else {
if (typeof enOtrosCasos === "function") {
return enOtrosCasos();
}
}
} catch(error) {
if(typeof errores === "function") {
return errores(error, parametros);
}
}
};
//Included:lib/534.castelog.v1.metodos.un_texto_aleatorio.js
Castelog.metodos.un_texto_aleatorio = function(caracteres, alfabeto = Castelog.variables.alfabeto_ingles) {
if(typeof caracteres !== "number") {
throw new Error("Required argument «caracteres» to be a number in order to «Castelog.metodos.un_texto_aleatorio»");
}
if(caracteres <= 0) {
throw new Error("Required argument «caracteres» to be a more than 0 in order to «Castelog.metodos.un_texto_aleatorio»");
}
if(!Array.isArray(alfabeto)) {
throw new Error("Required argument «alfabeto» to be an array in order to «Castelog.metodos.un_texto_aleatorio»");
}
let output = "";
for(let index = 0; index < caracteres; index++) {
output += alfabeto[Math.floor(Math.random() * alfabeto.length)];
}
return output;
};
//Included:lib/534.castelog.v1.metodos.un_valor_aleatorio.js
Castelog.metodos.un_valor_aleatorio = function(lista) {
if(!Array.isArray(lista)) {
throw new Error("Required argument «lista» to be an array in order to «Castelog.metodos.un_valor_aleatorio«");
}
return lista[Math.floor(Math.random() * lista.length)];
};
//Included:lib/535.castelog.v1.metodos.un_servidor_activo_de_control_remoto.js
Castelog.metodos.un_servidor_activo_de_control_remoto = async function(configuraciones, directorio) {
try {
return new Castelog.variables.ServidorActivoDeControlRemoto(configuraciones, directorio);
} catch(error) {
console.log("Error al «Castelog.metodos.una_centralita_de_control_remoto()»:", error);
throw error;
}
};
//Included:lib/536.castelog.v1.metodos.un_servidor_pasivo_de_control_remoto.js
Castelog.metodos.un_servidor_pasivo_de_control_remoto = async function(configuraciones, directorio) {
try {
return new Castelog.variables.ServidorPasivoDeControlRemoto(configuraciones, directorio);
} catch(error) {
console.log("Error al «Castelog.metodos.una_centralita_de_control_remoto()»:", error);
throw error;
}
};
//Included:lib/537.castelog.v1.metodos.un_cliente_activo_de_control_remoto.js
Castelog.metodos.un_cliente_activo_de_control_remoto = async function (configuraciones, directorio) {
try {
return new Castelog.variables.ClienteActivoDeControlRemoto(configuraciones, directorio);
} catch (error) {
console.log("Error al «Castelog.metodos.un_cliente_activo_de_control_remoto()»:", error);
throw error;
}
};
//Included:lib/538.castelog.v1.metodos.un_cliente_pasivo_de_control_remoto.js
Castelog.metodos.un_cliente_pasivo_de_control_remoto = async function (configuraciones, directorio) {
try {
return new Castelog.variables.ClientePasivoDeControlRemoto(configuraciones, directorio);
} catch (error) {
console.log("Error al «Castelog.metodos.un_cliente_pasivo_de_control_remoto()»:", error);
throw error;
}
};
//Included:lib/539.castelog.v1.metodos.un_fichero_xml.js
Castelog.metodos.un_fichero_xml = async fichero => {
try {
const fs = require("fs");
const xml2js = require("xml2js");
const parser = new xml2js.Parser();
const data = await fs.promises.readFile(fichero, "utf8");
const result = await new Promise((ok, fail) => {
parser.parseString(data, function (error, result) {
if (error) {
return fail(error);
}
return ok(result);
});
});
return result;
} catch (error) {
console.log("Error al intentar «Castelog.metodos.un_fichero_xml»:", error);
console.log("Nota específica de error (1): recuerda que para usar «Castelog.metodos.un_fichero_xml» necesitas la dependencia «xml2js» en tu «node_modules»");
throw error;
}
};
//Included:lib/540.castelog.v1.metodos.un_escaneo_de_puertos.js
Castelog.metodos.un_escaneo_de_puertos = async (agente = "nmap", opciones = {}) => {
try {
if(agente === "nmap") {
const {
parametros = undefined,
salida = "result.xml",
directorio = process.cwd()
} = opciones;
const opciones_de_comando_por_defecto = parametros ? parametros : [
"-p1-65535",
"--packet-trace",
"-r",
"-vv",
"-dd",
"--reason",
"--osscan-guess",
"--script-trace",
"-sV",
"-oX",
"result.xml",
"127.0.0.1",
];
const opciones_de_comando = typeof opciones === "string" ? opciones : opciones_de_comando_por_defecto.concat(opciones);
await new Promise((ok, fail) => {
const spawn = require("child_process").spawn("nmap", opciones_de_comando, { cwd: directorio, stdio: ["inherit", "inherit", "inherit"] });
spawn.on("error", function(error) {
if(error) {
return fail(error);
}
});
spawn.on("exit", function (code) {
return ok(code);
});
spawn.on("data", function (chunk) {});
});
const ruta_resultados = require("path").resolve(__dirname, salida);
return await Castelog.metodos.un_fichero_xml(ruta_resultados);
} else {
throw new Error("Required argument «agente» to be a valid port scanner agent like 'nmap' in order to «Castelog.metodos.un_escaneo_de_puertos»");
}
} catch (error) {
console.log("Error al intentar «Castelog.metodos.un_escaneo_de_puertos»:", error);
console.log("(*) Nota específica de error (1): recuerda que para «Castelog.metodos.un_escaneo_de_puertos(...)» necesitas la dependencia «nmap» en tu sistema operativo");
console.log("(*) Nota específica de error (2): recuerda que para «Castelog.metodos.un_escaneo_de_puertos(...)» necesitas la dependencia «xml2js» en tu «node_modules»");
throw error;
}
};
//Included:lib/541.castelog.v1.metodos.un_monitoreo_de_red.js
Castelog.metodos.un_monitoreo_de_red = async (agente = "nmap", opciones, parametros_iniciales = undefined, fichero_resultados = "result.xml", directorio = process.cwd()) => {
try {
if(agente === "pcap") {
} else {
throw new Error("Required argument «agente» to be a valid network monirot agent like 'node:pcap' in order to «Castelog.metodos.un_monitoreo_de_red»");
}
} catch (error) {
console.log("Error al intentar «Castelog.metodos.un_monitoreo_de_red»:", error);
console.log("(*) Nota específica de error (1): recuerda que para «Castelog.metodos.un_monitoreo_de_red(...)» necesitas la dependencia «libpcap» en tu sistema operativo");
console.log("(*) Nota específica de error (2): recuerda que para «Castelog.metodos.un_monitoreo_de_red(...)» necesitas la dependencia «pcap» en tu «node_modules»");
console.log("(*) Nota específica de error (3): recuerda que para «Castelog.metodos.un_monitoreo_de_red(...)» necesitarás normalmente privilegios elevados en el dispositivo o «sudo node ~.js» debido al uso del modo promiscuo de la tarjeta de red");
throw error;
}
};
//Included:lib/542.castelog.v1.metodos.una_propiedad_para.js
Castelog.metodos.no_es_propietizable = objeto => (typeof objeto !== "object") && (typeof objeto !== "string") && (typeof objeto !== "function");
Castelog.metodos.no_tiene_propiedad = (objeto, propiedad) => Castelog.metodos.no_es_propietizable(objeto) || (typeof propiedad !== "string") || (!(propiedad in objeto));
Castelog.metodos.una_propiedad_para = async (propiedad, objeto, valor_por_defecto = undefined) => {
if(!Array.isArray(propiedad)) {
throw new Error("Required parameter «propiedad» to be an array in order to «Castelog.metodos.una_propiedad_para»");
}
let valor_pivote = objeto;
for(let index_propiedad = 0; index_propiedad < propiedad.length; index_propiedad++) {
const id_de_propiedad = propiedad[index_propiedad];
if(Castelog.metodos.no_tiene_propiedad(valor_pivote, id_de_propiedad)) return valor_por_defecto;
valor_pivote = valor_pivote[id_de_propiedad];
}
return valor_pivote;
};
//Included:lib/543.castelog.v1.metodos.siendo.js
Castelog.metodos.siendo = (base, filtros) => {
if(!Array.isArray(filtros)) {
throw new Error("Required parameter «filtros» to be an array in order to «Castelog.metodos.siendo»");
}
let salida = base;
for(let indexFiltros = 0; indexFiltros < filtros.length; indexFiltros++) {
const [filtro, parametros] = filtros[indexFiltros];
if(!(filtro in Castelog.variables.apendices_de_siendo)) {
throw new Error("Required filter «" + filtro + "» to be registered on «Castelog.variables.apendices_de_siendo» in order to «Castelog.metodos.siendo@" + filtro + "»");
}
const filtroFunction = Castelog.variables.apendices_de_siendo[filtro];
salida = filtroFunction(salida, parametros);
}
return salida;
};
//Included:lib/544.castelog.v1.metodos.una_espera_de.js
Castelog.metodos.una_espera_de = (tiempo, bloque) => {
if(typeof tiempo !== "number") {
throw new Error("Required parameter «tiempo» to be a number in order to «Castelog.metodos.una_espera_de");
}
if(typeof bloque !== "function") {
throw new Error("Required parameter «bloque» to be a function in order to «Castelog.metodos.una_espera_de");
}
return new Promise(ok => {
bloque();
setTimeout(() => {
try {
ok();
} catch(error) {
fail(error);
}
}, tiempo);
})
};
//Included:lib/545.castelog.v1.metodos.una_aplicacion_sintactica_universal.js
Castelog.metodos.una_aplicacion_sintactica_universal = (comandos, configuracion) => {
if(typeof comandos !== "object") {
throw new Error("Required parameter «comandos» to be an object in order to «Castelog.metodos.una_aplicacion_sintactica_universal»");
}
if(typeof configuracion !== "object") {
throw new Error("Required parameter «configuracion» to be an object in order to «Castelog.metodos.una_aplicacion_sintactica_universal»");
}
return new Castelog.variables.Aplicacion_sintactica_universal(comandos, configuracion);
};
//Included:lib/546.castelog.v1.metodos.un_punto_sintactico_universal.js
Castelog.metodos.un_punto_sintactico_universal = (comando) => {
if (typeof comando !== "function") {
throw new Error("Required parameter «comando» to be an function in order to «Castelog.metodos.un_punto_sintactico_universal»");
}
return new Castelog.variables.Punto_sintactico_universal(comando);
};
//Included:lib/547.castelog.v1.metodos.un_call_wait_map.js
Castelog.metodos.un_call_wait_map = function(promiseMapping, defaultObject = {}, args = []) {
// Collect:
const startedPromises = [];
const out = defaultObject;
// Collect:
for(const prop in promiseMapping) {
try {
const val = promiseMapping[prop];
let result = undefined;
if((typeof result === "function") && (result instanceof Promise)) {
const currentPromise = result.then(data => {
out[prop] = data;
return out;
});
startedPromises.push(currentPromise);
} else if(typeof val === "function") {
result = val(...args);
out[prop] = result;
} else {
result = val;
out[prop] = result;
}
} catch(error) {
console.log("Error en «Castelog.metodos.un_call_wait_map» índice «" + prop + "»:", error);
}
}
if(startedPromises.length) {
return Promise.all(startedPromises).then(data => out).catch(error => console.log("Error en «Castelog.metodos.un_call_wait_map» con una función-promesa:", error));
}
return out;
};
//Included:lib/550.castelog.v1.metodos.un_abstract_factory_design_pattern.js
Castelog.metodos.un_abstract_factory_design_pattern = function(data) {
// Collect:
const dp = {};
Object.assign(dp, {
abstractFactory: (dp) => ({ build(productParams) { return productParams; } }),
factories: (dp) => ({}),
products: (dp) => ({})
}, data);
// Make
Castelog.metodos.un_call_wait_map([
["products", dp.products()],
["factories", dp.factories()],
["abstractFactory", dp.abstractFactory()]
], dp);
dp.abstractFactory.createFactory = function (factoryParams = {}) {
if(typeof factoryParams !== "object") throw new Error("Required «factoryParams» to be an object in order to «Castelog.metodos.un_abstract_factory_design_pattern»");
if(typeof factoryParams.type !== "string") throw new Error("Required «factoryParams.type» to be a string in order to «Castelog.metodos.un_abstract_factory_design_pattern»");
if(!(factoryParams.type in dp.factories)) throw new Error("Required «factoryParams.type» to be a known factory class in order to «Castelog.metodos.un_abstract_factory_design_pattern»");
const factoryClass = dp.factories[factoryParams.type];
let factoryInstance = undefined;
if(typeof factoryClass === "object") { factoryInstance = Object.assign(factoryClass, factoryParams); }
else if(typeof factoryClass === "function") { factoryInstance = new factoryClass(factoryParams); }
else throw new Error("Required «factories." + factoryParams.type + "» to be an object or a class in order to «Castelog.metodos.un_abstract_factory_design_pattern»");
return factoryInstance;
};
dp.abstractFactory.createProduct = function (factoryParams = {}, productParams = {}) {
const factoryInstance = dp.abstractFactory.createFactory(factoryParams);
if(typeof factoryInstance !== "object") throw new Error("Required «new factories." + factoryParams.type + "(...)» to return an object in order to «Castelog.metodos.un_abstract_factory_design_pattern»");
if(typeof factoryInstance.build === "function") return factoryInstance.build(productParams);
return dp.abstractFactory.build(productParams);
};
// Use
return dp;
};
//Included:lib/550.castelog.v1.metodos.un_adapter_design_pattern.js
Castelog.metodos.un_adapter_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_bridge_design_pattern.js
Castelog.metodos.un_bridge_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_builder_design_pattern.js
Castelog.metodos.un_builder_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_chain_of_responsability_design_pattern.js
Castelog.metodos.un_chain_of_responsability_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_command_design_pattern.js
Castelog.metodos.un_command_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_composite_design_pattern.js
Castelog.metodos.un_composite_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_decorator_design_pattern.js
Castelog.metodos.un_decorator_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_facade_design_pattern.js
Castelog.metodos.un_facade_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_factory_method_design_pattern.js
Castelog.metodos.un_factory_method_design_pattern = function (data) {
// Collect:
const dp = {};
Object.assign(dp, {
factory: (dp) => {
return (name = "DefaultFactory", parameters = {}, buildParameters = {}, usingOop = true) => {
if(typeof name !== "string") throw new Error("Required parameter «name» to be a string in order to «Castelog.metodos.un_factory_method_design_pattern»");
if(typeof parameters !== "object") throw new Error("Required parameter «name» to be an object in order to «Castelog.metodos.un_factory_method_design_pattern»");
if(!(name in dp.classes)) throw new Error("Required parameter «name» to be a class known by «dp.classes» in order «Castelog.metodos.un_factory_method_design_pattern»");
const clazz = dp.classes[name];
let instanze = undefined;
if(usingOop === true) {
instanze = new clazz(parameters);
} else {
instanze = clazz(parameters);
}
if (typeof instanze.build === "function") {
return instanze.build(buildParameters);
}
return instanze;
};
},
classes: (dp) => {
return {};
},
products: (dp) => {
return {};
}
}, data);
// Consume && Format
return Castelog.metodos.un_call_wait_map([
["factory", dp.factory()],
["classes", dp.classes()],
["products", dp.products()]
], dp);
};
//Included:lib/550.castelog.v1.metodos.un_flyweight_design_pattern.js
Castelog.metodos.un_flyweight_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_hooks_design_pattern.js
Castelog.metodos.un_hooks_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_interpreter_design_pattern.js
Castelog.metodos.un_interpreter_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_iterator_design_pattern.js
Castelog.metodos.un_iterator_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_mediator_design_pattern.js
Castelog.metodos.un_mediator_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_memento_design_pattern.js
Castelog.metodos.un_memento_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_observer_design_pattern.js
Castelog.metodos.un_observer_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_progressive_composition_design_pattern.js
Castelog.metodos.un_progressive_composition_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_progressive_decoration_design_pattern.js
Castelog.metodos.un_progressive_decoration_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_prototype_design_pattern.js
Castelog.metodos.un_prototype_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_proxy_design_pattern.js
Castelog.metodos.un_proxy_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_singleton_design_pattern.js
Castelog.metodos.un_singleton_design_pattern = function(data) {
// Collect:
const dp = {};
Object.assign(dp, {
getter: (dp) => {
return () => {
if(typeof dp.value === "undefined") {
dp.setter();
}
return dp.value;
};
},
setter: (dp) => {
return () => {
dp.value = undefined;
}
},
value: (dp) => 500
}, data);
// Consume && Format
return Castelog.metodos.un_call_wait_map([
[ "value", dp.value() ],
[ "setter", dp.setter() ],
[ "getter", dp.getter() ]
], dp);
return dp;
};
//Included:lib/550.castelog.v1.metodos.un_state_design_pattern.js
Castelog.metodos.un_state_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_strategy_design_pattern.js
Castelog.metodos.un_strategy_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_template_method_design_pattern.js
Castelog.metodos.un_template_method_design_pattern = function(data) {
return {};
};
//Included:lib/550.castelog.v1.metodos.un_visitor_design_pattern.js
Castelog.metodos.un_visitor_design_pattern = function(data) {
return {};
};
//Included:lib/553.castelog.v1.metodos.un_componente_vue2.js
Castelog.metodos.un_componente_vue2 = function(id, plantilla, logica, estilos, parametros_de_estilos = {}) {
if(typeof window === "object") {
const vue_global = (typeof window.Vue !== "undefined") ? window.Vue :
(typeof window.vue !== "undefined") ? window.vue : undefined;
if(typeof vue_global === "undefined") {
throw new Error("Castelog no pudo encontrar Vue en el entorno vía 'window.vue' o 'window.Vue'");
}
const componente_base_original = { template: plantilla };
const definicion_logica_de_componente = logica ? logica(componente_base_original) : {};
const componente_base = Object.assign({}, componente_base_original, definicion_logica_de_componente);
const componente_clase_base = vue_global.component(id, componente_base);
const uniqueId = "castelog-style-tag-" + id;
const foundElement = document.getElementById(uniqueId);
if(estilos && !foundElement) {
const styleTag = document.createElement("style");
styleTag.id = uniqueId;
styleTag.textContent = Castelog.metodos.una_plantilla(estilos, {
estilo_uid: uniqueId,
componente: componente_base,
componente_id: id,
componente_clase: componente_clase_base,
...parametros_de_estilos,
})();
document.head.appendChild(styleTag);
}
return componente_clase_base;
} else if(typeof global === "object") {
return;
}
};
//Included:lib/554.castelog.v1.metodos.una_aplicacion_vue2.js
Castelog.metodos.una_aplicacion_vue2 = function (id, plantilla, logica, estilos, parametros_de_estilos = {}, rutas = [], traducciones = [], montada = null) {
if(typeof window === "object") {
const vue_global = (typeof window.Vue !== "undefined") ? window.Vue : (typeof window.vue !== "undefined") ? window.vue : undefined;
if(typeof vue_global === "undefined") {
throw new Error("Castelog no pudo encontrar Vue en el entorno vía 'window.vue' o 'window.Vue'");
}
if(typeof vue_global.prototype.$primera_app_vue_desde_castelog === "undefined") {
if(typeof VueI18next !== "undefined") {
vue_global.use(VueI18n);
}
}
const componente_base_original = { template: plantilla };
const definicion_logica_de_componente = logica ? logica(componente_base_original) : {};
const componente_base = Object.assign({}, componente_base_original, definicion_logica_de_componente);
const uniqueId = "castelog-style-tag-" + id;
const foundElement = document.getElementById(uniqueId);
if(estilos && (!foundElement)) {
const styleTag = document.createElement("style");
styleTag.id = uniqueId;
styleTag.textContent = Castelog.metodos.una_plantilla(estilos, {
estilo_uid: uniqueId,
componente: componente_base,
componente_id: id,
...parametros_de_estilos,
})();
document.head.appendChild(styleTag);
}
// const userPreferredLocales = window.navigator.languages;
// const localeIds = Object.keys(traducciones);
// let currentLocale = "en";
// for(let indexLocales = 0; indexLocales < userPreferredLocales.length; indexLocales++) {
// const userPreferredLocale = userPreferredLocales[indexLocales];
// const userPreferredIso = userPreferredLocale.split("-")[0];
// const localePosition = localeIds.indexOf(userPreferredIso);
// if (localePosition !== -1) {
// currentLocale = localeIds[localePosition];
// }
// }
// i18next.init({
// lng: currentLocale,
// nsSeparator: "#<1>#",
// keySeparator: "#<2>#",
// pluralSeparator: "#<3>#",
// contextSeparator: "#<4>#",
// resources: traducciones ? Object.keys(traducciones).reduce(function(out, key) {
// if(!(key in out)) {
// out[key] = {
// translation: traducciones[key]
// };
// }
// return out;
// }, {}) : {}
// });
const vue_global_parameters = {...componente_base};
if(Array.isArray(rutas) && rutas.length) {
if(typeof vue_global.prototype.$primera_app_vue_desde_castelog === "undefined") {
vue_global_parameters.router = new VueRouter({
routes: rutas
});
} else {
throw new Error("Una segunda app vue no permite definir rutas específicas.");
}
}
// if(!("$i18n" in vue_global.prototype)) {
// vue_global_parameters.i18n = new VueI18next(i18next);
// }
const instancia_base = new vue_global(vue_global_parameters);
if(typeof(montada) === "string") {
instancia_base.$mount(montada);
} else {
console.log("[!] Aplicación Vue2 no montada.");
console.log(" [+] montada:", montada);
console.log(" [+] id:", id);
console.log(" [+] plantilla:", plantilla);
console.log(" [+] logica:", logica);
console.log(" [+] estilos:", estilos);
console.log(" [+] rutas:", rutas);
console.log(" [+] traducciones:", traducciones);
}
vue_global.prototype.$primera_app_vue_desde_castelog = instancia_base;
return instancia_base;
} else if(typeof global === "object") {
return;
}
};
//Included:lib/555.castelog.v1.vue.componentes_vue2_nativos.js
//Included:lib/560.castelog.v1.metodos.un_numero_textual.js
Castelog.metodos.un_numero_textual = function(numeroTextual) {
// @TOOVERRIDE:
return numeroTextual;
};
//Included:lib/561.castelog.v1.metodos.un_sistema_rest.js
Castelog.metodos.un_sistema_rest = function(configuraciones, configuracionesServer, donde, tipo, enError) {
if(typeof configuraciones !== "object") {
throw new Error("Required parameter «configuraciones» to be an object in order to «un_sistema_rest»");
}
if(typeof configuracionesServer !== "object") {
throw new Error("Required parameter «configuracionesServer» to be an object in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.adapter !== "string") {
configuracionesServer.adapter = "dexie";
}
let ServerClass = undefined;
if(configuracionesServer.adapter === "mysql") {
if(configuraciones.platform !== "node") {
throw new Error("Required parameter «configuracionesServer.adapter» to be compatible with «configuracionesApi.platform» in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials !== "object") {
throw new Error("Required parameter «configuracionesServer.credentials» to be an object in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials.user !== "string") {
throw new Error("Required parameter «configuracionesServer.credentials.user» to be an string in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials.password !== "string") {
throw new Error("Required parameter «configuracionesServer.credentials.password» to be an string in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials.host !== "string") {
throw new Error("Required parameter «configuracionesServer.credentials.host» to be an string in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials.port !== "number") {
throw new Error("Required parameter «configuracionesServer.credentials.port» to be an number in order to «un_sistema_rest»");
}
if(typeof configuracionesServer.credentials.database !== "string") {
throw new Error("Required parameter «configuracionesServer.credentials.database» to be an string in order to «un_sistema_rest»");
}
} else if(configuracionesServer.adapter === "dexie") {
if (configuraciones.platform !== "browser") {
configuraciones.platform = "browser";
}
} else {
throw new Error("Required parameter «configuraciones.adapter» to be a known type ('dexie','mysql') in order to «un_sistema_rest»");
}
const RestAPI = Castelog.variables.Automatic_http_rest_api_interface(configuraciones);
if (configuracionesServer.adapter === "dexie") {
ServerClass = RestAPI.VirtualDataServer;
} else if (configuracionesServer.adapter === "mysql") {
ServerClass = RestAPI.DataServer;
} else {
throw new Error("Required parameter «configuraciones.adapter» to be a known type ('dexie','mysql') in order to «un_sistema_rest»");
}
return ServerClass.initialize(configuracionesServer).then(serverInstance => {
Object.assign(serverInstance, {
create(options) {
return {
instanceType: "standard",
select(modelo, filtrando, ordenando, agrupando, paginando, bd, adaptador, objetivo) {
if(objetivo === "a un ítem") {
return serverInstance.rest.selectOne(modelo, {
where: filtrando ? filtrando : []
});
} else if (objetivo === "a varios ítems") {
return serverInstance.rest.selectMany(modelo, {
where: filtrando ? filtrando : [],
order: ordenando ? ordenando : [],
groups: agrupando ? agrupando : [],
pagination: paginando ? paginando : [1, 20]
});
} else if (objetivo === "al primer ítem") {
return serverInstance.rest.selectFirst(modelo, {
where: filtrando ? filtrando : [],
order: ordenando ? ordenando : [],
groups: agrupando ? agrupando : [],
pagination: paginando ? paginando : [1, 20]
});
} else if (objetivo === "al último ítem") {
return serverInstance.rest.selectLast(modelo, {
where: filtrando ? filtrando : [],
order: ordenando ? ordenando : [],
groups: agrupando ? agrupando : [],
pagination: paginando ? paginando : [1, 20]
});
} else {
throw new Error("Required argument «motivo» to be an identifiable string in order to «select»");
}
},
insert(modelo, valores) {
return serverInstance.rest.insertMany(modelo, {
items: Array.isArray(valores) ? valores : [valores]
});
},
update(modelo, filtrando, valores) {
return serverInstance.rest.updateMany(modelo, {
where: filtrando,
values: valores
});
},
delete(modelo, filtrando) {
return serverInstance.rest.deleteMany(modelo, {
where: filtrando
});
}
};
}
});
if(typeof donde === "function") {
return (async () => {
try {
await donde(serverInstance);
return serverInstance;
} catch(error) {
if (typeof enError === "function") {
return enError(error, RestAPI, serverInstance);
}
}
});
}
return serverInstance;
}).catch(error => {
if(typeof enError === "function") {
return enError(error, RestAPI);
}
});
};
//Included:lib/562.castelog.v1.metodos.un_diagrama_conceptual.js
Castelog.metodos.termino_el_programa = function(...args) {
debugar_sintaxis_de_diagramas(...args);
process.exit(0);
};
Castelog.variables.DiagramaConceptualPorDefecto = function () {
debugar_sintaxis_de_diagramas("Entro en: Castelog.variables.DiagramaConceptualPorDefecto");
this.codigo = {
cabeceras: "",
pieceras: "",
nodos: "",
relaciones: ""
};
this.sentencias = [];
this.toMermaidCode = () => {
return this.codigo.cabeceras + "\n" + this.codigo.nodos + "\n" + this.codigo.relaciones + "\n" + this.codigo.pieceras;
};
return this;
};
Castelog.variables.ContextoDeDiagramaConceptual = function (id_original, extra) {
debugar_sintaxis_de_diagramas("Entro en: Castelog.variables.ContextoDeDiagramaConceptual");
let id = id_original;
if(id_original instanceof Castelog.variables.ContextoDeDiagramaConceptual) {
id = id_original.id;
}
if(!Array.isArray(id)) {
throw new Error("Required argument «id» to be an array in order to «Castelog.variables.ContextoDeDiagramaConceptual»");
}
this.id = id;
if(typeof extra === "string") {
this.id = this.id.concat(extra);
} else if(typeof extra === "undefined") {
// @OK"
} else {
throw new Error("Required argument «extra» to be a string or undefined in order to «Castelog.variables.ContextoDeDiagramaConceptual»");
}
return this;
};
Castelog.variables.ContextoDeDiagramaConceptual.prototype = {};
Castelog.variables.ContextoDeDiagramaConceptual.prototype.tabulacion = function() {
let tab = "";
for(let index = 0; index < this.id.length; index++) {
const id_item = this.id[index];
tab += " ";
}
return tab;
};
Castelog.variables.DiagramaConceptualSeleccionado = Castelog.variables.DiagramaConceptualPorDefecto;
Castelog.variables.configuraciones_de_constructor_de_diagramas = { debug: false };
const debugar_sintaxis_de_diagramas = function(...args) {
if(Castelog.variables.configuraciones_de_constructor_de_diagramas.debug) {
console.log(...args);
}
};
const comprobar_objeto_de_diagrama = function(method, diagrama) {
debugar_sintaxis_de_diagramas("Entro en: comprobar_objeto_de_diagrama");
debugar_sintaxis_de_diagramas("OK en:" + method);
if(!(diagrama instanceof Castelog.variables.DiagramaConceptualSeleccionado)) {
throw new Error("Required argument «diagrama» to be an instance of «Castelog.variables.DiagramaConceptualSeleccionado» in order to «" + method + "»");
}
};
const comprobar_contexto_de_diagrama = function (method, contexto) {
debugar_sintaxis_de_diagramas("Entro en: comprobar_contexto_de_diagrama");
debugar_sintaxis_de_diagramas("OK en:" + method);
if(!(contexto instanceof Castelog.variables.ContextoDeDiagramaConceptual)) {
throw new Error("Required argument «contexto» to be an instance of «Castelog.variables.ContextoDeDiagramaConceptual» in order to «" + method + "»");
}
};
const comprobar_valor_de_diagrama = function (method, valor) {
debugar_sintaxis_de_diagramas("Entro en: comprobar_valor_de_diagrama");
debugar_sintaxis_de_diagramas("OK en:" + method);
if (typeof valor !== "object") {
throw new Error("Required argument «valor» to be an object in order to «" + method + "»");
}
};
Castelog.metodos.un_diagrama_conceptual = async function(datos_de_diagrama, en_errores) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.un_diagrama_conceptual");
if (typeof datos_de_diagrama !== "function") {
throw new Error("Required argument «datos_de_diagrama» to be a function in order to «Castelog.metodos.un_diagrama_conceptual»");
}
const diagrama_objeto = new Castelog.variables.DiagramaConceptualSeleccionado();
const contexto_de_diagrama = new Castelog.variables.ContextoDeDiagramaConceptual([]);
await datos_de_diagrama(diagrama_objeto, contexto_de_diagrama);
return diagrama_objeto;
} catch(error) {
if(typeof en_errores === "function") {
return en_errores(error);
}
throw error;
}
};
Castelog.metodos.defino_direccion_de_diagrama = async function(diagrama, valor) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_direccion_de_diagrama");
comprobar_objeto_de_diagrama("Castelog.metodos.defino_direccion_de_diagrama", diagrama);
diagrama.codigo.cabeceras += "graph ";
switch (valor) {
case "izquierda a derecha":
diagrama.codigo.cabeceras += "LR;\n";
break;
case "derecha a izquierda":
diagrama.codigo.cabeceras += "RL;\n";
break;
case "arriba a abajo":
diagrama.codigo.cabeceras += "TB;\n";
break;
case "abajo a arriba":
diagrama.codigo.cabeceras += "BT;\n";
break;
default:
throw new Error("Required argument «valor» to be recognized on «Castelog.metodos.defino_direccion_de_diagrama»");
}
diagrama.sentencias.push({ tipo: "dirección de diagrama", valor });
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_direccion_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_nodo_de_diagrama = async function(diagrama, valor, contexto) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_nodo_de_diagrama");
debugar_sintaxis_de_diagramas("defino_nodo_de_diagrama", diagrama, valor, contexto);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_nodo_de_diagrama", diagrama);
comprobar_contexto_de_diagrama("Castelog.metodos.defino_nodo_de_diagrama", contexto);
comprobar_valor_de_diagrama("Castelog.metodos.defino_nodo_de_diagrama", valor);
const { nombre } = valor;
let { texto } = valor;
if (typeof nombre !== "string") {
throw new Error("Required argument «nombre» to be a string in order to «Castelog.metodos.defino_nodo_de_diagrama»");
}
if(!("texto" in valor)) {
texto = nombre;
}
if (typeof texto !== "string") {
throw new Error("Required argument «texto» to be a string in order to «Castelog.metodos.defino_nodo_de_diagrama»");
}
const abre_grupo = "[";
const cierra_grupo = "]";
diagrama.codigo.nodos += `${contexto.tabulacion()}${nombre}${abre_grupo}${JSON.stringify(texto)}${cierra_grupo};\n`;
diagrama.sentencias.push({ tipo: "nodo de diagrama", valor, contexto });
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_nodo_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_relacion_de_diagrama = async function(diagrama, valor) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_relacion_de_diagrama");
debugar_sintaxis_de_diagramas("defino_relacion_de_diagrama", diagrama, valor);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_relacion_de_diagrama", diagrama);
comprobar_valor_de_diagrama("Castelog.metodos.defino_relacion_de_diagrama", valor);
const { origen, texto, destino } = valor;
if (typeof origen !== "string") {
throw new Error("Required argument «origen» to be a string in order to «Castelog.metodos.defino_relacion_de_diagrama»");
}
if (typeof texto !== "string") {
throw new Error("Required argument «texto» to be a string in order to «Castelog.metodos.defino_relacion_de_diagrama»");
}
if (typeof destino !== "string") {
throw new Error("Required argument «destino» to be a string in order to «Castelog.metodos.defino_relacion_de_diagrama»");
}
const abre_relacion = "-- ";
const cierra_relacion = " -->";
diagrama.codigo.relaciones += `${origen} ${abre_relacion}${texto}${cierra_relacion} ${destino}\n`;
diagrama.sentencias.push({ tipo: "relación de diagrama", valor });
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_relacion_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_conjunto_de_diagrama = async function(diagrama, valor, contexto) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_conjunto_de_diagrama");
debugar_sintaxis_de_diagramas("defino_conjunto_de_diagrama", diagrama, valor, contexto);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_conjunto_de_diagrama", diagrama);
comprobar_contexto_de_diagrama("Castelog.metodos.defino_conjunto_de_diagrama", contexto);
comprobar_valor_de_diagrama("Castelog.metodos.defino_conjunto_de_diagrama", valor);
const { nombre, callback } = valor;
if (typeof nombre !== "string") {
throw new Error("Required argument «nombre» to be a string in order to «Castelog.metodos.defino_conjunto_de_diagrama»");
}
if(typeof callback !== "function") {
throw new Error("Required argument «callback» to be a function in order to «Castelog.metodos.defino_conjunto_de_diagrama»");
}
const nuevo_contexto = new Castelog.variables.ContextoDeDiagramaConceptual(contexto, nombre);
diagrama.sentencias.push({ tipo: "conjunto de diagrama", valor, contexto });
diagrama.codigo.nodos += `${contexto.tabulacion()}subgraph ${nombre}:\n`;
await callback(diagrama, nuevo_contexto);
diagrama.codigo.nodos += `${contexto.tabulacion()}end\n`;
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_conjunto_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_clase_de_diagrama = async function(diagrama, valor) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_clase_de_diagrama");
debugar_sintaxis_de_diagramas("defino_clase_de_diagrama", diagrama, valor);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_clase_de_diagrama", diagrama);
comprobar_valor_de_diagrama("Castelog.metodos.defino_clase_de_diagrama", valor);
const { nombre, relleno = "#FFF", grosor = "1px", borde = "#333" } = valor;
if(typeof nombre !== "string") {
throw new Error("Required argument «nombre» to be a string in order to «Castelog.metodos.defino_clase_de_diagrama»");
}
if (typeof relleno !== "string") {
throw new Error("Required argument «relleno» to be a string in order to «Castelog.metodos.defino_clase_de_diagrama»");
}
if (typeof grosor !== "string") {
throw new Error("Required argument «grosor» to be a string in order to «Castelog.metodos.defino_clase_de_diagrama»");
}
if (typeof borde !== "string") {
throw new Error("Required argument «borde» to be a string in order to «Castelog.metodos.defino_clase_de_diagrama»");
}
diagrama.sentencias.push({ tipo: "clase de diagrama", valor });
diagrama.codigo.pieceras += `classDef ${nombre} fill:${relleno},stroke:${borde},stroke-width:${grosor}\n`;
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_clase_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_clasificacion_de_diagrama = async function(diagrama, valor) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_clasificacion_de_diagrama");
debugar_sintaxis_de_diagramas("defino_clasificacion_de_diagrama", diagrama, valor);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_clasificacion_de_diagrama", diagrama);
comprobar_valor_de_diagrama("Castelog.metodos.defino_clasificacion_de_diagrama", valor);
const { nombre, nodos } = valor;
if (typeof nombre !== "string") {
throw new Error("Required argument «nombre» to be a string in order to «Castelog.metodos.defino_clasificacion_de_diagrama");
}
if (!Array.isArray(nodos)) {
throw new Error("Required argument «nodos» to be an array in order to «Castelog.metodos.defino_clasificacion_de_diagrama");
}
for(let index = 0; index < nodos.length; index++) {
const nodo = nodos[index];
diagrama.codigo.pieceras += `class ${nombre} ${nodo}\n`;
diagrama.sentencias.push({ tipo: "clasificación de diagrama", valor });
}
} catch(error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_clasificacion_de_diagrama»:", error);
throw error;
}
};
Castelog.metodos.defino_estrategias_de_diagrama = async function(diagrama, valor) {
try {
debugar_sintaxis_de_diagramas("Entro en: Castelog.metodos.defino_estrategias_de_diagrama");
debugar_sintaxis_de_diagramas("defino_estrategias_de_diagrama", diagrama, valor);
comprobar_objeto_de_diagrama("Castelog.metodos.defino_estrategias_de_diagrama", diagrama);
comprobar_valor_de_diagrama("Castelog.metodos.defino_estrategias_de_diagrama", valor);
} catch (error) {
debugar_sintaxis_de_diagramas("Error on «Castelog.metodos.defino_estrategias_de_diagrama»:", error);
throw error;
}
};
//Included:lib/562.castelog.v1.metodos.un_diagrama_de_dependencias.js
Castelog.variables.Gestor_de_dependencia = class {
static create(...args) {
return new this(...args);
}
constructor(dependencies, scope) {
this.data = [];
this.dependencies = dependencies;
this.scope = scope;
this.find = {
one: this.$find_one,
};
this.append = this.$append;
this.config = {
tipo: this.$from_scope_to_tipo(scope)
};
}
$find_one(filter) {
const result = this.data.filter(filter);
if (result.length === 0) throw new Error("Required parameter «filter» to result in any match on «" + this.scope + "» in order to «Castelog.variables.Gestor_de_dependencia.find_one»");
if (result.length !== 1) throw new Error("Required parameter «filter» to result in a match of only one item on «" + this.scope + "» in order to «Castelog.variables.Gestor_de_dependencia.find_one»");
return result[0];
}
$append() {
const sentence = {
tipo: this.config.tipo,
item,
};
this.data.push(sentence);
this.dependencies.sentences.push(sentence);
}
$from_scope_to_tipo(scope) {
return scope === "packages" ? "defino paquete" :
scope === "classes" ? "defino clase" :
scope === "objects" ? "defino objeto" :
scope === "functions" ? "defino función" :
scope === "factories" ? "defino fábrica" :
scope === "variables" ? "defino variable" :
scope === "constants" ? "defino constante" :
scope === "ui_components" ? "defino componente UI" :
scope === "ui_applications" ? "defino aplicación UI" :
false;
}
};
Castelog.variables.Sistema_de_dependencias_de_software = class {
static create(...args) {
return new this(...args);
}
constructor() {
this.sentences = Castelog.variables.Gestor_de_dependencia.create(this, "sentences");
this.packages = Castelog.variables.Gestor_de_dependencia.create(this, "packages");
this.classes = Castelog.variables.Gestor_de_dependencia.create(this, "classes");
this.objects = Castelog.variables.Gestor_de_dependencia.create(this, "objects");
this.functions = Castelog.variables.Gestor_de_dependencia.create(this, "functions");
this.factories = Castelog.variables.Gestor_de_dependencia.create(this, "factories");
this.variables = Castelog.variables.Gestor_de_dependencia.create(this, "variables");
this.constants = Castelog.variables.Gestor_de_dependencia.create(this, "constants");
this.ui = {
components: Castelog.variables.Gestor_de_dependencia.create(this, "ui_components"),
applications: Castelog.variables.Gestor_de_dependencia.create(this, "ui_applications")
};
this.to = {
validation: () => {
try {
} catch(error) {
throw error;
}
},
project: async (basepath = ".") => {
try {
const basedir = require("path").resolve(basepath);
const state = { dependencies: this, basedir, sentences: [], index: -1 };
for (let indexSentence = 0; indexSentence < this.sentences.data.length; indexSentence++) {
state.index = indexSentence;
const sentence = this.sentences.data[indexSentence];
const result = await this.de_sentencia_a_proyecto(sentence, state);
state.sentences.push(result);
}
return result;
} catch (error) {
throw error;
}
}
};
}
async de_sentencia_a_proyecto(sentence, state) {
try {
let result = false;
if (false) {
} else if (sentence.tipo === "defino paquete") {
// @TODO...
} else if (sentence.tipo === "defino clase") {
// @TODO...
} else if (sentence.tipo === "defino objeto") {
// @TODO...
} else if (sentence.tipo === "defino función") {
// @TODO...
} else if (sentence.tipo === "defino fábrica") {
// @TODO...
} else if (sentence.tipo === "defino variable") {
// @TODO...
} else if (sentence.tipo === "defino constante") {
// @TODO...
} else if (sentence.tipo === "defino componente UI") {
// @TODO...
} else if (sentence.tipo === "defino aplicación UI") {
// @TODO...
} else throw new Error("Required property «tipo» to be identificable in order to «Castelog.variables.Gestor_de_dependencia.to.project»");
return result;
} catch (error) {
throw error;
}
}
};
Castelog.metodos.un_diagrama_de_dependencias = function(diagrama) {
};
//Included:lib/562.castelog.v1.metodos.utilidades_del_dom.js
Castelog.metodos.una_seleccion_de_elementos_del_dom = function(parametros, base) {
if(typeof parametros !== "string") {
throw new Error("Required parameter «parametros» to be a string (a css selector) in order to «Castelog.metodos.una_seleccion_de_elementos_del_dom»");
}
if(typeof base === "string") {
base = document.querySelector(base);
}
if(!(base instanceof HTMLElement)) {
throw new Error("Required parameter «base» to a string (a css selector) matching at least 1 element or an instance of HTMLElement in order to «Castelog.metodos.una_seleccion_de_elementos_del_dom»");
}
return Array.from(base.querySelectorAll(parametros));
};
Castelog.metodos.una_seleccion_del_primer_elemento_del_dom = function(parametros, base) {
if (typeof parametros !== "string") {
throw new Error("Required parameter «parametros» to be a string (a css selector) in order to «Castelog.metodos.una_seleccion_del_primer_elemento_del_dom»");
}
if (typeof base === "string") {
base = document.querySelector(base);
}
if (!(base instanceof HTMLElement)) {
throw new Error("Required parameter «base» to a string (a css selector) matching at least 1 element or an instance of HTMLElement in order to «Castelog.metodos.una_seleccion_del_primer_elemento_del_dom»");
}
return base.querySelector(parametros);
};
Castelog.metodos.una_insercion_de_estilos_en_cascada = function(id, contenidos) {
const PROPERTY = "data-identificador-de-estilo-en-cascada-de-castelog";
const matches = Array.from(document.head.querySelectorAll(`style`)).filter(item => {
const id_elemento = item.getAttribute(PROPERTY);
return id === id_elemento;
});
if(matches.length) {
return false;
}
const styleTag = document.createElement("style");
styleTag.setAttribute(PROPERTY, id);
styleTag.textContent = contenidos;
document.head.appendChild(styleTag);
};
Castelog.metodos.un_bloque_de_estilos_en_cascada = function(bloque_de_texto) {
return bloque_de_texto;
};
Castelog.metodos.una_insercion_de_elemento_del_dom = function(selector, base, elemento_html) {
if(typeof base === "string") {
base = Array.from(document.querySelectorAll(base));
}
if (base === null) {
base = [document.body];
}
if(base instanceof HTMLElement) {
base = [ base ];
}
if(!Array.isArray(base)) {
throw new Error("Required parameter «base» to result a css selection as an array in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
if(base.length === 0) {
throw new Error("Required parameter «base» to be css selection matching minimum 1 element in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
if(base.length > 1) {
throw new Error("Required parameter «base» to be css selection matching maximum 1 element in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
base = base[0];
if(!(base instanceof HTMLElement)) {
throw new Error("Required parameter «base» to result an instance of HTMLElement in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
if (typeof selector !== "string") {
throw new Error("Required parameter «selector» to be a string in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
const selection = base.querySelectorAll(selector);
if(selection.length === 0) {
throw new Error("Required parameter «selector» to match minimum 1 element in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
if(selection.length > 1) {
throw new Error("Required parameter «selector» to match maximum 1 element in order to «Castelog.metodos.una_insercion_de_elemento_del_dom»");
}
const selected = selection[0];
selected.appendChild(elemento_html);
return [selected, elemento_html];
};
Castelog.metodos.un_elemento_jquery = function(...parametros) {
if(typeof jQuery !== "function") {
throw new Error("Required «jQuery» library to be loaded in order to «Castelog.metodos.un_elemento_jquery»");
}
return jQuery(...parametros);
};
//Included:lib/563.castelog.v1.metodos.un_formateo_de_fecha.js
Castelog.variables.formato_de_fecha_por_defecto = "YYYY/MM/DD HH:mm:ss.xxx";
Castelog.metodos.un_formateo_de_fecha = function (fecha = new Date(), formato = Castelog.variables.formato_de_fecha_por_defecto, direccion = "un formateo de fecha a texto") {
const maxLength = Castelog.variables.formato_de_fecha_por_defecto.length;
const minLength = "ss".length;
if(typeof formato === "undefined") {
formato = Castelog.variables.formato_de_fecha_por_defecto;
}
if(formato === null) {
formato = Castelog.variables.formato_de_fecha_por_defecto;
}
if(direccion === "un formateo de fecha a texto") {
if(typeof formato !== "string") {
throw new Error("Required parameter «formato» to be a string while «direccion» is «un formateo de fecha a texto» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(formato.length > maxLength) {
throw new Error("Required parameter «formato» to be greater than «" + maxLength + "» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(formato.length < minLength) {
throw new Error("Required parameter «formato» to be greater than «" + minLength + "» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(!(fecha instanceof Date)) {
throw new Error("Required parameter «fecha» to be an instance of Date in order while «direccion» is «un formateo de fecha a texto» to «Castelog.metodos.un_formateo_de_fecha»");
}
return formato
.replace("YYYY", Castelog.metodos.un_relleno_de_texto(fecha.getFullYear(), 4, "0"))
.replace("MM", Castelog.metodos.un_relleno_de_texto(fecha.getMonth() + 1, 2, "0"))
.replace("DD", Castelog.metodos.un_relleno_de_texto(fecha.getDate(), 2, "0"))
.replace("HH", Castelog.metodos.un_relleno_de_texto(fecha.getHours(), 2, "0"))
.replace("mm", Castelog.metodos.un_relleno_de_texto(fecha.getMinutes(), 2, "0"))
.replace("ss", Castelog.metodos.un_relleno_de_texto(fecha.getSeconds(), 2, "0"))
.replace("xxx", Castelog.metodos.un_relleno_de_texto(fecha.getMilliseconds(), 3, "0"));
} else if(direccion === "un formateo de texto a fecha") {
if (typeof formato !== "string") {
throw new Error("Required parameter «formato» to be a string while «direccion» is «un formateo de texto a fecha» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(formato.length > maxLength) {
throw new Error("Required parameter «formato» to be greater than «" + maxLength + "» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(formato.length < minLength) {
throw new Error("Required parameter «formato» to be greater than «" + minLength + "» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if (typeof fecha !== "string") {
throw new Error("Required parameter «fecha» to be a string while «direccion» is «un formateo de texto a fecha» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
if(fecha.length < minLength) {
throw new Error("Required parameter «fecha» to be greater than «" + minLength + "» in order to «Castelog.metodos.un_formateo_de_fecha»");
}
let nueva_fecha = new Date();
nueva_fecha.setHours(0);
nueva_fecha.setMinutes(0);
nueva_fecha.setSeconds(0);
nueva_fecha.setMilliseconds(0);
ExtractingDatePart: {
const matchedPosition = formato.indexOf("YYYY");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 4);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setFullYear(date_part_int);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("MM");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 2);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setMonth(date_part_int - 1);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("DD");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 2);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setDate(date_part_int);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("HH");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 2);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setHours(date_part_int);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("mm");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 2);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setMinutes(date_part_int);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("ss");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 2);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setSeconds(date_part_int);
}
ExtractingDatePart: {
const matchedPosition = formato.indexOf("xxx");
if(matchedPosition === -1) break ExtractingDatePart;
const date_part = fecha.substring(matchedPosition, matchedPosition + 3);
const date_part_int = parseInt(date_part);
if(date_part) nueva_fecha.setMilliseconds(date_part_int);
}
return nueva_fecha;
}
};
//Included:lib/564.castelog.v1.metodos.un_relleno_de_texto.js
Castelog.metodos.un_relleno_de_texto = function(texto, longitud = 2, relleno = "0", por_el_principio = true) {
if(typeof longitud !== "number") {
throw new Error("Required parameter «longitud» to be a number in order to «Castelog.metodos.un_relleno_de_texto»");
}
if(typeof relleno !== "string") {
throw new Error("Required parameter «relleno» to be a string in order to «Castelog.metodos.un_relleno_de_texto»");
}
let salida = "" + texto;
while(salida.length < longitud) {
if(por_el_principio) {
salida = relleno + salida;
} else {
salida = salida + relleno;
}
}
return salida;
};
//Included:lib/565.castelog.v1.metodos.un_dia_de_la_semana.js
Castelog.metodos.un_dia_de_la_semana = function(base) {
if(typeof base === "string") {
const baseLower = base.toLowerCase();
if (baseLower === "lunes") { return 1 }
else if (baseLower === "martes") { return 2 }
else if (baseLower === "miércoles") { return 3 }
else if (baseLower === "jueves") { return 4 }
else if (baseLower === "viernes") { return 5 }
else if (baseLower === "sábado") { return 6 }
else if (baseLower === "domingo") { return 0 }
else throw new Error("Required parameter «base» to be a valid week day when string in order to «Castelog.metodos.un_dia_de_la_semana»");
}
if(base instanceof Date) {
base = base.getDay();
}
if(typeof base === "number") {
if (base === 0) { return "Domingo" }
else if (base === 1) { return "Lunes" }
else if (base === 2) { return "Martes" }
else if (base === 3) { return "Miércoles" }
else if (base === 4) { return "Jueves" }
else if (base === 5) { return "Viernes" }
else if (base === 6) { return "Sábado" }
else throw new Error("Required parameter «base» to be a valid number when number in order to «Castelog.metodos.un_dia_de_la_semana»");
}
throw new Error("Required parameter «base» to be a valid type (string, number or date) in order to «Castelog.metodos.un_dia_de_la_semana»");
};
//Included:lib/566.castelog.v1.metodos.un_nombre_de_mes.js
Castelog.metodos.un_nombre_de_mes = function(base) {
let mes = base;
if(base instanceof Date) {
mes = base.getMonth();
}
if(typeof base === "number") {
mes = base;
}
if(typeof base === "string") {
mes = parseInt(base);
}
if(typeof mes !== "number") {
throw new Error("Required parameter «base» to be an instance of Date, a string or a number in order to «Castelog.metodos.un_nombre_de_mes»");
}
if(mes === 0) return "Enero";
if(mes === 1) return "Febrero";
if(mes === 2) return "Marzo";
if(mes === 3) return "Abril";
if(mes === 4) return "Mayo";
if(mes === 5) return "Junio";
if(mes === 6) return "Julio";
if(mes === 7) return "Agosto";
if(mes === 8) return "Setiembre";
if(mes === 9) return "Octubre";
if(mes === 10) return "Noviembre";
if(mes === 11) return "Diciembre";
throw new Error("Required parameter «base» to be a number between 1 and 11 in order to «Castelog.metodos.un_nombre_de_mes»");
};
//Included:lib/567.castelog.v1.metodos.una_comunicacion_de_entrada_de_usuario.js
Castelog.metodos.una_comunicacion_de_entrada_de_usuario = function (componente, atributos = {}, eventos = {}) {
if(typeof Vue === "undefined") {
throw new Error("Required global «Vue» to be defined in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
if(typeof Vue.prototype === "undefined") {
throw new Error("Required global «Vue.prototype» to be defined in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
if(typeof Vue.prototype.$comunicaciones.una_entrada_de_usuario === "undefined") {
throw new Error("Required global «Vue.prototype.una_comunicacion_de_entrada_de_usuario» to be defined in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
if(typeof componente !== "string") {
throw new Error("Required argument «componente» to be a string in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
if(typeof atributos !== "object") {
throw new Error("Required argument «atributos» to be a object in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
if(typeof eventos !== "object") {
throw new Error("Required argument «eventos» to be a object in order to «Castelog.metodos.una_comunicacion_de_entrada_de_usuario»");
}
return Vue.prototype.$comunicaciones.una_entrada_de_usuario(componente, atributos, eventos);
};
//Included:lib/568.castelog.v1.metodos.una_comunicacion_de_salida_a_usuario.js
Castelog.metodos.una_comunicacion_de_salida_a_usuario = function (componente, atributos = {}, eventos = {}) {
if(typeof Vue === "undefined") {
throw new Error("Required global «Vue» to be defined in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
if(typeof Vue.prototype === "undefined") {
throw new Error("Required global «Vue.prototype» to be defined in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
if(typeof Vue.prototype.$comunicaciones.una_salida_a_usuario === "undefined") {
throw new Error("Required global «Vue.prototype.una_comunicacion_de_salida_a_usuario» to be defined in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
if(typeof componente !== "string") {
throw new Error("Required argument «componente» to be a string in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
if(typeof atributos !== "object") {
throw new Error("Required argument «atributos» to be a object in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
if(typeof eventos !== "object") {
throw new Error("Required argument «eventos» to be a object in order to «Castelog.metodos.una_comunicacion_de_salida_a_usuario»");
}
return Vue.prototype.$comunicaciones.una_salida_a_usuario(componente, atributos, eventos);
};
//Included:lib/999.finalizacion.part.js
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////// Aquí termina el script de Castelog //
////////////////////////////////////////////////////////////////////////////////
Castelog.metodos.analizo_sistema = function() {
try {
console.log("JEI!");
} catch(error) {
console.log("Error al analizar el sistema: " + error);
console.log(error);
}
};
( async () => {
await Castelog.metodos.analizo_sistema({
});})();